instruction_seed stringlengths 29 40.5k | source stringclasses 6
values |
|---|---|
convert this code to TypeScript:
```vb
Private Function LongestSubstring(ByVal s As String, ByVal k As Integer) As Integer
If String.IsNullOrEmpty(s) OrElse k <= 0 Then
Return 0
End If
Dim char_count As New Dictionary(Of Char, Integer)
For Each ch As Char In s
If Not char_count.Cont... | dolphin |
translate this code from Clojure to F#:
```clojure
(defn min-swaps-couples [row]
(let [n (count row)
position (vec (repeat n 0))]
(doseq [i (range n)]
(aset position (nth row i) i))
(loop [swaps 0 i 0]
(if (< i n)
(let [partner (if (= 0 (mod (nth row i) 2)))
... | dolphin |
translate this code from javascript to Rust:
```javascript
function queensAttacktheKing(queens, king) {
const result = [];
for (let x = -1; x <= 1; x++) {
for (let y = -1; y <= 1; y++) {
if (x === 0 && y === 0) continue;
let posX = king[0] + x;
let posY = king[1] + y;... | dolphin |
convert this code from Lisp to Object Pascal:
```lisp
(defun distinct-rows-from (nums)
(let ((rows '()))
(dolist (num nums)
(let ((inserted nil))
(dolist (row rows)
(when (not (member num row))
(push num row)
(setf inserted t)
(return-from row)))
... | dolphin |
translate this code to PHP:
```groovy
def shortestDistance(wordsDict, word1, word2) {
def index1 = -1
def index2 = -1
def minDistance = Integer.MAX_VALUE
for (int i = 0; i < wordsDict.size(); i++) {
if (wordsDict[i] == word1) {
index1 = i
}
if (wordsDict[i] == word2) ... | dolphin |
Please explain the following problem in detail and provide code in F#:
You are playing a Flip Game with your friend.
You are given a string `currentState` that contains only `'+'` and `'-'`. You and your friend take turns to flip **two consecutive** `"++ "` into `"-- "`. The game ends when a person can no longer make ... | dolphin |
convert this code from ANSI C to Lua:
```
#include <stdio.h>
#define MOD 1000000007
long long minNonZeroProduct(int p) {
long long prod = 1;
long long a = (1LL << p) - 2;
long long b = (1LL << p) - 1;
b %= MOD;
while (a > 0) {
if (a & 1) {
prod = (prod * b) % MOD;
}... | dolphin |
Please explain the reasoning behind the following solution and provide code in python:
You are given an `m x n` binary `grid`, where each `1` represents a brick and `0` represents an empty space. A brick is **stable** if:
* It is directly connected to the top of the grid, or
* At least one other brick in its four ... | dolphin |
Please write the following solution using Scala:
You are given a string `s` that contains some bracket pairs, with each pair containing a **non-empty** key.
* For example, in the string `"(name)is(age)yearsold "`, there are **two** bracket pairs that contain the keys `"name "` and `"age "`.
You know the values of a... | dolphin |
port this code to Fortran:
```php
function visiblePoints($points, $angle, $location) {
$visible_points = 0;
foreach ($points as $p) {
$x = $p[0] - $location[0];
$y = $p[1] - $location[1];
if ($x == 0 && $y == 0) {
$visible_points += 1;
} elseif ($x == 0) {
... | dolphin |
port this code to Kotlin:
```ruby
def maximize_number(n, x)
nums = n.chars.map(&:to_i)
pos = nums.index(nums.min)
pos -= 1 if nums.first.negative?
nums.insert(pos + 1, x)
nums.join.to_i.to_s
end
``` | dolphin |
translate this code to Julia:
```objectivec
-(int)maxSubArray:(NSArray<NSNumber*>*)nums {
int max_sum = [nums[0] intValue];
int current_sum = [nums[0] intValue];
for (int i = 1; i < nums.count; i++) {
int num = [nums[i] intValue];
current_sum = MAX(current_sum + num, num);
max_s... | dolphin |
Please write the following solution using C#:
You are the manager of a basketball team. For the upcoming tournament, you want to choose the team with the highest overall score. The score of the team is the **sum** of scores of all the players in the team.
However, the basketball team is not allowed to have **conflicts... | dolphin |
Please explain the following problem in detail and provide code in TypeScript:
You are given a `rows x cols` matrix `grid` representing a field of cherries where `grid[i][j]` represents the number of cherries that you can collect from the `(i, j)` cell.
You have two robots that can collect cherries for you:
* **Rob... | dolphin |
Please focus on the algorithm of this problem and provide code in Go:
We want to split a group of `n` people (labeled from `1` to `n`) into two groups of **any size**. Each person may dislike some other people, and they should not go into the same group.
Given the integer `n` and the array `dislikes` where `dislikes[i... | dolphin |
Please write the following solution using Lua:
You are given the `root` of a binary tree with **unique values**.
In one operation, you can choose any two nodes **at the same level** and swap their values.
Return _the minimum number of operations needed to make the values at each level sorted in a **strictly increasin... | dolphin |
Please explain the reasoning behind the following solution and provide code in Scala:
You have `n` super washing machines on a line. Initially, each washing machine has some dresses or is empty.
For each move, you could choose any `m` (`1 <= m <= n`) washing machines, and pass one dress of each washing machine to one ... | dolphin |
port this code from C# to c++:
```csharp
public int GetMaxEarnings(int n, int[][] rides) {
Array.Sort(rides, (a, b) => a[0] - b[0]);
int[] dp = new int[n + 1];
for (int i = 0; i < n; i++) {
dp[i + 1] = Math.Max(dp[i + 1], dp[i]);
for (int j = i; j < n; j++) {
if (rides[j][0] > i ... | dolphin |
Please write the following solution using Swift:
You are given an integer array `score` of size `n`, where `score[i]` is the score of the `ith` athlete in a competition. All the scores are guaranteed to be **unique**.
The athletes are **placed** based on their scores, where the `1st` place athlete has the highest scor... | dolphin |
Please write the following solution using Object Pascal:
Given an integer array `arr`, and an integer `target`, return the number of tuples `i, j, k` such that `i < j < k` and `arr[i] + arr[j] + arr[k] == target`.
As the answer can be very large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** arr = \[1,1,... | dolphin |
translate this code from Go to F#:
```go
import "container/list"
func playGame(graph [][]int) int {
queue := list.New()
visited := make(map[[3]int]bool)
mousePos, catPos := 1, 2
player := 1
queue.PushBack([3]int{player, mousePos, catPos})
visited[[3]int{player, mousePos, catPos}] = true
for... | dolphin |
Please focus on the efficiency of this problem and provide code in Scala:
You are given a string `s` that consists of the digits `'1'` to `'9'` and two integers `k` and `minLength`.
A partition of `s` is called **beautiful** if:
* `s` is partitioned into `k` non-intersecting substrings.
* Each substring has a len... | dolphin |
Please write the following solution using Erlang:
There is a ball in a `maze` with empty spaces (represented as `0`) and walls (represented as `1`). The ball can go through the empty spaces by rolling **up, down, left or right**, but it won't stop rolling until hitting a wall. When the ball stops, it could choose the n... | dolphin |
translate this code from Erlang to java:
```erlang
-module(solution).
-export([num_of_ways/2]).
num_of_ways(Nums, K) ->
{Left, Right} = count(Nums, 0, 0, K),
Len = length(Nums),
case Left == Len of
true -> 0;
false ->
case Right - Left =:= Len - Right of
true -> ... | dolphin |
translate this code to Elixir:
```haskell
maxFrequencyScore :: [Int] -> Int -> Int
maxFrequencyScore nums k =
let n = length nums
go left right count score freqMap maxScore
| left == n = maxScore
| right < n && count < k =
let freq = Map.findWithDefault 0 (nums !! rig... | dolphin |
convert this code from Lisp to F#:
```lisp
(defun minimum-jumps (forbidden a b x)
(let ((forbidden-positions (make-hash-table))
(visited (make-hash-table))
(queue (list (list 0 0 0))))
(dolist (pos forbidden)
(setf (gethash pos forbidden-positions) t))
(setf (gethash (list 0 0) visited) ... | dolphin |
port this code from Ruby to Perl:
```ruby
def arrays_intersection(arr1, arr2, arr3)
i, j, k = 0, 0, 0
result = []
while i < arr1.length && j < arr2.length && k < arr3.length
if arr1[i] == arr2[j] && arr2[j] == arr3[k]
result << arr1[i]
i, j, k = i + 1, j + 1, k + 1
el... | dolphin |
port this code from Rust to PHP:
```rust
fn is_prime(num: i32) -> bool {
if num < 2 {
return false;
}
for i in 2..=((num as f64).sqrt() as i32) {
if num % i == 0 {
return false;
}
}
true
}
fn is_palindrome(num: i32) -> bool {
num.to_string() == num.to_string(... | dolphin |
translate this code to Lua:
```ruby
def is_covered(ranges, left, right)
covered = Array.new(51, 0)
ranges.each do |range|
(range[0]..range[1]).each do |i|
covered[i] = 1
end
end
(left..right).each do |i|
if covered[i] == 0
return false
end
end
... | dolphin |
Please explain the reasoning behind the following solution and provide code in javascript:
Given two strings `s1` and `s2`, return _the lowest **ASCII** sum of deleted characters to make two strings equal_.
**Example 1:**
**Input:** s1 = "sea ", s2 = "eat "
**Output:** 231
**Explanation:** Deleting "s " from "sea... | dolphin |
Please explain the following problem in detail and provide code in java:
Alice and Bob have an undirected graph of `n` nodes and three types of edges:
* Type 1: Can be traversed by Alice only.
* Type 2: Can be traversed by Bob only.
* Type 3: Can be traversed by both Alice and Bob.
Given an array `edges` where ... | dolphin |
Please explain the following problem in detail and provide code in java:
You are given an integer array `nums`. Two players are playing a game with this array: player 1 and player 2.
Player 1 and player 2 take turns, with player 1 starting first. Both players start the game with a score of `0`. At each turn, the playe... | dolphin |
port this code from Objective-C to Object Pascal:
```objective-c
- (NSInteger)firstDayBeenInAllRooms:(NSArray<NSNumber*>*)nextVisit {
NSInteger n = [nextVisit count];
NSInteger ans = 0;
NSInteger MOD = 1000000007;
NSMutableArray<NSNumber*>* dp = [NSMutableArray arrayWithCapacity:n];
for (NSInte... | dolphin |
Please write the following solution using Dart:
Given an array of integers `arr`, sort the array by performing a series of **pancake flips**.
In one pancake flip we do the following steps:
* Choose an integer `k` where `1 <= k <= arr.length`.
* Reverse the sub-array `arr[0...k-1]` (**0-indexed**).
For example, i... | dolphin |
Please write the following solution using C#:
On an `2 x 3` board, there are five tiles labeled from `1` to `5`, and an empty square represented by `0`. A **move** consists of choosing `0` and a 4-directionally adjacent number and swapping it.
The state of the board is solved if and only if the board is `[[1,2,3],[4,5... | dolphin |
Please focus on the algorithm of this problem and provide code in Haskell:
You are given two positive integers `n` and `target`.
An integer is considered **beautiful** if the sum of its digits is less than or equal to `target`.
Return the _minimum **non-negative** integer_ `x` _such that_ `n + x` _is beautiful_. The ... | dolphin |
Please explain the reasoning behind the following solution and provide code in Scala:
You are given two integers `n` and `k` and two integer arrays `speed` and `efficiency` both of length `n`. There are `n` engineers numbered from `1` to `n`. `speed[i]` and `efficiency[i]` represent the speed and efficiency of the `ith... | dolphin |
convert this code from Perl to Scala:
```perl
sub find_secret_sharers {
my ($n, $meetings, $first_person) = @_;
my @secret_holders = (-1) x $n;
$secret_holders[0] = 0;
$secret_holders[$first_person] = 0;
@$meetings = sort { $a->[2] <=> $b->[2] } @$meetings;
foreach my $meeting (@$meetings) {
... | dolphin |
Please write the following solution using Swift:
A web developer needs to know how to design a web page's size. So, given a specific rectangular web page's area, your job by now is to design a rectangular web page, whose length L and width W satisfy the following requirements:
1. The area of the rectangular web page ... | dolphin |
translate this code from Julia to Haskell:
```julia
function leftBoundary(node, boundary)
if node == nothing || (node.left == nothing && node.right == nothing)
return
end
push!(boundary, node.val)
if node.left != nothing
leftBoundary(node.left, boundary)
else
leftBoundary(nod... | dolphin |
Please focus on the algorithm of this problem and provide code in Dart:
Given a circular integer array `nums` (i.e., the next element of `nums[nums.length - 1]` is `nums[0]`), return _the **next greater number** for every element in_ `nums`.
The **next greater number** of a number `x` is the first greater number to it... | dolphin |
Please focus on the algorithm of this problem and provide code in R:
You are given a **0-indexed** `m x n` **binary** matrix `grid`.
In one operation, you can choose any `i` and `j` that meet the following conditions:
* `0 <= i < m`
* `0 <= j < n`
* `grid[i][j] == 1`
and change the values of **all** cells in r... | dolphin |
Please explain the reasoning behind the following solution and provide code in ANSI C:
You are given a 2D array of integers `envelopes` where `envelopes[i] = [wi, hi]` represents the width and the height of an envelope.
One envelope can fit into another if and only if both the width and height of one envelope are grea... | dolphin |
translate this code from Scala to R:
```scala
import scala.collection.mutable
object Solution {
def minTransfers(transactions: Array[Array[Int]]): Int = {
val balances = mutable.Map[Int, Int]().withDefaultValue(0)
for (transaction <- transactions) {
balances(transaction(0)) -= transacti... | dolphin |
Please explain the following problem in detail and provide code in Julia:
We define `str = [s, n]` as the string `str` which consists of the string `s` concatenated `n` times.
* For example, `str == [ "abc ", 3] == "abcabcabc "`.
We define that string `s1` can be obtained from string `s2` if we can remove some char... | dolphin |
Please write the following solution using java:
Given `n` `points` on a 2D plane where `points[i] = [xi, yi]`, Return _the **widest vertical area** between two points such that no points are inside the area._
A **vertical area** is an area of fixed-width extending infinitely along the y-axis (i.e., infinite height). T... | dolphin |
Please explain the reasoning behind the following solution and provide code in Haskell:
Given an binary array `nums` and an integer `k`, return `true` _if all_ `1`_'s are at least_ `k` _places away from each other, otherwise return_ `false`.
**Example 1:**
**Input:** nums = \[1,0,0,0,1,0,0,1\], k = 2
**Output:** true... | dolphin |
port this code to Elixir:
```fsharp
let minVisibleWhiteTiles (floor: string) (numCarpets: int) (carpetLen: int) : int =
let n, res = floor.Length, floor.Length
for i in 0 .. n - carpetLen do
let count = [ for j in i .. i + carpetLen - 1 do yield if floor.[j] = '1' then 1 else 0 ] |> List.sum
for... | dolphin |
convert this code to Visual Basic .NET:
```c
#include <stdbool.h>
bool checkPossibility(int* nums, int numsSize){
int cnt = 0;
for (int i = 1; i < numsSize; i++) {
if (nums[i] < nums[i - 1]) {
cnt++;
if (i == 1 || nums[i] >= nums[i - 2]) {
nums[i - 1] = nums[i];
... | dolphin |
convert this code to Lua:
```javascript
function maxPoints(points) {
let m = points.length, n = points[0].length;
let dp = new Array(n).fill(0);
for (const row of points) {
const next_dp = new Array(n).fill(0);
for (let c1 = 0; c1 < n; ++c1) {
const score = dp[c1] + row[c1] - c1;... | dolphin |
Please explain the following problem in detail and provide code in TypeScript:
The **factorial** of a positive integer `n` is the product of all positive integers less than or equal to `n`.
* For example, `factorial(10) = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1`.
We make a **clumsy factorial** using the integers in ... | dolphin |
translate this code from F# to Kotlin:
```fsharp
let reverse (x: int) : int =
let sign = if x < 0 then -1 else 1
let mutable x' = abs(x)
let mutable res = 0
while x' <> 0 do
res <- res * 10 + x' % 10
x' <- x' / 10
res <- res * sign
if res < -2_147_483_648 || res > 2_147_483_647 t... | dolphin |
Please explain the following problem in detail and provide code in Clojure:
You have an infinite number of stacks arranged in a row and numbered (left to right) from `0`, each of the stacks has the same maximum capacity.
Implement the `DinnerPlates` class:
* `DinnerPlates(int capacity)` Initializes the object with ... | dolphin |
Please write the following solution using Ruby:
There is a tree (i.e., a connected, undirected graph with no cycles) structure country network consisting of `n` cities numbered from `0` to `n - 1` and exactly `n - 1` roads. The capital city is city `0`. You are given a 2D integer array `roads` where `roads[i] = [ai, bi... | dolphin |
Please explain the reasoning behind the following solution and provide code in Kotlin:
Given a non-negative integer `num`, Return its _encoding_ string.
The encoding is done by converting the integer to a string using a secret function that you should deduce from the following table:
**Example 1:**
**Input:** num = ... | dolphin |
Please focus on the efficiency of this problem and provide code in python:
You are given an empty 2D binary grid `grid` of size `m x n`. The grid represents a map where `0`'s represent water and `1`'s represent land. Initially, all the cells of `grid` are water cells (i.e., all the cells are `0`'s).
We may perform an ... | dolphin |
Please explain the following problem in detail and provide code in Object Pascal:
You are given two **0-indexed** integer arrays `nums1` and `nums2`, each of size `n`, and an integer `diff`. Find the number of **pairs** `(i, j)` such that:
* `0 <= i < j <= n - 1` **and**
* `nums1[i] - nums1[j] <= nums2[i] - nums2[... | dolphin |
Please explain the following problem in detail and provide code in python:
You are given an array of strings `equations` that represent relationships between variables where each string `equations[i]` is of length `4` and takes one of two different forms: `"xi==yi "` or `"xi!=yi "`.Here, `xi` and `yi` are lowercase let... | dolphin |
Please explain the following problem in detail and provide code in python:
Given a list of `accounts` where each element `accounts[i]` is a list of strings, where the first element `accounts[i][0]` is a name, and the rest of the elements are **emails** representing emails of the account.
Now, we would like to merge th... | dolphin |
Please explain the following problem in detail and provide code in javascript:
A **row-sorted binary matrix** means that all elements are `0` or `1` and each row of the matrix is sorted in non-decreasing order.
Given a **row-sorted binary matrix** `binaryMatrix`, return _the index (0-indexed) of the **leftmost column*... | dolphin |
Please explain the reasoning behind the following solution and provide code in Lua:
You are given an integer `n`. We reorder the digits in any order (including the original order) such that the leading digit is not zero.
Return `true` _if and only if we can do this so that the resulting number is a power of two_.
**E... | dolphin |
port this code from Julia to Lisp:
```julia
function pyramid_transition(bottom, allowed)
mapping = Dict()
for s in allowed
key = s[1:2]
if !(key in keys(mapping))
mapping[key] = []
end
push!(mapping[key], s[3])
end
return pyramid_transition_helper(bottom, "", ... | dolphin |
translate this code from Julia to c++:
```julia
function lonely_numbers(nums)
count = Dict()
result = []
for num in nums
if !haskey(count, num)
count[num] = 1
else
count[num] += 1
end
end
for key in keys(count)
k = parse(Int, key)
if co... | dolphin |
Please explain the following problem in detail and provide code in Lisp:
You are given a **0-indexed** integer array `nums`.
* The **low** score of `nums` is the minimum value of `|nums[i] - nums[j]|` over all `0 <= i < j < nums.length`.
* The **high** score of `nums` is the maximum value of `|nums[i] - nums[j]|` ... | dolphin |
translate this code to Clojure:
```typescript
function ones_k_apart(nums: number[], k: number): boolean {
let last_one = -k - 1;
for (let i = 0; i < nums.length; i++) {
if (nums[i] === 1) {
if (i - last_one <= k) {
return false;
}
last_one = i;
}
}
return true;
}
``` | dolphin |
Please focus on the algorithm of this problem and provide code in c++:
Suppose we have a file system that stores both files and directories. An example of one system is represented in the following picture:
Here, we have `dir` as the only directory in the root. `dir` contains two subdirectories, `subdir1` and `subdir2... | dolphin |
Please explain the following problem in detail and provide code in Rust:
You are given an integer array `nums` and an integer `k`.
In one operation, you can choose any index `i` where `0 <= i < nums.length` and change `nums[i]` to `nums[i] + x` where `x` is an integer from the range `[-k, k]`. You can apply this opera... | dolphin |
Please explain the reasoning behind the following solution and provide code in Dart:
Given an integer array `nums`, return _the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle_.
**Example 1:**
**Input:** nums = \[2,2,3,4\]
**Output:** 3
**Explanation:** V... | dolphin |
Please explain the following problem in detail and provide code in Groovy:
You are given a string of digits `num`, such as `"123456579 "`. We can split it into a Fibonacci-like sequence `[123, 456, 579]`.
Formally, a **Fibonacci-like** sequence is a list `f` of non-negative integers such that:
* `0 <= f[i] < 231`, ... | dolphin |
Please explain the following problem in detail and provide code in Kotlin:
Given an array of intervals `intervals` where `intervals[i] = [starti, endi]`, return _the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping_.
**Example 1:**
**Input:** intervals = \[\[1,2\],\[2,3... | dolphin |
port this code to Haskell:
```dart
int averageEvenDivisibleByThree(List<int> nums) {
int total = 0;
int count = 0;
for (int num in nums) {
if (num % 2 == 0 && num % 3 == 0) {
total += num;
count += 1;
}
}
return count > 0 ? total ~/ count : 0;
}
``` | dolphin |
translate this code to Dart:
```vb.net
Function OddEvenJumps(arr As Integer()) As Integer
Dim n As Integer = arr.Length
Dim can_reach_odd(n - 1) As Boolean
Dim can_reach_even(n - 1) As Boolean
can_reach_odd(n - 1) = True
can_reach_even(n - 1) = True
Dim index_map As New Dictionary(Of Integer, I... | dolphin |
Please focus on the efficiency of this problem and provide code in Elixir:
You are given an **even** number of people `numPeople` that stand around a circle and each person shakes hands with someone else so that there are `numPeople / 2` handshakes total.
Return _the number of ways these handshakes could occur such th... | dolphin |
Please write the following solution using Haskell:
You are given an integer array `ranks` representing the **ranks** of some mechanics. ranksi is the rank of the ith mechanic. A mechanic with a rank `r` can repair n cars in `r * n2` minutes.
You are also given an integer `cars` representing the total number of cars wa... | dolphin |
Please explain the following problem in detail and provide code in Clojure:
Given a `rows x cols` binary `matrix` filled with `0`'s and `1`'s, find the largest rectangle containing only `1`'s and return _its area_.
**Example 1:**
**Input:** matrix = \[\[ "1 ", "0 ", "1 ", "0 ", "0 "\],\[ "1 ", "0 ", "1 ", "1 ", "1 "\... | dolphin |
port this code from ANSI C to c++:
```c
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
typedef struct {
int* queue;
int maxSize;
int front;
int rear;
int count;
int sum;
} MovingAverage;
MovingAverage* movingAverageCreate(int size) {
MovingAverage* obj = (MovingAverage*) malloc... | dolphin |
Please explain the following problem in detail and provide code in Mojo:
Given two arrays of strings `list1` and `list2`, find the **common strings with the least index sum**.
A **common string** is a string that appeared in both `list1` and `list2`.
A **common string with the least index sum** is a common string suc... | dolphin |
translate this code to Scala:
```c
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
bool isMatch(char * s, char * p){
int m = strlen(s), n = strlen(p);
bool dp[m + 1][n + 1];
memset(dp, false, sizeof(dp));
dp[0][0] = true;
for (int j = 1; j <= n; j++) {
if (p[j - 1] == '*' && d... | dolphin |
Please explain the following problem in detail and provide code in python:
There exists an undirected and initially unrooted tree with `n` nodes indexed from `0` to `n - 1`. You are given the integer `n` and a 2D integer array `edges` of length `n - 1`, where `edges[i] = [ai, bi]` indicates that there is an edge betwee... | dolphin |
Please write the following solution using ANSI C:
Given an array `nums` of integers and integer `k`, return the maximum `sum` such that there exists `i < j` with `nums[i] + nums[j] = sum` and `sum < k`. If no `i`, `j` exist satisfying this equation, return `-1`.
**Example 1:**
**Input:** nums = \[34,23,1,24,75,33,54,... | dolphin |
Please explain the reasoning behind the following solution and provide code in Ruby:
In the "100 game " two players take turns adding, to a running total, any integer from `1` to `10`. The player who first causes the running total to **reach or exceed** 100 wins.
What if we change the game so that players **cannot** r... | dolphin |
Please explain the following problem in detail and provide code in Erlang:
Design a text editor with a cursor that can do the following:
* **Add** text to where the cursor is.
* **Delete** text from where the cursor is (simulating the backspace key).
* **Move** the cursor either left or right.
When deleting tex... | dolphin |
Please explain the reasoning behind the following solution and provide code in Lua:
Given an array of integers `arr`, replace each element with its rank.
The rank represents how large the element is. The rank has the following rules:
* Rank is an integer starting from 1.
* The larger the element, the larger the r... | dolphin |
Please write the following solution using Visual Basic .NET:
You are given a nested list of integers `nestedList`. Each element is either an integer or a list whose elements may also be integers or other lists.
The **depth** of an integer is the number of lists that it is inside of. For example, the nested list `[1,[2... | dolphin |
Please focus on the algorithm of this problem and provide code in Haskell:
A **complete binary tree** is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible.
Design an algorithm to insert a new node to a complete binary tree keeping it complete ... | dolphin |
convert this code to Rust:
```swift
func longestArithmeticSubsequence(_ nums: [Int]) -> Int {
let n = nums.count
if n < 3 {
return n
}
var dp: [[Int: Int]] = [Dictionary() | _ in [:] | n]
var maxLength = 2
for i in 0..<n {
for j in (i+1)..<n {
let diff = nums[j] - n... | dolphin |
Please explain the reasoning behind the following solution and provide code in Groovy:
Given a string `s`, return `true` _if it is possible to split the string_ `s` _into three **non-empty** palindromic substrings. Otherwise, return_ `false`.
A string is said to be palindrome if it the same string when reversed.
... | dolphin |
Please explain the following problem in detail and provide code in Swift:
You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once.
Return _the single element that appears only once_.
Your solution must run in `O(log n)` time... | dolphin |
port this code from Perl to Scheme:
```perl
sub minTimeToType {
my ($word) = @_;
my $time = 0;
my $position = 0;
foreach my $c (split //, $word) {
my $next_position = ord($c) - ord('a');
my $diff = abs($next_position - $position);
$time += ($diff < (26 - $diff)) ? $diff : (26 - $... | dolphin |
Please focus on the efficiency of this problem and provide code in Julia:
You are given a **0-indexed** array of positive integers `nums`. Find the number of triplets `(i, j, k)` that meet the following conditions:
* `0 <= i < j < k < nums.length`
* `nums[i]`, `nums[j]`, and `nums[k]` are **pairwise distinct**.
... | dolphin |
Please explain the following problem in detail and provide code in Rust:
You are given a string `num` consisting of digits only.
Return _the **largest palindromic** integer (in the form of a string) that can be formed using digits taken from_ `num`. It should not contain **leading zeroes**.
**Notes:**
* You do **n... | dolphin |
convert this code from Ruby to Groovy:
```ruby
def max_groups(n, edges)
graph = Hash.new{|h, k| h[k] = []}
color = Array.new(n+1, 0)
edges.each do |edge|
graph[edge[0]] << edge[1]
graph[edge[1]] << edge[0]
end
max_group = 0
(1..n).each do |i|
if color[i] == 0
... | dolphin |
port this code from c++ to Rust:
```cpp
int strangePrinter(string s) {
int n = s.size();
if(n == 0) return 0;
vector<vector<int>> dp(n, vector<int>(n, 0));
for(int i = 0; i < n; i++) dp[i][i] = 1;
for(int len = 1; len < n; len++) {
for(int i = 0; i < n - len; i++) {
int j = i + l... | dolphin |
Please write the following solution using Kotlin:
Given an integer `n`, return `true` _if_ `n` _has **exactly three positive divisors**. Otherwise, return_ `false`.
An integer `m` is a **divisor** of `n` if there exists an integer `k` such that `n = k * m`.
**Example 1:**
**Input:** n = 2
**Output:** false
**Explant... | dolphin |
Please focus on the functionality of this problem and provide code in c++:
You are given a **0-indexed** positive integer array `nums` and a positive integer `k`.
A pair of numbers `(num1, num2)` is called **excellent** if the following conditions are satisfied:
* **Both** the numbers `num1` and `num2` exist in the... | dolphin |
convert this code to Scheme:
```objective-c
- (BOOL)checkSubarraySum:(NSArray<NSNumber *> *)nums k:(NSInteger)k {
NSInteger n = nums.count, sum = 0;
NSMutableDictionary<NSNumber *, NSNumber *> *mp = [NSMutableDictionary new];
mp[@(0)] = @(-1);
for (NSInteger i = 0; i < n; i++) {
sum += nums[i].i... | dolphin |
Please explain the reasoning behind the following solution and provide code in Swift:
> Note: This is a companion problem to the [System Design](https://leetcode.com/discuss/interview-question/system-design/) problem: [Design TinyURL](https://leetcode.com/discuss/interview-question/124658/Design-a-URL-Shortener-(-TinyU... | dolphin |
Please focus on the functionality of this problem and provide code in Julia:
You are given an integer array of unique positive integers `nums`. Consider the following graph:
* There are `nums.length` nodes, labeled `nums[0]` to `nums[nums.length - 1]`,
* There is an undirected edge between `nums[i]` and `nums[j]` ... | dolphin |
convert this code to Rust:
````mojo
sub jobScheduling(start_time as [Int], end_time as [Int], profit as [Int]) returns Int
n = start_time.len
jobs = zip(end_time, start_time, profit).sort_by(|j| j.0)
dp = [jobs[0].2]
fn latestNonConflict(index as Int) -> Int
start_time_to_find = jobs[index].1
... | dolphin |
Please explain the following problem in detail and provide code in Fortran:
A **[binary expression tree](https://en.wikipedia.org/wiki/Binary_expression_tree)** is a kind of binary tree used to represent arithmetic expressions. Each node of a binary expression tree has either zero or two children. Leaf nodes (nodes wit... | dolphin |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.