instruction_seed stringlengths 29 40.5k | source stringclasses 6
values |
|---|---|
Please explain the reasoning behind the following solution and provide code in F#:
You are given an integer array `coins` representing coins of different denominations and an integer `amount` representing a total amount of money.
Return _the number of combinations that make up that amount_. If that amount of money can... | dolphin |
Please write the following solution using Julia:
Given an alphanumeric string `s`, return _the **second largest** numerical digit that appears in_ `s`_, or_ `-1` _if it does not exist_.
An **alphanumeric** string is a string consisting of lowercase English letters and digits.
**Example 1:**
**Input:** s = "dfa12321... | dolphin |
Please write the following solution using c++:
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, **group** the digits from left to right int... | dolphin |
translate this code from Perl to Dart:
```perl
sub sum_numbers {
my ($root, $cur) = @_;
$cur //= 0;
return 0 if !$root;
$cur = $cur * 10 + $root->{val};
return $cur if !$root->{left} && !$root->{right};
return sum_numbers($root->{left}, $cur) + sum_numbers($root->{right}, $cur);
}
``` | dolphin |
Please explain the reasoning behind the following solution and provide code in python:
The **width** of a sequence is the difference between the maximum and minimum elements in the sequence.
Given an array of integers `nums`, return _the sum of the **widths** of all the non-empty **subsequences** of_ `nums`. Since the... | dolphin |
convert this code to Mojo:
```scheme
(define (correct-binary-tree root)
(let ((stack '())
(curr root)
(prev #f))
(while #t
(while curr
(set! stack (cons curr stack))
(set! curr (node-right curr)))
(if (null? stack)
(break))
(let ((node (pop stack)))
... | dolphin |
Please explain the reasoning behind the following solution and provide code in Lua:
You are given a string `sentence` containing words separated by spaces, and an integer `k`. Your task is to separate `sentence` into **rows** where the number of characters in each row is **at most** `k`. You may assume that `sentence` ... | dolphin |
Please write the following solution using Scheme:
There are `n` gas stations along a circular route, where the amount of gas at the `ith` station is `gas[i]`.
You have a car with an unlimited gas tank and it costs `cost[i]` of gas to travel from the `ith` station to its next `(i + 1)th` station. You begin the journey ... | dolphin |
translate this code from Erlang to Scala:
```erlang
-module(worker).
-export([worker_with_longest_task/2]).
worker_with_longest_task(N, Logs) ->
Result = 0,
MaxTime = element(2, lists:nth(1, Logs)),
worker_with_longest_task(2, Logs, MaxTime, Result).
worker_with_longest_task(I, Logs, MaxTime, Result) whe... | dolphin |
port this code to R:
```fsharp
let max_score nums k =
let pq = nums |> Seq.map (fun x -> -x) |> Heap.ofSeq
let mutable score = 0
for i = 1 to k do
let cur = -Heap.top pq
score <- score + cur
pq.removeTop()
pq.add (ceil(float cur / float 3) |> int |> (-))
score
`... | dolphin |
Please write the following solution using java:
You are given the `root` of a binary tree with `n` nodes where each `node` in the tree has `node.val` coins. There are `n` coins in total throughout the whole tree.
In one move, we may choose two adjacent nodes and move one coin from one node to another. A move may be fr... | dolphin |
Please explain the reasoning behind the following solution and provide code in Object Pascal:
An integer array is called arithmetic if it consists of **at least three elements** and if the difference between any two consecutive elements is the same.
* For example, `[1,3,5,7,9]`, `[7,7,7,7]`, and `[3,-1,-5,-9]` are a... | dolphin |
Please write the following solution using Haskell:
Given an array `nums`. We define a running sum of an array as `runningSum[i] = sum(nums[0]...nums[i])`.
Return the running sum of `nums`.
**Example 1:**
**Input:** nums = \[1,2,3,4\]
**Output:** \[1,3,6,10\]
**Explanation:** Running sum is obtained as follows: \[1, ... | dolphin |
Please explain the reasoning behind the following solution and provide code in Fortran:
You are given an array of points in the **X-Y** plane `points` where `points[i] = [xi, yi]`.
Return _the minimum area of any rectangle formed from these points, with sides **not necessarily parallel** to the X and Y axes_. If there... | dolphin |
port this code from javascript to C#:
```javascript
function numRabbits(answers) {
const count = new Map();
let rabbits = 0;
for(let ans of answers) {
count.set(ans, (count.get(ans) || 0) + 1);
}
for(let [ans, cnt] of count.entries()) {
rabbits += Math.floor((ans + cnt) / (ans + 1)) ... | dolphin |
Please explain the reasoning behind the following solution and provide code in F#:
You are given a positive integer `n` representing the number of nodes in an **undirected** graph. The nodes are labeled from `1` to `n`.
You are also given a 2D integer array `edges`, where `edges[i] = [ai, bi]` indicates that there is ... | dolphin |
Please write the following solution using Mojo:
Given two strings `a` and `b`, return _the length of the **longest uncommon subsequence** between_ `a` _and_ `b`. If the longest uncommon subsequence does not exist, return `-1`.
An **uncommon subsequence** between two strings is a string that is a **subsequence of one b... | dolphin |
Please focus on the functionality of this problem and provide code in Rust:
There is an undirected connected tree with `n` nodes labeled from `0` to `n - 1` and `n - 1` edges.
You are given a **0-indexed** integer array `nums` of length `n` where `nums[i]` represents the value of the `ith` node. You are also given a 2... | dolphin |
Please explain the following problem in detail and provide code in Lua:
Given a binary string `s` **without leading zeros**, return `true` _if_ `s` _contains **at most one contiguous segment of ones**_. Otherwise, return `false`.
**Example 1:**
**Input:** s = "1001 "
**Output:** false
**Explanation:** The on... | dolphin |
Please write the following solution using Go:
There are three stones in different positions on the X-axis. You are given three integers `a`, `b`, and `c`, the positions of the stones.
In one move, you pick up a stone at an endpoint (i.e., either the lowest or highest position stone), and move it to an unoccupied posit... | dolphin |
Please explain the reasoning behind the following solution and provide code in PHP:
You are given an array of people, `people`, which are the attributes of some people in a queue (not necessarily in order). Each `people[i] = [hi, ki]` represents the `ith` person of height `hi` with **exactly** `ki` other people in fron... | dolphin |
Please write the following solution using Groovy:
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.val == 2 * x + 2`
Now the bina... | dolphin |
Please write the following solution using Haskell:
Given a **0-indexed** integer array `nums` of size `n` and two integers `lower` and `upper`, return _the number of fair pairs_.
A pair `(i, j)` is **fair** if:
* `0 <= i < j < n`, and
* `lower <= nums[i] + nums[j] <= upper`
**Example 1:**
**Input:** nums = \[0,... | dolphin |
Please focus on the efficiency of this problem and provide code in Lua:
You are given an array of `logs`. Each log is a space-delimited string of words, where the first word is the **identifier**.
There are two types of logs:
* **Letter-logs**: All words (except the identifier) consist of lowercase English letters.... | dolphin |
Please write the following solution using c++:
Given an array of integers `nums` containing `n + 1` integers where each integer is in the range `[1, n]` inclusive.
There is only **one repeated number** in `nums`, return _this repeated number_.
You must solve the problem **without** modifying the array `nums` and uses... | dolphin |
Please explain the following problem in detail and provide code in c++:
Write an efficient algorithm that searches for a value `target` in an `m x n` integer matrix `matrix`. This matrix has the following properties:
* Integers in each row are sorted in ascending from left to right.
* Integers in each column are s... | dolphin |
Please explain the reasoning behind the following solution and provide code in ANSI C:
Given the roots of two binary trees `p` and `q`, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.
**Example 1:**
... | dolphin |
Please explain the reasoning behind the following solution and provide code in Dart:
There is an **undirected** graph with `n` nodes, where each node is numbered between `0` and `n - 1`. You are given a 2D array `graph`, where `graph[u]` is an array of nodes that node `u` is adjacent to. More formally, for each `v` in ... | dolphin |
translate this code from Lisp to F#:
```lisp
(defun max-gold (grid)
(let ((m (length grid))
(n (length (first grid))))
(let ((max-gold 0)
(dp (make-array (list m n))))
(dotimes (i m)
(dotimes (j n)
(when (> (aref grid i j) 0)
(setf (aref dp i j) (aref grid i j... | dolphin |
Please explain the reasoning behind the following solution and provide code in PHP:
Given an array of strings `words`, return `true` _if it forms a valid **word square**_.
A sequence of strings forms a valid **word square** if the `kth` row and column read the same string, where `0 <= k < max(numRows, numColumns)`.
*... | dolphin |
convert this code from Rust to java:
```rust
fn kth_smallest_subarray_sum(nums: &[i32], k: i32) -> i32 {
let n = nums.len();
let mut left = nums.iter().min().unwrap().clone();
let mut right = nums.iter().sum();
while left < right {
let mid = (left + right) / 2;
let mut count = 0;
... | dolphin |
translate this code to Clojure:
```php
class PolyNode {
public $coefficient;
public $power;
public $next;
function __construct($c, $p, $next = null) {
$this->coefficient = $c;
$this->power = $p;
$this->next = $next;
}
}
function addPoly($poly1, $poly2) {
$dummy = ne... | dolphin |
Please write the following solution using Haskell:
You are given an array `routes` representing bus routes where `routes[i]` is a bus route that the `ith` bus repeats forever.
* For example, if `routes[0] = [1, 5, 7]`, this means that the `0th` bus travels in the sequence `1 -> 5 -> 7 -> 1 -> 5 -> 7 -> 1 -> ...` for... | dolphin |
port this code from Scheme to Erlang:
```scheme
(define (maximum-swap num)
(define num-str (string->list (number->string num)))
(define last (make-hash))
(do ((i 0 (+ i 1))) ((= i (string-length num-str)))
(hash-set! last (char->integer (list-ref num-str i)) i))
(do ((i 0 (+ i 1))) ((= i (string-lengt... | dolphin |
Please write the following solution using Fortran:
You are given a **0-indexed** array of strings `words` and a 2D array of integers `queries`.
Each query `queries[i] = [li, ri]` asks us to find the number of strings present in the range `li` to `ri` (both **inclusive**) of `words` that start and end with a vowel.
Re... | dolphin |
Please focus on the efficiency of this problem and provide code in Rust:
You have observations of `n + m` **6-sided** dice rolls with each face numbered from `1` to `6`. `n` of the observations went missing, and you only have the observations of `m` rolls. Fortunately, you have also calculated the **average value** of ... | dolphin |
Please explain the following problem in detail and provide code in TypeScript:
Given an `n x n` binary `grid`, in one step you can choose two **adjacent rows** of the grid and swap them.
A grid is said to be **valid** if all the cells above the main diagonal are **zeros**.
Return _the minimum number of steps_ needed ... | dolphin |
convert this code to Julia:
```cpp
#include <vector>
using namespace std;
int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
bool isGoodArray(vector<int>& nums) {
int res = nums[0];
for (int num : nums) {
res = gcd(res, num);
}
return res == 1;
}
```
| dolphin |
Please explain the reasoning behind the following solution and provide code in Haskell:
Given a positive integer `num`, return _the number of positive integers **less than or equal to**_ `num` _whose digit sums are **even**_.
The **digit sum** of a positive integer is the sum of all its digits.
**Example 1:**
**Inpu... | dolphin |
Please explain the reasoning behind the following solution and provide code in Fortran:
Given a string `s` and an integer `k`, return `true` if `s` is a `k`**\-palindrome**.
A string is `k`**\-palindrome** if it can be transformed into a palindrome by removing at most `k` characters from it.
**Example 1:**
**Input:*... | dolphin |
Please write the following solution using Julia:
Given a string `date` representing a [Gregorian calendar](https://en.wikipedia.org/wiki/Gregorian_calendar) date formatted as `YYYY-MM-DD`, return _the day number of the year_.
**Example 1:**
**Input:** date = "2019-01-09 "
**Output:** 9
**Explanation:** Given date is... | dolphin |
convert this code from Perl to Scheme:
```perl
sub checkPossibility {
my ($nums) = @_;
my $cnt = 0;
for my $i (1 .. @$nums - 1) {
if ($nums->[$i] < $nums->[$i - 1]) {
$cnt++;
if ($i == 1 || $nums->[$i] >= $nums->[$i - 2]) {
$nums->[$i - 1] = $nums->[$i];
... | dolphin |
Please explain the following problem in detail and provide code in Rust:
You are given an `m x n` matrix `M` initialized with all `0`'s and an array of operations `ops`, where `ops[i] = [ai, bi]` means `M[x][y]` should be incremented by one for all `0 <= x < ai` and `0 <= y < bi`.
Count and return _the number of maxim... | dolphin |
Please explain the following problem in detail and provide code in Groovy:
You may recall that an array `arr` is a **mountain array** if and only if:
* `arr.length >= 3`
* There exists some index `i` (**0-indexed**) with `0 < i < arr.length - 1` such that:
* `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]`
... | dolphin |
Please explain the reasoning behind the following solution and provide code in TypeScript:
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 "... | dolphin |
Please write the following solution using Go:
There is an undirected tree with `n` nodes labeled from `0` to `n - 1` and `n - 1` edges.
You are given a 2D integer array `edges` of length `n - 1` where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi` in the tree. You are also given an i... | dolphin |
Please explain the following problem in detail and provide code in Elixir:
An array `A` is larger than some array `B` if for the first index `i` where `A[i] != B[i]`, `A[i] > B[i]`.
For example, consider `0`\-indexing:
* `[1,3,2,4] > [1,2,2,4]`, since at index `1`, `3 > 2`.
* `[1,4,4,4] < [2,1,1,1]`, since at ind... | dolphin |
Please write the following solution using Clojure:
International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows:
* `'a'` maps to `".- "`,
* `'b'` maps to `"-... "`,
* `'c'` maps to `"-.-. "`, and so on.
For convenience, the full table for the `26` l... | dolphin |
translate this code to TypeScript:
```clojure
(defn cheapest-jump [coins max-jump]
(let [n (count coins)
dp (vec (repeat n Float/POSITIVE_INFINITY))
parent (vec (repeat n -1))]
(assoc dp 0 (first coins))
(doseq [i (range n)
:when (not= -1 (nth coins i))
j (range 1 (inc ... | dolphin |
Please write the following solution using c++:
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 tre... | dolphin |
Please explain the following problem in detail and provide code in Go:
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 one unique set of... | dolphin |
Please explain the reasoning behind the following solution and provide code in Julia:
Given a 2D integer array `nums`, return _all elements of_ `nums` _in diagonal order as shown in the below images_.
**Example 1:**
**Input:** nums = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\]
**Output:** \[1,4,2,7,5,3,8,6,9\]
**Example 2:**
... | dolphin |
Please explain the reasoning behind the following solution and provide code in Scala:
You are given two integer arrays of equal length `target` and `arr`. In one step, you can select any **non-empty subarray** of `arr` and reverse it. You are allowed to make any number of steps.
Return `true` _if you can make_ `arr` _... | dolphin |
Please write the following solution using R:
Given a **0-indexed** integer array `nums` of size `n` and two integers `lower` and `upper`, return _the number of fair pairs_.
A pair `(i, j)` is **fair** if:
* `0 <= i < j < n`, and
* `lower <= nums[i] + nums[j] <= upper`
**Example 1:**
**Input:** nums = \[0,1,7,4,... | dolphin |
Please explain the reasoning behind the following solution and provide code in Ruby:
Given an integer array `nums` which is sorted in **ascending order** and all of its elements are **unique** and given also an integer `k`, return the `kth` missing number starting from the leftmost number of the array.
**Example 1:**
... | dolphin |
Please write the following solution using Groovy:
Given two nodes of a binary tree `p` and `q`, return _their lowest common ancestor (LCA)_.
Each node will have a reference to its parent node. The definition for `Node` is below:
class Node {
public int val;
public Node left;
public Node right;
public ... | dolphin |
Please focus on the efficiency of this problem and provide code in Clojure:
There is a donuts shop that bakes donuts in batches of `batchSize`. They have a rule where they must serve **all** of the donuts of a batch before serving any donuts of the next batch. You are given an integer `batchSize` and an integer array `... | dolphin |
translate this code to Fortran:
```dart
class MyHashSet {
List<bool> storage;
MyHashSet() {
storage = List.filled(1000001, false);
}
void add(int key) {
storage[key] = true;
}
void remove(int key) {
storage[key] = false;
}
bool contains(int key) {
return storage[key];
}
}
``` | dolphin |
convert this code to Scala:
```go
func multiply(mat1 [][]int, mat2 [][]int) [][]int {
m, k, n := len(mat1), len(mat1[0]), len(mat2[0])
result := make([][]int, m)
for i := 0; i < m; i++ {
result[i] = make([]int, n)
}
for i := 0; i < m; i++ {
for j := 0; j < k; j++ {
if mat... | dolphin |
translate this code from Go to Groovy:
```go
package main
import "fmt"
func hammingWeight(n uint32) int {
count := 0
for n != 0 {
count++
n &= n - 1
}
return count
}
func main() {
fmt.Println(hammingWeight(00000000000000000000000000001011)) // Output: 3
fmt.Println(hammingWeig... | dolphin |
convert this code from Haskell to PHP:
```haskell
removeDuplicateLetters :: String -> String
removeDuplicateLetters s = reverse $ go s [] count visited
where
count = [0 | _ <- [0..255]]
visited = [False | _ <- [0..255]]
go [] st _ _ = st
go (ch:xs) st count visited
| visited !! fromEnum ch = ... | dolphin |
Please explain the reasoning behind the following solution and provide code in C#:
You are playing a variation of the game Zuma.
In this variation of Zuma, there is a **single row** of colored balls on a board, where each ball can be colored red `'R'`, yellow `'Y'`, blue `'B'`, green `'G'`, or white `'W'`. You also ha... | dolphin |
Please write the following solution using Scala:
You are given an integer `num.` **Rearrange** the digits of `num` such that its value is **minimized** and it does not contain **any** leading zeros.
Return _the rearranged number with minimal value_.
Note that the sign of the number does not change after rearranging t... | dolphin |
translate this code from Erlang to Elixir:
```erlang
%% longest_increasing_path function
longest_increasing_path(Matrix) ->
M = length(Matrix),
N = length(hd(Matrix)),
Memo = lists:duplicate(M, lists:duplicate(N, 0)),
MaxLen = lists:foldl(fun(I, Acc) ->
lists:foldl(fun(J,... | dolphin |
Please write the following solution using Julia:
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 content at minute `0` in... | dolphin |
convert this code from Julia to Scheme:
```julia
function find_lucky(arr)
freq = Dict()
for num in arr
freq[num] = get(freq, num, 0) + 1
end
max_lucky = -1
for (num, count) in freq
if num == count
max_lucky = max(max_lucky, num)
end
end
return max_lucky
en... | dolphin |
Please explain the following problem in detail and provide code in Ruby:
Design an algorithm to encode **a list of strings** to **a string**. The encoded string is then sent over the network and is decoded back to the original list of strings.
Machine 1 (sender) has the function:
string encode(vector strs) {
// ...... | dolphin |
Please write the following solution using Dart:
You are given a **0-indexed** integer array `nums` consisting of `n` non-negative integers.
You are also given an array `queries`, where `queries[i] = [xi, yi]`. The answer to the `ith` query is the sum of all `nums[j]` where `xi <= j < n` and `(j - xi)` is divisible by ... | dolphin |
translate this code to Scheme:
```cpp
#include <string>
std::string toLowerCase(std::string s) {
for (char& c : s) {
if (c >= 'A' && c <= 'Z') {
c = c - 'A' + 'a';
}
}
return s;
}
```
| dolphin |
convert this code from Haskell to R:
```haskell
import Data.List (foldl')
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
type Graph = Map Int [Int]
gardenNoAdj :: Int -> [[Int]] -> [Int]
gardenNoAdj n paths = result
where
graph = foldl' (\g [x, y] -> Map.insertWith (++) x [y] (Map.insertWi... | dolphin |
Please explain the reasoning behind the following solution and provide code in PHP:
You are given an integer array `rolls` of length `n` and an integer `k`. You roll a `k` sided dice numbered from `1` to `k`, `n` times, where the result of the `ith` roll is `rolls[i]`.
Return _the length of the **shortest** sequence o... | dolphin |
Please write the following solution using Scala:
You are given an array of strings `ideas` that represents a list of names to be used in the process of naming a company. The process of naming a company is as follows:
1. Choose 2 **distinct** names from `ideas`, call them `ideaA` and `ideaB`.
2. Swap the first letter... | dolphin |
Please explain the reasoning behind the following solution and provide code in Lisp:
You're given strings `jewels` representing the types of stones that are jewels, and `stones` representing the stones you have. Each character in `stones` is a type of stone you have. You want to know how many of the stones you have are... | dolphin |
translate this code from Visual Basic .NET to Lua:
```vb
Public Function LongestPalindromeSubseq(ByVal s As String) As Integer
Dim n As Integer = s.Length
Dim dp(n, n) As Integer
For i As Integer = n - 1 To 0 Step -1
dp(i, i) = 1
For j As Integer = i + 1 To n - 1
If s(i) = s(j) T... | dolphin |
Please focus on the efficiency of this problem and provide code in Groovy:
You are given the `root` of a binary tree and an integer `distance`. A pair of two different **leaf** nodes of a binary tree is said to be good if the length of **the shortest path** between them is less than or equal to `distance`.
Return _the... | dolphin |
Please explain the reasoning behind the following solution and provide code in F#:
You are given a **0-indexed** array of strings `nums`, where each string is of **equal length** and consists of only digits.
You are also given a **0-indexed** 2D integer array `queries` where `queries[i] = [ki, trimi]`. For each `queri... | dolphin |
convert this code to F#:
```lua
function bag_of_tokens_score(tokens, power)
table.sort(tokens)
local max_score, score = 0, 0
local left, right = 1, #tokens
while left <= right do
if power >= tokens[left] then
power = power - tokens[left]
left = left + 1
score... | dolphin |
Please write the following solution using Objective-C:
You are given an integer array `nums` with no duplicates. A **maximum binary tree** can be built recursively from `nums` using the following algorithm:
1. Create a root node whose value is the maximum value in `nums`.
2. Recursively build the left subtree on the... | dolphin |
port this code from Object Pascal to F#:
```pascal
function minTimeToVisitAllPoints(points: array of array of integer): integer;
var
time, dx, dy: integer;
i: integer;
begin
time := 0;
for i := 1 to length(points) - 1 do
begin
dx := abs(points[i][0] - points[i - 1][0]);
dy := abs(points[i][1] - points... | dolphin |
Please focus on the algorithm of this problem and provide code in Rust:
Given a string `num` which represents an integer, return `true` _if_ `num` _is a **strobogrammatic number**_.
A **strobogrammatic number** is a number that looks the same when rotated `180` degrees (looked at upside down).
**Example 1:**
**Input... | dolphin |
Please write the following solution using Swift:
You have `n` packages that you are trying to place in boxes, **one package in each box**. There are `m` suppliers that each produce boxes of **different sizes** (with infinite supply). A package can be placed in a box if the size of the package is **less than or equal to... | dolphin |
Please write the following solution using Mojo:
You are given two **0-indexed** integer arrays `nums1` and `nums2` of equal length `n` and a positive integer `k`. You must choose a **subsequence** of indices from `nums1` of length `k`.
For chosen indices `i0`, `i1`, ..., `ik - 1`, your **score** is defined as:
* Th... | dolphin |
Please write the following solution using python:
Given a string array `words`, return _an array of all characters that show up in all strings within the_ `words` _(including duplicates)_. You may return the answer in **any order**.
**Example 1:**
**Input:** words = \["bella","label","roller"\]
**Output:** \["e","l",... | dolphin |
Please explain the reasoning behind the following solution and provide code in java:
You are given a **0-indexed** integer array `mapping` which represents the mapping rule of a shuffled decimal system. `mapping[i] = j` means digit `i` should be mapped to digit `j` in this system.
The **mapped value** of an integer is... | dolphin |
Please explain the reasoning behind the following solution and provide code in PHP:
You are asked to cut off all the trees in a forest for a golf event. The forest is represented as an `m x n` matrix. In this matrix:
* `0` means the cell cannot be walked through.
* `1` represents an empty cell that can be walked t... | dolphin |
Please explain the following problem in detail and provide code in Dart:
You are given an `m x n` binary matrix `grid`.
A **move** consists of choosing any row or column and toggling each value in that row or column (i.e., changing all `0`'s to `1`'s, and all `1`'s to `0`'s).
Every row of the matrix is interpreted as... | dolphin |
convert this code to Dart:
```csharp
public class Solution {
public IList<string> WordBreak(string s, IList<string> wordDict) {
var memo = new Dictionary<string, List<string>>();
var wordSet = new HashSet<string>(wordDict);
return DFS(s, wordSet, memo);
}
private List<string> DF... | dolphin |
port this code to Elixir:
```perl
sub magnetic_force {
my ($position, $m) = @_;
my $n = scalar(@$position);
@$position = sort {$a <=> $b} @$position;
my $left = 1;
my $right = $position->[$n-1] - $position->[0];
my $result = 0;
while ($left <= $right) {
my $mid = int(($left + $right)... | dolphin |
Please write the following solution using Swift:
You are currently designing a dynamic array. You are given a **0-indexed** integer array `nums`, where `nums[i]` is the number of elements that will be in the array at time `i`. In addition, you are given an integer `k`, the **maximum** number of times you can **resize**... | dolphin |
port this code to PHP:
```
(define (decode encoded)
(define n (+ (length encoded) 1))
(define (xor-all-from-1-to-n)
(define (helper i acc)
(if (> i n)
acc
(helper (+ i 1) (bitwise-xor acc i))))
(helper 1 0))
(define total-xor (xor-all-from-1-to-n))
(define (xor-all-even-... | dolphin |
Please focus on the algorithm of this problem and provide code in Ruby:
You have `n` packages that you are trying to place in boxes, **one package in each box**. There are `m` suppliers that each produce boxes of **different sizes** (with infinite supply). A package can be placed in a box if the size of the package is ... | dolphin |
Please write the following solution using Visual Basic .NET:
You are given an array `points` representing integer coordinates of some points on a 2D-plane, where `points[i] = [xi, yi]`.
The cost of connecting two points `[xi, yi]` and `[xj, yj]` is the **manhattan distance** between them: `|xi - xj| + |yi - yj|`, wher... | dolphin |
Please write the following solution using Visual Basic .NET:
You are given an integer array `height` of length `n`. There are `n` vertical lines drawn such that the two endpoints of the `ith` line are `(i, 0)` and `(i, height[i])`.
Find two lines that together with the x-axis form a container, such that the container ... | dolphin |
Please explain the reasoning behind the following solution and provide code in Perl:
You have `n` binary tree nodes numbered from `0` to `n - 1` where node `i` has two children `leftChild[i]` and `rightChild[i]`, return `true` if and only if **all** the given nodes form **exactly one** valid binary tree.
If node `i` h... | dolphin |
port this code from Scheme to Objective-C:
```scheme
(define (is-concatenated word word-set)
(let ((n (string-length word))
(dp (make-vector (+ n 1) #f)))
(vector-set! dp 0 #t)
(do ((i 1 (+ i 1)))
((> i n))
(do ((j 0 (+ j 1)))
((> j i))
(when (and (vector-ref dp j)
... | dolphin |
Please write the following solution using javascript:
You are given an integer array `banned` and two integers `n` and `maxSum`. You are choosing some number of integers following the below rules:
* The chosen integers have to be in the range `[1, n]`.
* Each integer can be chosen **at most once**.
* The chosen ... | dolphin |
Please explain the following problem in detail and provide code in Kotlin:
Implement [pow(x, n)](http://www.cplusplus.com/reference/valarray/pow/), which calculates `x` raised to the power `n` (i.e., `xn`).
**Example 1:**
**Input:** x = 2.00000, n = 10
**Output:** 1024.00000
**Example 2:**
**Input:** x = 2.10000, n... | dolphin |
Please explain the reasoning behind the following solution and provide code in Elixir:
A **boolean expression** is an expression that evaluates to either `true` or `false`. It can be in one of the following shapes:
* `'t'` that evaluates to `true`.
* `'f'` that evaluates to `false`.
* `'!(subExpr)'` that evaluat... | dolphin |
convert this code to Julia:
```csharp
public bool IsValidPreorder(int[] preorder) {
Stack<int> stack = new Stack<int>();
int lowerBound = int.MinValue;
foreach (int num in preorder) {
if (num < lowerBound) {
return false;
}
while (stack.Count > 0 && num > stack.Peek()) {
... | dolphin |
translate this code to Erlang:
```dart
bool canDestroyAll(int mass, List<int> asteroids) {
asteroids.sort();
for (int asteroid in asteroids) {
if (mass >= asteroid) {
mass += asteroid;
} else {
return false;
}
}
return true;
}
``` | dolphin |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.