instruction_seed stringlengths 29 40.5k | source stringclasses 6
values |
|---|---|
Please explain the following problem in detail and provide code in Swift:
Given `n` orders, each order consist in pickup and delivery services.
Count all valid pickup/delivery possible sequences such that delivery(i) is always after of pickup(i).
Since the answer may be too large, return it modulo 10^9 + 7.
**Exampl... | dolphin |
Please focus on the algorithm of this problem and provide code in python:
A binary tree is given such that each node contains an additional random pointer which could point to any node in the tree or null.
Return a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) of the tree.
The tree is repres... | dolphin |
Please focus on the algorithm of this problem and provide code in Elixir:
There is a **1-based** binary matrix where `0` represents land and `1` represents water. You are given integers `row` and `col` representing the number of rows and columns in the matrix, respectively.
Initially on day `0`, the **entire** matrix ... | dolphin |
translate this code from Lisp to F#:
```lisp
(defun earliest-blooms (plant-time grow-time)
(let ((n (length plant-time))
(process-time (mapcar #'list plant-time grow-time))
(day 0)
(blooms 0))
(dolist (p (sort process-time #'< :key #'first))
(incf day (first p))
(setf blooms (m... | dolphin |
Please write the following solution using ANSI C:
Given an integer `n`, your task is to count how many strings of length `n` can be formed under the following rules:
* Each character is a lower case vowel (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`)
* Each vowel `'a'` may only be followed by an `'e'`.
* Each vowel `'e'` ... | dolphin |
convert this code to python:
```smalltalk
| nums k n sum mp |
checkSubarraySum: nums k
n := nums size.
sum := 0.
mp := Dictionary new.
mp at: 0 put: -1.
1 to: n do: [:i |
sum := sum + (nums at: i).
sum := k = 0 ifTrue: [sum] ifFalse: [sum \\ k].
(mp includesKey: sum) ifTrue: ... | dolphin |
Please focus on the functionality of this problem and provide code in Ruby:
You are given a string `number` representing a **positive integer** and a character `digit`.
Return _the resulting string after removing **exactly one occurrence** of_ `digit` _from_ `number` _such that the value of the resulting string in **d... | dolphin |
Please explain the reasoning behind the following solution and provide code in Ruby:
There are `n` uniquely-sized sticks whose lengths are integers from `1` to `n`. You want to arrange the sticks such that **exactly** `k` sticks are **visible** from the left. A stick is **visible** from the left if there are no **longe... | dolphin |
Please explain the following problem in detail and provide code in Lua:
Given two **sorted 0-indexed** integer arrays `nums1` and `nums2` as well as an integer `k`, return _the_ `kth` _(**1-based**) smallest product of_ `nums1[i] * nums2[j]` _where_ `0 <= i < nums1.length` _and_ `0 <= j < nums2.length`.
**Example 1:**... | dolphin |
port this code to Erlang:
```pascal
function MaxProductDifference(nums: array of Integer): Integer;
var
max1, max2, min1, min2: Integer;
i: Integer;
begin
max1 := -10001;
max2 := -10001;
min1 := 10001;
min2 := 10001;
for i := Low(nums) to High(nums) do
begin
if nums[i] > max1 then
begin
m... | dolphin |
port this code to PHP:
```c
#include <stdio.h>
void singleNumber(int* nums, int numsSize, int* n1, int* n2){
int xor_all = 0;
for (int i = 0; i < numsSize; i++){
xor_all ^= nums[i];
}
int bit = xor_all & -xor_all;
*n1 = 0;
*n2 = 0;
for (int i = 0; i < numsSize; i++){
if (nu... | dolphin |
Please explain the following problem in detail and provide code in F#:
We will use a file-sharing system to share a very large file which consists of `m` small **chunks** with IDs from `1` to `m`.
When users join the system, the system should assign **a unique** ID to them. The unique ID should be used **once** for ea... | dolphin |
Please explain the following problem in detail and provide code in Lisp:
Given an integer array `nums` with possible **duplicates**, randomly output the index of a given `target` number. You can assume that the given target number must exist in the array.
Implement the `Solution` class:
* `Solution(int[] nums)` Ini... | dolphin |
Please explain the following problem in detail and provide code in Ruby:
A sequence is **special** if it consists of a **positive** number of `0`s, followed by a **positive** number of `1`s, then a **positive** number of `2`s.
* For example, `[0,1,2]` and `[0,0,1,1,1,2]` are special.
* In contrast, `[2,1,0]`, `[1]... | dolphin |
Please explain the reasoning behind the following solution and provide code in Object Pascal:
There is a broken calculator that has the integer `startValue` on its display initially. In one operation, you can:
* multiply the number on display by `2`, or
* subtract `1` from the number on display.
Given two integer... | dolphin |
Please write the following solution using R:
There are `k` workers who want to move `n` boxes from an old warehouse to a new one. You are given the two integers `n` and `k`, and a 2D integer array `time` of size `k x 4` where `time[i] = [leftToRighti, pickOldi, rightToLefti, putNewi]`.
The warehouses are separated by ... | dolphin |
Please explain the reasoning behind the following solution and provide code in Clojure:
You are given the `head` of a linked list, which contains a series of integers **separated** by `0`'s. The **beginning** and **end** of the linked list will have `Node.val == 0`.
For **every** two consecutive `0`'s, **merge** all t... | dolphin |
Please explain the reasoning behind the following solution and provide code in Kotlin:
You are given an array `nums` of positive integers and a **positive** integer `k`.
A subset of `nums` is **beautiful** if it does not contain two integers with an absolute difference equal to `k`.
Return _the number of **non-empty ... | dolphin |
Please explain the reasoning behind the following solution and provide code in Perl:
You are given an integer `n`, which indicates that there are `n` courses labeled from `1` to `n`. You are also given an array `relations` where `relations[i] = [prevCoursei, nextCoursei]`, representing a prerequisite relationship betwe... | dolphin |
port this code from Scheme to Ruby:
```scheme
(define (largest-square-subgrid grid)
(define n (length grid))
(define m (length (car grid)))
(define ans 0)
(do ((i 0 (+ i 1)))
((>= i n))
(do ((j 0 (+ j 1)))
((>= j m))
(if (or (= i 0) (= j 0) (= i (- n 1)) (= j (- m 1)))
(set! an... | dolphin |
Please explain the reasoning behind the following solution and provide code in F#:
Design a Leaderboard class, which has 3 functions:
1. `addScore(playerId, score)`: Update the leaderboard by adding `score` to the given player's score. If there is no player with such id in the leaderboard, add him to the leaderboard ... | dolphin |
convert this code from Elixir to Scheme:
```elixir
defmodule Solution do
def minimum_number_of_subsequences(nums, k) do
freqs = %{}
for num <- nums do
if freqs[num - k] > 0 do
freqs[num - k] -= 1
freqs[num] = freqs[num] || 0 + 1
else
freqs[num] = freqs[num] || 0 + 1
... | dolphin |
convert this code to Scheme:
```groovy
import groovy.transform.CompileStatic
@CompileStatic
def minAbsoluteSumDiff(nums1, nums2) {
def n = nums1.size()
def total = 0
def max_diff = 0
def mod = 10**9 + 7
def sorted_nums1 = nums1.sort()
for (int i = 0; i < n; i++) {
def diff = (nums1[i] ... | dolphin |
port this code from Perl to Elixir:
```perl
use strict;
use warnings;
sub number_of_ways {
my ($hats) = @_;
my $MOD = 10**9 + 7;
my $max_hat = 40;
# define a map of person to preferred hats
my %hat_map;
for my $i (0 .. @$hats - 1) {
for my $j (0 .. @{$hats->[$i]} - 1) {
pu... | dolphin |
Please explain the following problem in detail and provide code in Fortran:
You are given a **0-indexed** array `nums` consisting of positive integers, representing targets on a number line. You are also given an integer `space`.
You have a machine which can destroy targets. **Seeding** the machine with some `nums[i]`... | dolphin |
port this code from Object Pascal to Erlang:
```
function IntegerBreak(n: Integer): Integer;
var
product: Integer;
begin
if n <= 3 then
Exit(n - 1);
product := 1;
while n > 4 do
begin
product := product * 3;
n := n - 3;
end;
Result := product * n;
end;
``` | dolphin |
Please explain the reasoning behind the following solution and provide code in R:
This is an **interactive problem**.
There is a robot in a hidden grid, and you are trying to get it from its starting cell to the target cell in this grid. The grid is of size `m x n`, and each cell in the grid is either empty or blocked... | dolphin |
Please explain the reasoning behind the following solution and provide code in Mojo:
Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie.
Each child `i` has a greed factor `g[i]`, which is the minimum size of a cookie that the child will be c... | dolphin |
Please write the following solution using java:
You are given an integer `n`.
Each number from `1` to `n` is grouped according to the sum of its digits.
Return _the number of groups that have the largest size_.
**Example 1:**
**Input:** n = 13
**Output:** 4
**Explanation:** There are 9 groups in total, they are gro... | dolphin |
port this code to Rust:
```haskell
cellRange :: String -> [String]
cellRange s = sort [c : show r | c <- [c1..c2], r <- [r1..r2]]
where r1 = read [s !! 1] :: Int
r2 = read [s !! 4] :: Int
c1 = ord (s !! 0) - ord 'A' + 1
c2 = ord (s !! 3) - ord 'A' + 1
``` | dolphin |
port this code to c++:
```perl
sub numberToWords {
my ($num) = @_;
if ($num == 0) {
return "Zero";
}
my @LESS_THAN_20 = ("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "... | dolphin |
Please explain the following problem in detail and provide code in Fortran:
You have `n` jobs and `m` workers. You are given three arrays: `difficulty`, `profit`, and `worker` where:
* `difficulty[i]` and `profit[i]` are the difficulty and the profit of the `ith` job, and
* `worker[j]` is the ability of `jth` work... | dolphin |
convert this code to C#:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char **readBinaryWatch(int turnedOn, int *returnSize) {
*returnSize = 0;
char **times = (char **)malloc(300 * sizeof(char *));
for (int h = 0; h < 12; h++) {
for (int m = 0; m < 60; m++) {
int bits ... | dolphin |
port this code from Objective-C to Groovy:
```
FOLLOWING-OCCURRENCES(nums, key):
counter = {}
max_target = -1
max_count = -1
for i = 0 to nums.length - 2:
if nums[i] == key:
if nums[i+1] not in counter:
counter[nums[i+1]] = 1
else:
counter... | dolphin |
port this code from Erlang to Lisp:
```erlang
fence(Trees) ->
Trees1 = lists:sort(fun(X, Y) -> X < Y end, Trees),
fence(Trees1, []).
fence([], Acc) -> Acc;
fence([P|T], Acc) ->
Acc1 = insert(P, Acc),
fence(T, Acc1).
insert(P, [P1, P2 |T]) when cross_product(P1, P2, P) < 0 ->
insert(P, [P2|T]);
ins... | dolphin |
Please explain the following problem in detail and provide code in PHP:
In a string `s` of lowercase letters, these letters form consecutive groups of the same character.
For example, a string like `s = "abbxxxxzyy "` has the groups `"a "`, `"bb "`, `"xxxx "`, `"z "`, and `"yy "`.
A group is identified by an interval... | dolphin |
Please write the following solution using Elixir:
You are given a **strictly increasing** integer array `rungs` that represents the **height** of rungs on a ladder. You are currently on the **floor** at height `0`, and you want to reach the last rung.
You are also given an integer `dist`. You can only climb to the nex... | dolphin |
Please focus on the algorithm of this problem and provide code in Dart:
Given an integer array `nums` where the elements are sorted in **ascending order**, convert _it to a_ **_height-balanced_** _binary search tree_.
**Example 1:**
**Input:** nums = \[-10,-3,0,5,9\]
**Output:** \[0,-3,9,-10,null,5\]
**Explanation:**... | dolphin |
Please explain the reasoning behind the following solution and provide code in Scheme:
A shop is selling candies at a discount. For **every two** candies sold, the shop gives a **third** candy for **free**.
The customer can choose **any** candy to take away for free as long as the cost of the chosen candy is less than... | dolphin |
Please focus on the functionality of this problem and provide code in Visual Basic .NET:
Given an `n x n` integer matrix `grid`, return _the minimum sum of a **falling path with non-zero shifts**_.
A **falling path with non-zero shifts** is a choice of exactly one element from each row of `grid` such that no two eleme... | dolphin |
translate this code to javascript:
```
-module(solution).
-export([get_max_safe_minutes/1]).
-define(DX, [0, 1, 0, -1]).
-define(DY, [1, 0, -1, 0]).
get_max_safe_minutes(Grid) ->
{M, N} = {length(Grid), length(hd(Grid))},
Dist = lists:duplicate(M, lists:duplicate(N, -1)),
Q = queue:new(),
case lists:... | dolphin |
Please write the following solution using R:
You are given a string `allowed` consisting of **distinct** characters and an array of strings `words`. A string is **consistent** if all characters in the string appear in the string `allowed`.
Return _the number of **consistent** strings in the array_ `words`.
**Example ... | dolphin |
Please explain the reasoning behind the following solution and provide code in Perl:
Given the `root` of a binary tree and an integer `targetSum`, return _all **root-to-leaf** paths where the sum of the node values in the path equals_ `targetSum`_. Each path should be returned as a list of the node **values**, not node... | dolphin |
Please explain the reasoning behind the following solution and provide code in Julia:
You are given a positive integer `n`, that is initially placed on a board. Every day, for `109` days, you perform the following procedure:
* For each number `x` present on the board, find all numbers `1 <= i <= n` such that `x % i ... | dolphin |
port this code from Objective-C to Rust:
```objective-c
- (NSArray<NSNumber *> *)largestLexSequence:(int)n {
NSMutableArray<NSNumber *> *res = [NSMutableArray arrayWithCapacity:n];
for (int i = 0; i < n; i++) {
[res addObject:@(i % 2)];
}
return [res copy];
}
``` | dolphin |
Please write the following solution using java:
In a binary tree, a **lonely** node is a node that is the only child of its parent node. The root of the tree is not lonely because it does not have a parent node.
Given the `root` of a binary tree, return _an array containing the values of all lonely nodes_ in the tree.... | dolphin |
port this code to Erlang:
```lisp
(defun construct-bst (preorder)
(if (null preorder)
nil
(let ((root (make-instance 'tree-node :val (first preorder))))
(loop :for i :from 1 :below (length preorder)
:when (< (aref preorder i) (tree-node-val root))
:do (setf (tree-node-l... | dolphin |
Please focus on the algorithm of this problem and provide code in java:
Given a **0-indexed** integer array `nums`, return _the number of subarrays of_ `nums` _having an even product_.
**Example 1:**
**Input:** nums = \[9,6,7,13\]
**Output:** 6
**Explanation:** There are 6 subarrays with an even product:
- nums\[0..1... | dolphin |
convert this code to Dart:
```cpp
class AllOne {
public:
unordered_map<string, int> data;
void inc(string key) {
data[key]++;
}
void dec(string key) {
if (data[key] > 0) data[key]--;
if (data[key] == 0) data.erase(key);
}
string getMaxKey() {
if (data.empty()) ret... | dolphin |
Please explain the following problem in detail and provide code in PHP:
Given a string `s` consisting only of characters _a_, _b_ and _c_.
Return the number of substrings containing **at least** one occurrence of all these characters _a_, _b_ and _c_.
**Example 1:**
**Input:** s = "abcabc "
**Output:** 10
**Explana... | dolphin |
port this code from Fortran to Lua:
```Fortran
function digit_sum(n)
implicit none
integer, intent(in) :: n
integer :: digit_sum, digit
digit_sum = 0
do while (n > 0)
digit = n % 10
digit_sum = digit_sum + digit
n = n / 10
end do
digit_sum = digit_sum
end function
fu... | dolphin |
Please write the following solution using Clojure:
A `width x height` grid is on an XY-plane with the **bottom-left** cell at `(0, 0)` and the **top-right** cell at `(width - 1, height - 1)`. The grid is aligned with the four cardinal directions ( `"North "`, `"East "`, `"South "`, and `"West "`). A robot is **initiall... | dolphin |
translate this code to c++:
```julia
function max_prizes(prize_positions::Vector{Int}, k::Int)::Int
n = length(prize_positions)
ans = 0
for i in 1:n
left_segment_end = prize_positions[i] + k
right_segment_start = searchsortedlast(prize_positions, left_segment_end)
right_segment_end =... | dolphin |
convert this code to F#:
```scala
def anagramOperations(words: Array[String]): Array[String] = {
var i = 1
while (i < words.length) {
val word1 = words(i).sorted
val word2 = words(i - 1).sorted
if (word1 == word2) {
words(i) = null
} else {
i += 1
... | dolphin |
Please explain the following problem in detail and provide code in Lisp:
There are `n` servers numbered from `0` to `n - 1` connected by undirected server-to-server `connections` forming a network where `connections[i] = [ai, bi]` represents a connection between servers `ai` and `bi`. Any server can reach other servers... | dolphin |
Please focus on the functionality of this problem and provide code in ANSI C:
There are `n` houses evenly lined up on the street, and each house is beautifully painted. You are given a **0-indexed** integer array `colors` of length `n`, where `colors[i]` represents the color of the `ith` house.
Return _the **maximum**... | dolphin |
port this code to python:
```c
#include <stdio.h>
#include <string.h>
int maxProduct(char **words, int wordsSize){
int i, j, k, max_product = 0, mask[wordsSize];
memset(mask, 0, sizeof(mask));
for(i = 0; i < wordsSize; i++){
for(j = 0; j < strlen(words[i]); j++){
mask[i] |= (1 << (words... | dolphin |
Please explain the following problem in detail and provide code in Perl:
You are given an integer array `bloomDay`, an integer `m` and an integer `k`.
You want to make `m` bouquets. To make a bouquet, you need to use `k` **adjacent flowers** from the garden.
The garden consists of `n` flowers, the `ith` flower will b... | dolphin |
Please explain the reasoning behind the following solution and provide code in F#:
Given a `m x n` binary matrix `mat`. In one step, you can choose one cell and flip it and all the four neighbors of it if they exist (Flip is changing `1` to `0` and `0` to `1`). A pair of cells are called neighbors if they share one edg... | dolphin |
Please explain the reasoning behind the following solution and provide code in Clojure:
Alice has `n` candies, where the `ith` candy is of type `candyType[i]`. Alice noticed that she started to gain weight, so she visited a doctor.
The doctor advised Alice to only eat `n / 2` of the candies she has (`n` is always even... | dolphin |
Please focus on the efficiency of this problem and provide code in Perl:
There is a street with `n * 2` **plots**, where there are `n` plots on each side of the street. The plots on each side are numbered from `1` to `n`. On each plot, a house can be placed.
Return _the number of ways houses can be placed such that no... | dolphin |
Please explain the reasoning behind the following solution and provide code in Object Pascal:
Given two strings `s` and `goal`, return `true` _if you can swap two letters in_ `s` _so the result is equal to_ `goal`_, otherwise, return_ `false`_._
Swapping letters is defined as taking two indices `i` and `j` (0-indexed)... | dolphin |
port this code from Kotlin to ANSI C:
```kotlin
fun reverse(x: Int): Int {
var rev = 0
var num = x
while (num != 0) {
rev = rev * 10 + num % 10
num /= 10
}
return rev
}
fun countSquareTriples(n: Int): Int {
val MOD = 1_000_000_007
val count = hashMapOf<Int, Int>()
var re... | dolphin |
Please focus on the algorithm of this problem and provide code in Scala:
You are given a binary string `binary` consisting of only `0`'s or `1`'s. You can apply each of the following operations any number of times:
* Operation 1: If the number contains the substring `"00 "`, you can replace it with `"10 "`.
* ... | dolphin |
Please explain the following problem in detail and provide code in javascript:
Given the `root` of a binary tree, find the maximum value `v` for which there exist **different** nodes `a` and `b` where `v = |a.val - b.val|` and `a` is an ancestor of `b`.
A node `a` is an ancestor of `b` if either: any child of `a` is e... | dolphin |
translate this code to R:
```dart
int basketballTeamScore(List<int> scores, List<int> ages) {
int n = scores.length;
List<Tuple<int, int>> players = List<Tuple<int, int>>.generate(
n, (i) => Tuple<int, int>(scores[i], ages[i]));
players.sort((a, b) => b.item1.compareTo(a.item1));
List<int> dp = List<int>.... | dolphin |
Please explain the reasoning behind the following solution and provide code in java:
Given a string `s`, reverse the string according to the following rules:
* All the characters that are not English letters remain in the same position.
* All the English letters (lowercase or uppercase) should be reversed.
Return... | dolphin |
Please explain the following problem in detail and provide code in javascript:
There are `n` cities labeled from `1` to `n`. You are given the integer `n` and an array `connections` where `connections[i] = [xi, yi, costi]` indicates that the cost of connecting city `xi` and city `yi` (bidirectional connection) is `cost... | dolphin |
Please explain the reasoning behind the following solution and provide code in java:
Given a **0-indexed** integer array `nums` of size `n`, find the **maximum difference** between `nums[i]` and `nums[j]` (i.e., `nums[j] - nums[i]`), such that `0 <= i < j < n` and `nums[i] < nums[j]`.
Return _the **maximum difference*... | dolphin |
port this code to python:
```lua
function countArrangement(n)
local function helper(idx, visited)
if idx > n then
return 1
end
local count = 0
for i = 1, n do
if not visited[i] and (idx % i == 0 or i % idx == 0) then
visited[i] = true
... | dolphin |
port this code to java:
```lua
function cherryPickup(grid)
local function dp(r1, c1, c2)
local r2 = r1 + c1 - c2
if r1 == #grid or r2 == #grid or c1 == #grid or c2 == #grid or
grid[r1+1][c1+1] == -1 or grid[r2+1][c2+1] == -1 then
return -math.huge
elseif r1 == #grid-1... | dolphin |
Please explain the reasoning behind the following solution and provide code in R:
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
**Example 1:**
**Input:** head = \[1,2,3,4... | dolphin |
Please focus on the algorithm of this problem and provide code in Scheme:
Given four integers `sx`, `sy`, `tx`, and `ty`, return `true` _if it is possible to convert the point_ `(sx, sy)` _to the point_ `(tx, ty)` _through some operations__, or_ `false` _otherwise_.
The allowed operation on some point `(x, y)` is to c... | dolphin |
translate this code from Perl to Groovy:
```perl
sub BITWISE_AND_SIZE {
my ($candidates) = @_;
my $n = scalar(@$candidates);
my $max_size = 0;
for (my $i = 0; $i < 2**$n; $i++) {
my $bitwise_and = $candidates->[0];
my $size = 1;
for (my $j = 1; $j < $n; $j++) {
if (... | dolphin |
port this code from Fortran to TypeScript:
```fortran
function new21Game(n, k, maxPts) result(ans)
integer, intent(in) :: n, k, maxPts
real :: dp(n+1), s, ans
integer :: i
if (k == 0 .or. n >= k + maxPts) then
ans = 1.0
return
endif
dp(1) = 1.0
s = 1.0
do i = 2, n+1
... | dolphin |
convert this code to Ruby:
```objective-c
NSInteger minOperations(NSArray<NSNumber *> *nums) {
NSInteger operations = 0;
NSMutableArray<NSNumber *> *mutableNums = [nums mutableCopy];
for (NSInteger i = 1; i < mutableNums.count; i++) {
if (mutableNums[i].integerValue <= mutableNums[i - 1].integerValu... | dolphin |
convert this code from Swift to javascript:
```swift
func getFolderNames(_ names: [String]) -> [String] {
var folders = [String](repeating: "", count: names.count)
var count = [String: Int]()
for i in 0..<names.count {
let curr = names[i]
if count[curr] == nil {
folders[i] =... | dolphin |
Please explain the following problem in detail and provide code in Scala:
Given an `m x n` `picture` consisting of black `'B'` and white `'W'` pixels and an integer target, return _the number of **black** lonely pixels_.
A black lonely pixel is a character `'B'` that located at a specific position `(r, c)` where:
* ... | dolphin |
Please explain the reasoning behind the following solution and provide code in Rust:
Given a binary tree with the following rules:
1. `root.val == 0`
2. If `treeNode.val == x` and `treeNode.left != null`, then `treeNode.left.val == 2 * x + 1`
3. If `treeNode.val == x` and `treeNode.right != null`, then `treeNode.ri... | dolphin |
Please explain the following problem in detail and provide code in javascript:
Given a string `s` containing only lowercase English letters and the `'?'` character, convert **all** the `'?'` characters into lowercase letters such that the final string does not contain any **consecutive repeating** characters. You **can... | dolphin |
Please explain the following problem in detail and provide code in R:
A sequence of numbers is called **arithmetic** if it consists of at least two elements, and the difference between every two consecutive elements is the same. More formally, a sequence `s` is arithmetic if and only if `s[i+1] - s[i] == s[1] - s[0]` f... | dolphin |
Please focus on the functionality of this problem and provide code in Erlang:
There is a rooted tree consisting of `n` nodes numbered `0` to `n - 1`. Each node's number denotes its **unique genetic value** (i.e. the genetic value of node `x` is `x`). The **genetic difference** between two genetic values is defined as t... | dolphin |
Please write the following solution using Rust:
You are given an integer array `nums`. You want to maximize the number of points you get by performing the following operation any number of times:
* Pick any `nums[i]` and delete it to earn `nums[i]` points. Afterwards, you must delete **every** element equal to `nums... | dolphin |
translate this code from C# to TypeScript:
```csharp
public class Solution {
public int FindSpecialInteger(int[] arr) {
int n = arr.Length;
int interval = n / 4;
for (int i = 0; i < n - interval; i++) {
if (arr[i] == arr[i + interval]) {
return arr[i];
... | dolphin |
convert this code from Julia to Dart:
```julia
function convert(s::AbstractString, numRows::Int)::AbstractString
if numRows == 1 || numRows >= length(s)
return s
end
rows = fill("", numRows)
curRow = 1
goingDown = false
for c in s
rows[curRow] *= c
if curRow == ... | dolphin |
Please focus on the efficiency of this problem and provide code in Go:
Given an integer array `nums`, return _the largest perimeter of a triangle with a non-zero area, formed from three of these lengths_. If it is impossible to form any triangle of a non-zero area, return `0`.
**Example 1:**
**Input:** nums = \[2,1,2... | dolphin |
Please write the following solution using F#:
The thief has found himself a new place for his thievery again. There is only one entrance to this area, called `root`.
Besides the `root`, each house has one and only one parent house. After a tour, the smart thief realized that all houses in this place form a binary tree... | dolphin |
Please focus on the algorithm of this problem and provide code in TypeScript:
You are given an integer array `nums` of **even** length `n` and an integer `limit`. In one move, you can replace any integer from `nums` with another integer between `1` and `limit`, inclusive.
The array `nums` is **complementary** if for a... | dolphin |
convert this code to R:
```python
def maximum_binary_string(binary: str) -> str:
zero_count = binary.count('0')
if zero_count <= 1:
return binary
one_count = len(binary) - zero_count
result = "1" * one_count + "0" * (zero_count - 1) + "1####1"
return result[:len(binary)]
```
| dolphin |
Please focus on the algorithm of this problem and provide code in TypeScript:
In MATLAB, there is a handy function called `reshape` which can reshape an `m x n` matrix into a new one with a different size `r x c` keeping its original data.
You are given an `m x n` matrix `mat` and two integers `r` and `c` representing... | dolphin |
Please write the following solution using python:
Given a string `s` and an integer `k`, reverse the first `k` characters for every `2k` characters counting from the start of the string.
If there are fewer than `k` characters left, reverse all of them. If there are less than `2k` but greater than or equal to `k` chara... | dolphin |
Please focus on the functionality of this problem and provide code in Lisp:
Given `head`, the head of a linked list, determine if the linked list has a cycle in it.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the `next` pointer. Internally, `p... | dolphin |
convert this code to Objective-C:
```csharp
public class Solution {
public int LastStoneWeightII(int[] stones) {
int sum = stones.Sum();
int n = stones.Length;
bool[,] dp = new bool[n + 1, sum / 2 + 1];
dp[0, 0] = true;
for (int i = 1; i <= n; i++) {
for (int j = ... | dolphin |
Please explain the following problem in detail and provide code in F#:
The **alternating sum** of a **0-indexed** array is defined as the **sum** of the elements at **even** indices **minus** the **sum** of the elements at **odd** indices.
* For example, the alternating sum of `[4,2,5,3]` is `(4 + 5) - (2 + 3) = 4`.... | dolphin |
convert this code from PHP to Swift:
```php
function orderOfLargestPlusSign($n, $mines) {
if ($n == 1 && count($mines) == 1 && $mines[0][0] == 0 && $mines[0][1] == 0) {
return 0;
}
$grid = array_fill(0, $n, array_fill(0, $n, 1));
foreach ($mines as $mine) {
$grid[$mine[0]][$mine[1]]... | dolphin |
Please explain the reasoning behind the following solution and provide code in Object Pascal:
Given the `root` of a binary tree, return all **duplicate subtrees**.
For each kind of duplicate subtrees, you only need to return the root node of any **one** of them.
Two trees are **duplicate** if they have the **same str... | dolphin |
Please explain the reasoning behind the following solution and provide code in c++:
You have a graph of `n` nodes labeled from `0` to `n - 1`. You are given an integer n and a list of `edges` where `edges[i] = [ai, bi]` indicates that there is an undirected edge between nodes `ai` and `bi` in the graph.
Return `true` ... | dolphin |
translate this code to java:
```erlang
find_kth_number(N, K) ->
NumList = lists:seq(1, N),
SortedList = lists:sort(fun(A, B) -> lists:concat([integer_to_list(A), integer_to_list(B)]) < lists:concat([integer_to_list(B), integer_to_list(A)]) end, NumList),
lists:nth(K, SortedList).
``` | dolphin |
Please write the following solution using Object Pascal:
We have an array of integers, `nums`, and an array of `requests` where `requests[i] = [starti, endi]`. The `ith` request asks for the sum of `nums[starti] + nums[starti + 1] + ... + nums[endi - 1] + nums[endi]`. Both `starti` and `endi` are _0-indexed_.
Return _... | dolphin |
port this code to Kotlin:
```groovy
import java.util.*
def largestComponentSize(nums) {
def n = nums.size()
def uf = new UnionFind(n)
def factors = new HashMap<Integer, Integer[]>()
def primes = sieve(100000)
for (int i = 0; i < n; ++i) {
int num = nums[i], p = -1
for (int j = 0; j... | dolphin |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.