instruction_seed stringlengths 29 40.5k | source stringclasses 6
values |
|---|---|
port this code to Dart:
```erlang
-module(largest_integer_api).
-export([compareSub/4, length/0, find_largest_integer/0]).
%% API functions
compareSub(L, R, X, Y) ->
%% implementation goes here
0.
length() ->
%% implementation goes here
0.
%% Implementation of find_largest_integer function
find_larg... | dolphin |
Please write the following solution using PHP:
Given an array of integers `arr`, return `true` if we can partition the array into three **non-empty** parts with equal sums.
Formally, we can partition the array if we can find indexes `i + 1 < j` with `(arr[0] + arr[1] + ... + arr[i] == arr[i + 1] + arr[i + 2] + ... + a... | dolphin |
Please explain the reasoning behind the following solution and provide code in Fortran:
Given two string arrays `word1` and `word2`, return `true` _if the two arrays **represent** the same string, and_ `false` _otherwise._
A string is **represented** by an array if the array elements concatenated **in order** forms th... | dolphin |
Please explain the following problem in detail and provide code in ANSI C:
There are `n` cars on an infinitely long road. The cars are numbered from `0` to `n - 1` from left to right and each car is present at a **unique** point.
You are given a **0-indexed** string `directions` of length `n`. `directions[i]` can be e... | dolphin |
Please write the following solution using Swift:
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 rank. If two elements are equal, the... | dolphin |
Please focus on the efficiency of this problem and provide code in python:
There is an `m x n` binary grid `matrix` with all the values set `0` initially. Design an algorithm to randomly pick an index `(i, j)` where `matrix[i][j] == 0` and flips it to `1`. All the indices `(i, j)` where `matrix[i][j] == 0` should be eq... | dolphin |
convert this code from python to Rust:
```python
def minOperations(nums):
count = 0
nums.sort()
i = 0
while i < len(nums):
if nums[i] > 0:
target = nums[i]
while i < len(nums) and nums[i] == target:
i += 1
count += 1
else:
... | dolphin |
translate this code to C#:
```javascript
function countPyramids(grid) {
const m = grid.length, n = grid[0].length;
let count = 0;
for (let i = 1; i < m - 1; ++i) {
for (let j = 1; j < n - 1; ++j) {
if (grid[i][j] === grid[i - 1][j] + grid[i][j - 1] - grid[i - 1][j - 1]
&&... | dolphin |
convert this code from Swift to python:
```swift
struct Meeting {
var start: Int
var end: Int
}
func mostVisitedRoom(_ n: Int, _ meetings: [Meeting]) -> Int {
let sortedMeetings = meetings.sorted(by: { $0.start < $1.start })
var pq = [(end: Int, room: Int)]()
var rooms = [Int](repeating: 0, count: ... | dolphin |
Please focus on the efficiency of this problem and provide code in java:
You are given a **0-indexed** array of positive integers `nums`. A triplet of three **distinct** indices `(i, j, k)` is called a **single divisor triplet** of `nums` if `nums[i] + nums[j] + nums[k]` is divisible by **exactly one** of `nums[i]`, `n... | dolphin |
Please explain the following problem in detail and provide code in Objective-C:
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.right.v... | dolphin |
translate this code from javascript to Objective-C:
```javascript
function numStrictlyIncreasingSubarrays(nums) {
const n = nums.length;
let count = 0;
let sum = 0;
for (let i = 1; i < n; ++i) {
if (nums[i] > nums[i - 1]) {
count++;
} else {
count = 0;
}
... | dolphin |
Please focus on the algorithm of this problem and provide code in Kotlin:
Alice and Bob take turns playing a game, with Alice starting first.
Initially, there are `n` stones in a pile. On each player's turn, that player makes a _move_ consisting of removing **any** non-zero **square number** of stones in the pile.
Al... | dolphin |
Please write the following solution using Perl:
Given an integer array `data` representing the data, return whether it is a valid **UTF-8** encoding (i.e. it translates to a sequence of valid UTF-8 encoded characters).
A character in **UTF8** can be from **1 to 4 bytes** long, subjected to the following rules:
1. Fo... | dolphin |
Please focus on the algorithm of this problem and provide code in Perl:
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]`... | dolphin |
Please explain the following problem in detail and provide code in Mojo:
Given an array `nums` of **distinct** positive integers, return _the number of tuples_ `(a, b, c, d)` _such that_ `a * b = c * d` _where_ `a`_,_ `b`_,_ `c`_, and_ `d` _are elements of_ `nums`_, and_ `a != b != c != d`_._
**Example 1:**
**Input:*... | dolphin |
translate this code from Rust to Mojo:
```rust
fn sort_names_by_height(names: Vec<String>, heights: Vec<u32>) -> Vec<String> {
let mut name_height_pairs: Vec<(&u32, &String)> = heights.iter().zip(names.iter()).collect();
name_height_pairs.sort_by(|a, b| b.0.cmp(a.0));
name_height_pairs.iter().map(|pair| pai... | dolphin |
convert this code to Haskell:
```cpp
#include <vector>
#include <unordered_map>
#include <limits>
int min_sum_of_lengths(std::vector<int> &arr, int target) {
int n = arr.size(), sum = 0, min_len = std::numeric_limits<int>::max();
int result = std::numeric_limits<int>::max();
std::unordered_map<int, int> mp... | dolphin |
Please write the following solution using javascript:
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
**Note:** A leaf is a node with no children.
**Example 1:**
**Input:** root = \[3,9,20,null,null,15,7\... | dolphin |
convert this code to PHP:
```go
func numSpecialEquivGroups(words []string) int {
groups := make(map[string]bool)
for _, word := range words {
evens := []rune{}
odds := []rune{}
for i, c := range word {
if i % 2 == 0 {
evens = append(evens, c)
} e... | dolphin |
port this code to c++:
```go
func isAlienSorted(words []string, order string) bool {
alienOrder := make(map[rune]int)
for i, char := range order {
alienOrder[char] = i
}
for i := 1; i < len(words); i++ {
for j := 0; j < len(words[i-1]); j++ {
if j == len(words[i]) {
... | dolphin |
translate this code to R:
```lua
function find_digits_in_ascending_order(s)
local count = {0,0,0,0,0,0,0,0,0,0}
for i = 1, #s do
local c = s:sub(i,i)
if c == 'z' then count[1] = count[1] + 1 end
if c == 'w' then count[3] = count[3] + 1 end
if c == 'u' then count[5] = count[5] + 1 end
if c == 'x'... | dolphin |
Please write the following solution using Groovy:
You are given a 2D integer array `intervals` where `intervals[i] = [starti, endi]` represents all the integers from `starti` to `endi` inclusively.
A **containing set** is an array `nums` where each interval from `intervals` has **at least two** integers in `nums`.
* ... | dolphin |
port this code from Rust to Go:
```rust
fn max_profit_assignment(difficulty: Vec<i32>, profit: Vec<i32>, worker: Vec<i32>) -> i32 {
let n = difficulty.len();
let mut jobs = difficulty.iter().zip(profit.iter()).collect::<Vec<_>>();
jobs.sort();
let mut worker = worker;
worker.sort();
let mut ma... | dolphin |
Please write the following solution using PHP:
You are given a **0-indexed** integer array `stones` sorted in **strictly increasing order** representing the positions of stones in a river.
A frog, initially on the first stone, wants to travel to the last stone and then return to the first stone. However, it can jump t... | dolphin |
Please explain the following problem in detail and provide code in Lisp:
In the world of Dota2, there are two parties: the Radiant and the Dire.
The Dota2 senate consists of senators coming from two parties. Now the Senate wants to decide on a change in the Dota2 game. The voting for this change is a round-based proce... | dolphin |
Please explain the following problem in detail and provide code in Visual Basic .NET:
Given an integer array `nums`, partition it into two (contiguous) subarrays `left` and `right` so that:
* Every element in `left` is less than or equal to every element in `right`.
* `left` and `right` are non-empty.
* `left` h... | dolphin |
translate this code to Scheme:
```rust
fn can_construct(ransom_note: String, magazine: String) -> bool {
let mut letter_count: std::collections::HashMap<char, i32> = std::collections::HashMap::new();
for c in magazine.chars() {
*letter_count.entry(c).or_insert(0) += 1;
}
for c in ranso... | dolphin |
port this code to C#:
```objective-c
#import <Foundation/Foundation.h>
@interface ExamRoom : NSObject
- (instancetype)initWithN:(int)n;
- (int)seat;
- (void)leave:(int)p;
@end
@implementation ExamRoom {
int _n;
NSMutableArray<NSNumber *> *_occupiedSeats;
}
- (instancetype)initWithN:(int)n {
if (self = ... | dolphin |
Please focus on the algorithm of this problem and provide code in TypeScript:
Given a list of folders `folder`, return _the folders after removing all **sub-folders** in those folders_. You may return the answer in **any order**.
If a `folder[i]` is located within another `folder[j]`, it is called a **sub-folder** of ... | dolphin |
Please explain the following problem in detail and provide code in python:
You are given an array of points on the **X-Y** plane `points` where `points[i] = [xi, yi]`. The points form a polygon when joined sequentially.
Return `true` if this polygon is [convex](http://en.wikipedia.org/wiki/Convex_polygon) and `false` ... | dolphin |
Please explain the following problem in detail and provide code in Lisp:
On an infinite plane, a robot initially stands at `(0, 0)` and faces north. Note that:
* The **north direction** is the positive direction of the y-axis.
* The **south direction** is the negative direction of the y-axis.
* The **east direct... | dolphin |
Please explain the reasoning behind the following solution and provide code in Rust:
You are given a tree (i.e. a connected, undirected graph that has no cycles) consisting of `n` nodes numbered from `0` to `n - 1` and exactly `n - 1` `edges`. The **root** of the tree is the node `0`, and each node of the tree has **a ... | dolphin |
Please write the following solution using Lua:
There are a total of `numCourses` courses you have to take, labeled from `0` to `numCourses - 1`. You are given an array `prerequisites` where `prerequisites[i] = [ai, bi]` indicates that you **must** take course `bi` first if you want to take course `ai`.
* For example... | dolphin |
Please write the following solution using Erlang:
Design an algorithm that accepts a stream of integers and retrieves the product of the last `k` integers of the stream.
Implement the `ProductOfNumbers` class:
* `ProductOfNumbers()` Initializes the object with an empty stream.
* `void add(int num)` Appends the in... | dolphin |
translate this code from Julia to PHP:
```julia
function merge_sorted_bst(root1::Union{Nothing, TreeNode}, root2::Union{Nothing, TreeNode})::Vector{Int}
if root1 == nothing
return inorder(root2)
end
if root2 == nothing
return inorder(root1)
end
merged_list = Vector{Int}()
... | dolphin |
Please explain the reasoning behind the following solution and provide code in Dart:
The Tribonacci sequence Tn is defined as follows:
T0 = 0, T1 = 1, T2 = 1, and Tn+3 = Tn + Tn+1 + Tn+2 for n >= 0.
Given `n`, return the value of Tn.
**Example 1:**
**Input:** n = 4
**Output:** 4
**Explanation:**
T\_3 = 0 + 1 + 1 = ... | dolphin |
translate this code to ANSI C:
```rust
fn partition_labels(s: String) -> Vec<i32> {
let mut last: Vec<usize> = vec![0; 26];
for (i, c) in s.chars().enumerate() {
last[c as usize - 'a' as usize] = i;
}
let mut ans: Vec<i32> = Vec::new();
let (mut j, mut anchor) = (0, 0);
for (i, c) in s.c... | dolphin |
Please write the following solution using F#:
Given two arrays of integers with equal lengths, return the maximum value of:
`|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|`
where the maximum is taken over all `0 <= i, j < arr1.length`.
**Example 1:**
**Input:** arr1 = \[1,2,3,4\], arr2 = \[-1,4,5,6\]
**Output:... | dolphin |
Please focus on the functionality of this problem and provide code in ANSI C:
You are the operator of a Centennial Wheel that has **four gondolas**, and each gondola has room for **up** **to** **four people**. You have the ability to rotate the gondolas **counterclockwise**, which costs you `runningCost` dollars.
You ... | dolphin |
Please write the following solution using javascript:
You are given a string `s` consisting of lowercase English letters, and an integer `k`.
First, **convert** `s` into an integer by replacing each letter with its position in the alphabet (i.e., replace `'a'` with `1`, `'b'` with `2`, ..., `'z'` with `26`). Then, **t... | dolphin |
convert this code to Dart:
```R
minimum_height_trees <- function(n, edges){
if(n == 1){
return(0)
}
adj_list <- vector("list", n)
for(i in 1:n){
adj_list[[i]] <- integer()
}
for(i in 1:(n-1)){
a <- edges[i, 1]
b <- edges[i, 2]
adj_list[[a]] <- c(adj_list[[a]], b)
adj_list[[b]] ... | dolphin |
Please explain the following problem in detail and provide code in Mojo:
You are given an integer array `cookies`, where `cookies[i]` denotes the number of cookies in the `ith` bag. You are also given an integer `k` that denotes the number of children to distribute **all** the bags of cookies to. All the cookies in the... | dolphin |
Please explain the following problem in detail and provide code in javascript:
You are given two strings `word1` and `word2`. Merge the strings by adding letters in alternating order, starting with `word1`. If a string is longer than the other, append the additional letters onto the end of the merged string.
Return _t... | dolphin |
Please explain the following problem in detail and provide code in Kotlin:
You are given a string `s` and a robot that currently holds an empty string `t`. Apply one of the following operations until `s` and `t` **are both empty**:
* Remove the **first** character of a string `s` and give it to the robot. The robot ... | dolphin |
convert this code to TypeScript:
```fsharp
type TreeNode(val: int, left: TreeNode option, right: TreeNode option) =
member this.Val = val
member this.Left = left
member this.Right = right
let rec findLcaUtil (root: TreeNode option) =
match root with
| None -> None, 0
| Some node ->
let ... | dolphin |
Please explain the reasoning behind the following solution and provide code in Mojo:
Design a time-based key-value data structure that can store multiple values for the same key at different time stamps and retrieve the key's value at a certain timestamp.
Implement the `TimeMap` class:
* `TimeMap()` Initializes the... | dolphin |
Please focus on the algorithm of this problem and provide code in Rust:
Given a positive integer num, return _the smallest positive integer_ `x` _whose multiplication of each digit equals_ `num`. If there is no answer or the answer is not fit in **32-bit** signed integer, return `0`.
**Example 1:**
**Input:** num = 4... | dolphin |
translate this code to Julia:
```scheme
(define (min-operations n)
(define (helper n steps)
(if (= n 1)
steps
(helper (if (even? n)
(/ n 2)
(if (or (= (modulo (- n 1) 4) 0) (= n 3))
(- n 1)
(+ n 1)))
... | dolphin |
Please focus on the functionality of this problem and provide code in Visual Basic .NET:
A **valid number** can be split up into these components (in order):
1. A **decimal number** or an **integer**.
2. (Optional) An `'e'` or `'E'`, followed by an **integer**.
A **decimal number** can be split up into these compon... | dolphin |
Please explain the reasoning behind the following solution and provide code in Swift:
Given a positive integer `n`, find and return _the **longest distance** between any two **adjacent**_ `1`_'s in the binary representation of_ `n`_. If there are no two adjacent_ `1`_'s, return_ `0`_._
Two `1`'s are **adjacent** if th... | dolphin |
translate this code from TypeScript to Go:
```typescript
class ListNode {
val: number;
next: ListNode | null;
constructor(val?: number, next?: ListNode | null) {
this.val = (val === undefined ? 0 : val);
this.next = (next === undefined ? null : next);
}
}
function plusOne(head: ListNode | null): ListNo... | dolphin |
Please write the following solution using C#:
We build a table of `n` rows (**1-indexed**). We start by writing `0` in the `1st` row. Now in every subsequent row, we look at the previous row and replace each occurrence of `0` with `01`, and each occurrence of `1` with `10`.
* For example, for `n = 3`, the `1st` row ... | dolphin |
Please explain the reasoning behind the following solution and provide code in Lua:
You are given a phone number as a string `number`. `number` consists of digits, spaces `' '`, and/or dashes `'-'`.
You would like to reformat the phone number in a certain manner. Firstly, **remove** all spaces and dashes. Then, **grou... | dolphin |
Please explain the following problem in detail and provide code in Kotlin:
Given an array of distinct integers `arr`, where `arr` is sorted in **ascending order**, return the smallest index `i` that satisfies `arr[i] == i`. If there is no such index, return `-1`.
**Example 1:**
**Input:** arr = \[-10,-5,0,3,7\]
**Out... | dolphin |
Please explain the following problem in detail and provide code in Elixir:
Given an integer array `nums` and an integer `k`, return _the number of **subarrays** of_ `nums` _where the greatest common divisor of the subarray's elements is_ `k`.
A **subarray** is a contiguous non-empty sequence of elements within an arra... | dolphin |
Please explain the reasoning behind the following solution and provide code in ANSI C:
Given an integer array `nums` and a positive integer `k`, return _the most **competitive** subsequence of_ `nums` _of size_ `k`.
An array's subsequence is a resulting sequence obtained by erasing some (possibly zero) elements from t... | dolphin |
Please explain the following problem in detail and provide code in Lua:
A `k x k` **magic square** is a `k x k` grid filled with integers such that every row sum, every column sum, and both diagonal sums are **all equal**. The integers in the magic square **do not have to be distinct**. Every `1 x 1` grid is trivially ... | dolphin |
Please write the following solution using C#:
You are given a string `s` (**0-indexed**). You are asked to perform the following operation on `s` until you get a sorted string:
1. Find **the largest index** `i` such that `1 <= i < s.length` and `s[i] < s[i - 1]`.
2. Find **the largest index** `j` such th... | dolphin |
port this code to javascript:
```swift
func minOperations(_ nums: [Int]) -> Int {
var minPrefix = 0
var prefix = 0
for num in nums {
prefix += num
minPrefix = min(minPrefix, prefix)
}
return minPrefix < 0 ? -minPrefix : 0
}
``` | dolphin |
Please write the following solution using PHP:
You are given a positive integer `n`, indicating that we initially have an `n x n` **0-indexed** integer matrix `mat` filled with zeroes.
You are also given a 2D integer array `query`. For each `query[i] = [row1i, col1i, row2i, col2i]`, you should do the following operati... | dolphin |
convert this code from Elixir to javascript:
```elixir
defmodule Solution do
def is_prime(n) do
if n <= 1 do
false
else
for i <- 2..(trunc :math.sqrt(n)) do
if rem(n, i) == 0 do
return false
end
end
true
end
end
def closest_prime_pair(left, right) do
... | dolphin |
Please write the following solution using Clojure:
You are given an integer array `nums` that is **sorted in non-decreasing order**.
Determine if it is possible to split `nums` into **one or more subsequences** such that **both** of the following conditions are true:
* Each subsequence is a **consecutive increasing... | dolphin |
Please explain the following problem in detail and provide code in Perl:
Given a binary string `s`, return `true` _if the **longest** contiguous segment of_ `1`'_s is **strictly longer** than the **longest** contiguous segment of_ `0`'_s in_ `s`, or return `false` _otherwise_.
* For example, in `s = "110100010 "` th... | dolphin |
Please explain the following problem in detail and provide code in Dart:
You are given an array `time` where `time[i]` denotes the time taken by the `ith` bus to complete **one trip**.
Each bus can make multiple trips **successively**; that is, the next trip can start **immediately after** completing the current trip.... | dolphin |
Please explain the reasoning behind the following solution and provide code in java:
The red-green-blue color `"#AABBCC "` can be written as `"#ABC "` in shorthand.
* For example, `"#15c "` is shorthand for the color `"#1155cc "`.
The similarity between the two colors `"#ABCDEF "` and `"#UVWXYZ "` is `-(AB - UV)2 -... | dolphin |
convert this code from Perl to C#:
```perl
sub max_bitwise_xor {
my @nums = @_;
my $msb = 30;
my $res = 0;
while ($msb >= 0) {
my $count = 0;
foreach my $num (@nums) {
if ($num & (1 << $msb)) {
$count += 1;
}
}
if ($count >= 2) {
... | dolphin |
Please focus on the algorithm of this problem and provide code in Fortran:
Given a `pattern` and a string `s`, return `true` _if_ `s` _**matches** the_ `pattern`_._
A string `s` **matches** a `pattern` if there is some **bijective mapping** of single characters to strings such that if each character in `pattern` is re... | dolphin |
Please explain the following problem in detail and provide code in C#:
Given an integer array nums, return _the number of **AND triples**_.
An **AND triple** is a triple of indices `(i, j, k)` such that:
* `0 <= i < nums.length`
* `0 <= j < nums.length`
* `0 <= k < nums.length`
* `nums[i] & nums[j] & nums[k] ... | dolphin |
convert this code to Clojure:
```
longest_line(Mat) ->
Rows = length(Mat),
Cols = length(hd(Mat)),
Dp = lists:duplicate(Rows, lists:duplicate(Cols, [0, 0, 0, 0])),
longest_line(Mat, Rows, Cols, Dp, 0).
longest_line(_, 0, _, _, MaxLength) ->
MaxLength;
longest_line(Mat, Row, Cols, Dp, MaxLength) ->
... | dolphin |
Please focus on the efficiency of this problem and provide code in Dart:
Given an array of **distinct** integers `nums` and a target integer `target`, return _the number of possible combinations that add up to_ `target`.
The test cases are generated so that the answer can fit in a **32-bit** integer.
**Example 1:**
... | dolphin |
port this code from Haskell to R:
```haskell
data TreeNode = TreeNode { val :: Int, left :: Maybe TreeNode, right :: Maybe TreeNode }
longestConsecutive :: Maybe TreeNode -> Int
longestConsecutive Nothing = 0
longestConsecutive (Just root) = longestConsecutiveSequence root longestPath
where
longestPath = [0]
lo... | dolphin |
Please write the following solution using python:
On an alphabet board, we start at position `(0, 0)`, corresponding to character `board[0][0]`.
Here, `board = [ "abcde ", "fghij ", "klmno ", "pqrst ", "uvwxy ", "z "]`, as shown in the diagram below.
We may make the following moves:
* `'U'` moves our position up o... | dolphin |
Please write the following solution using Swift:
Given an array `nums` with `n` integers, your task is to check if it could become non-decreasing by modifying **at most one element**.
We define an array is non-decreasing if `nums[i] <= nums[i + 1]` holds for every `i` (**0-based**) such that (`0 <= i <= n - 2`).
**Ex... | dolphin |
port this code to Erlang:
```python
def maxAbsoluteSum(nums):
max_sum = max_end = min_sum = min_end = 0
for num in nums:
max_end = max(max_end + num, num)
min_end = min(min_end + num, num)
max_sum = max(max_sum, max_end)
min_sum = min(min_sum, min_end)
return max(max_sum, -mi... | dolphin |
translate this code to Object Pascal:
```erlang
min_difference(Nums) ->
N = length(Nums) div 3,
Prefix = lists:duplicate(N+2, 0),
Suffix = lists:duplicate(N+2, 0),
Window = lists:sort(lists:sublist(Nums, N)),
lists:nth(1, Prefix, sum(Window)),
P = lists:foldl(fun(I, [_H|T]) ->
[Next|_R] ... | dolphin |
Please explain the following problem in detail and provide code in c++:
Given a **0-indexed** integer array `nums` of length `n` and an integer `k`, return _the **number of pairs**_ `(i, j)` _where_ `0 <= i < j < n`, _such that_ `nums[i] == nums[j]` _and_ `(i * j)` _is divisible by_ `k`.
**Example 1:**
**Input:** num... | dolphin |
Please explain the reasoning behind the following solution and provide code in Erlang:
You are given an `n x n` binary grid `board`. In each move, you can swap any two rows with each other, or any two columns with each other.
Return _the minimum number of moves to transform the board into a **chessboard board**_. If t... | dolphin |
translate this code from Object Pascal to PHP:
```pascal
function maxTastiness(price: array of Integer; tastiness: array of Integer; maxAmount: Integer; maxCoupons: Integer): Integer;
var
n, i, j, k, fruit_price, fruit_tastiness, half_fruit_price: Integer;
dp: array of array of array of Integer;
begin
n := Length... | dolphin |
Please explain the reasoning behind the following solution and provide code in C#:
Given the `root` of a binary tree, return _the number of **uni-value**_ _subtrees_.
A **uni-value subtree** means all nodes of the subtree have the same value.
**Example 1:**
**Input:** root = \[5,1,5,5,5,null,5\]
**Output:** 4
**Exa... | dolphin |
Please write the following solution using Haskell:
**Reversing** an integer means to reverse all its digits.
* For example, reversing `2021` gives `1202`. Reversing `12300` gives `321` as the **leading zeros are not retained**.
Given an integer `num`, **reverse** `num` to get `reversed1`, **then reverse** `reversed... | dolphin |
Please explain the following problem in detail and provide code in Dart:
Given a string `s` and a string array `dictionary`, return _the longest string in the dictionary that can be formed by deleting some of the given string characters_. If there is more than one possible result, return the longest word with the small... | dolphin |
Please write the following solution using Lua:
The **product sum** of two equal-length arrays `a` and `b` is equal to the sum of `a[i] * b[i]` for all `0 <= i < a.length` (**0-indexed**).
* For example, if `a = [1,2,3,4]` and `b = [5,2,3,1]`, the **product sum** would be `1*5 + 2*2 + 3*3 + 4*1 = 22`.
Given two arra... | dolphin |
Please explain the following problem in detail and provide code in Ruby:
You are given a personal information string `s`, representing either an **email address** or a **phone number**. Return _the **masked** personal information using the below rules_.
**Email address:**
An email address is:
* A **name** consisti... | dolphin |
Please explain the following problem in detail and provide code in Object Pascal:
You are given a string `num` representing a large integer. An integer is **good** if it meets the following conditions:
* It is a **substring** of `num` with length `3`.
* It consists of only one unique digit.
Return _the **maximum ... | dolphin |
Please write the following solution using Go:
Given an array of integers `citations` where `citations[i]` is the number of citations a researcher received for their `ith` paper and `citations` is sorted in **ascending order**, return _the researcher's h-index_.
According to the [definition of h-index on Wikipedia](htt... | dolphin |
Please explain the reasoning behind the following solution and provide code in Lua:
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 ... | dolphin |
translate this code from Elixir to Ruby:
```elixir
defmodule Solution do
def latest_time(arr) do
combinations = Enum.permutations(arr)
latest_time = "00:00"
for combination <- combinations do
hour = combination |> Enum.take(2) |> Enum.join() |> String.to_integer()
minute = combination |> Enum.... | dolphin |
Please explain the following problem in detail and provide code in Visual Basic .NET:
Given the `root` of a binary search tree, a `target` value, and an integer `k`, return _the_ `k` _values in the BST that are closest to the_ `target`. You may return the answer in **any order**.
You are **guaranteed** to have only on... | dolphin |
convert this code from Haskell to Rust:
```haskell
uniquePaths :: Int -> Int -> Int
uniquePaths m n = last $ foldl (\prevRow _ -> 1 : zipWith (+) prevRow (tail prevRow)) (replicate n 1) [1..m-1]
``` | dolphin |
Please explain the reasoning behind the following solution and provide code in Go:
You are given a **0-indexed** 2D integer array `grid` of size `m x n`. Each cell has one of two values:
* `0` represents an **empty** cell,
* `1` represents an **obstacle** that may be removed.
You can move up, down, left, or right... | dolphin |
convert this code to Perl:
```c
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
int countUnivalSubtrees(struct TreeNode* root){
int count = 0;
if (root == NULL)
return count;
bool helper(struct TreeNode* node){
... | dolphin |
port this code from Julia to Rust:
```julia
function findLengthOfShortestSubarray(arr::Array{Int, 1})
n = length(arr)
left, right = 1, n
while left < n && arr[left] <= arr[left + 1]
left += 1
end
if left == n
return 0
end
while right > 1 && arr[right] >= arr[right - 1]
... | dolphin |
Please focus on the functionality of this problem and provide code in python:
**Tic-tac-toe** is played by two players `A` and `B` on a `3 x 3` grid. The rules of Tic-Tac-Toe are:
* Players take turns placing characters into empty squares `' '`.
* The first player `A` always places `'X'` characters, while the seco... | dolphin |
Please explain the following problem in detail and provide code in Kotlin:
You are given an integer array `nums`. You are initially positioned at the array's **first index**, and each element in the array represents your maximum jump length at that position.
Return `true` _if you can reach the last index, or_ `false` ... | dolphin |
Please explain the following problem in detail and provide code in PHP:
Given a 2D integer array `circles` where `circles[i] = [xi, yi, ri]` represents the center `(xi, yi)` and radius `ri` of the `ith` circle drawn on a grid, return _the **number of lattice points**_ _that are present inside **at least one** circle_.
... | dolphin |
Please focus on the functionality of this problem and provide code in F#:
You have a video sharing platform where users can upload and delete videos. Each `video` is a **string** of digits, where the `ith` digit of the string represents the content of the video at minute `i`. For example, the first digit represents the... | dolphin |
Please explain the reasoning behind the following solution and provide code in Clojure:
Given an array of strings `names` of size `n`. You will create `n` folders in your file system **such that**, at the `ith` minute, you will create a folder with the name `names[i]`.
Since two files **cannot** have the same name, if... | dolphin |
Please write the following solution using Kotlin:
Given an integer array `nums`, return _the length of the longest **strictly increasing**_ _**subsequence**_.
**Example 1:**
**Input:** nums = \[10,9,2,5,3,7,101,18\]
**Output:** 4
**Explanation:** The longest increasing subsequence is \[2,3,7,101\], therefore the leng... | dolphin |
Please explain the following problem in detail and provide code in Dart:
The **diameter** of a tree is **the number of edges** in the longest path in that tree.
There is an undirected tree of `n` nodes labeled from `0` to `n - 1`. You are given a 2D array `edges` where `edges.length == n - 1` and `edges[i] = [ai, bi]`... | dolphin |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.