instruction_seed
stringlengths
29
40.5k
source
stringclasses
6 values
Please write the following solution using java: 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 from and to an empty cell. Return...
dolphin
Please explain the following problem in detail and provide code in python: You are given a **0-indexed** integer array `candies`. Each element in the array denotes a pile of candies of size `candies[i]`. You can divide each pile into any number of **sub piles**, but you **cannot** merge two piles together. You are als...
dolphin
Please explain the reasoning behind the following solution and provide code in Scheme: You are assigned to put some amount of boxes onto **one truck**. You are given a 2D array `boxTypes`, where `boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]`: * `numberOfBoxesi` is the number of boxes of type `i`. * `number...
dolphin
Please explain the reasoning behind the following solution and provide code in Objective-C: You are given a **0-indexed** integer array `buses` of length `n`, where `buses[i]` represents the departure time of the `ith` bus. You are also given a **0-indexed** integer array `passengers` of length `m`, where `passengers[j...
dolphin
Please explain the following problem in detail and provide code in Lisp: Given a string array `words`, return _the maximum value of_ `length(word[i]) * length(word[j])` _where the two words do not share common letters_. If no such two words exist, return `0`. **Example 1:** **Input:** words = \[ "abcw ", "baz ", "foo...
dolphin
convert this code to java: ```lisp (defun three-array-intersection (arr1 arr2 arr3) (let ((i 0) (j 0) (k 0) (result '())) (loop while (and (< i (length arr1)) (< j (length arr2)) (< k (length arr3))) do (cond ((and (= (elt arr1 i) (elt arr2 j)) (= (elt arr2 j) (elt arr3 k))) ...
dolphin
Please explain the following problem in detail and provide code in R: 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**....
dolphin
Please explain the reasoning behind the following solution and provide code in Kotlin: Alice and Bob take turns playing a game, with Alice starting first. Initially, there is a number `n` on the chalkboard. On each player's turn, that player makes a move consisting of: * Choosing any `x` with `0 < x < n` and `n % x...
dolphin
port this code to Lua: ```pascal uses SysUtils, Classes, Generics.Collections; const WALL = -1; GATE = 0; INF = 2147483647; type TArray2D = array of array of Integer; TPoint = record X, Y: Integer; constructor Create(aX, aY: Integer); end; constructor TPoint.Create(aX, aY: Integer); begin X := ...
dolphin
Please explain the following problem in detail and provide code in R: You have `n` gardens, labeled from `1` to `n`, and an array `paths` where `paths[i] = [xi, yi]` describes a bidirectional path between garden `xi` to garden `yi`. In each garden, you want to plant one of 4 types of flowers. All gardens have **at mos...
dolphin
Please focus on the algorithm of this problem and provide code in Go: On a social network consisting of `m` users and some friendships between users, two users can communicate with each other if they know a common language. You are given an integer `n`, an array `languages`, and an array `friendships` where: * Ther...
dolphin
Please explain the reasoning behind the following solution and provide code in Julia: You are given a **0-indexed** 2D integer array `grid` of size `m x n` which represents a field. Each cell has one of three values: * `0` represents grass, * `1` represents fire, * `2` represents a wall that you and fire cannot ...
dolphin
convert this code to Scheme: ```typescript function findUnsortedSubarray(nums: number[]): number { const sortedNums = [...nums].sort((a, b) => a - b); let start = 0, end = nums.length - 1; while (start < nums.length && nums[start] === sortedNums[start]) { start++; } while (end > start && num...
dolphin
port this code from Visual Basic .NET to Kotlin: ```vb.net Function NumDecodings(s As String) As Integer Const MOD As Integer = 1000000007 Dim n As Integer = s.Length Dim dp(n) As Integer dp(0) = 1 dp(1) = If(s(0) = "*", 9, If(s(0) = "0", 0, 1)) For i As Integer = 2 To n Dim c As Char =...
dolphin
translate this code to Erlang: ```go type TreeNode struct { Val int Left *TreeNode Right *TreeNode } func pathSumHelper(node *TreeNode, targetSum int, currentSum int) int { if node == nil { return 0 } currentSum += node.Val totalPaths := 0 if currentSum == targetSum { ...
dolphin
convert this code to TypeScript: ```julia function hamming_weight(n::String) count = 0 for i in 1:32 count += parse(Int, n[i]) & 1 end return count end ```
dolphin
translate this code to R: ```javascript function powerfulIntegers(x, y, bound) { const max_i = x === 1 ? 0 : Math.floor(Math.log(bound) / Math.log(x)); const max_j = y === 1 ? 0 : Math.floor(Math.log(bound) / Math.log(y)); const resultSet = new Set(); for (let i = 0; i <= max_i; i++) { for ...
dolphin
port this code to Julia: ```python from collections import defaultdict def find_ancestors(node, adj_list, visited, ans): if visited[node]: return visited[node] = True for ancestor in adj_list[node]: ans.append(ancestor) find_ancestors(ancestor, adj_list, visited, ans) def find_ance...
dolphin
Please explain the reasoning behind the following solution and provide code in Go: Write a function that takes the binary representation of an unsigned integer and returns the number of '1' bits it has (also known as the [Hamming weight](http://en.wikipedia.org/wiki/Hamming_weight)). **Note:** * Note that in some l...
dolphin
Please explain the following problem in detail and provide code in Groovy: You are given an array of characters `letters` that is sorted in **non-decreasing order**, and a character `target`. There are **at least two different** characters in `letters`. Return _the smallest character in_ `letters` _that is lexicograph...
dolphin
Please write the following solution using Fortran: You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day. You want to maximize your profit by choosing a **single day** to buy one stock and choosing a **different day in the future** to sell that stock. Return _the maximum pro...
dolphin
port this code from Erlang to F#: ```erlang minimum_deletions(Strs) -> N = length(Strs), M = length(hd(Strs)), deletions(N, M, Strs, 0). deletions(N, M, Strs, Del) -> case M of 0 -> Del; _ -> case lists:foldl( fun(I, Acc) -> case lists:nth...
dolphin
Please explain the reasoning behind the following solution and provide code in F#: Given a string `s` and an integer `k`, return _the length of the longest substring of_ `s` _such that the frequency of each character in this substring is greater than or equal to_ `k`. **Example 1:** **Input:** s = "aaabb ", k = 3 **...
dolphin
convert this code from F# to Scheme: ```fsharp let mostVisited (n:int) (rounds:int[]) = let visited = Array.create (n + 1) 0 for i = 1 to Array.length rounds - 1 do let mutable start = rounds.[i-1] let mutable end_ = rounds.[i] while start <> end_ do visited.[start] <- v...
dolphin
port this code from Lisp to Fortran: ```lisp (defun can-place-flowers (flowerbed n) (let ((count 0)) (loop for i from 0 below (length flowerbed) when (and (= (nth i flowerbed) 0) (or (= i 0) (= (nth (1- i) flowerbed) 0)) (or (= i (1- (length flowerbed))) (= (nth (...
dolphin
Please focus on the algorithm of this problem and provide code in Visual Basic .NET: You are given an `m x n` `grid` where each cell can have one of three values: * `0` representing an empty cell, * `1` representing a fresh orange, or * `2` representing a rotten orange. Every minute, any fresh orange that is **...
dolphin
translate this code from C# to Julia: ```csharp public class Node { public bool val; public bool isLeaf; public Node topLeft; public Node topRight; public Node bottomLeft; public Node bottomRight; public Node(bool val, bool isLeaf, Node topLeft, Node topRight, Node bottomLeft, Node bott...
dolphin
Please focus on the efficiency of this problem and provide code in python: You are given two **0-indexed** arrays, `nums1` and `nums2`, consisting of non-negative integers. There exists another array, `nums3`, which contains the bitwise XOR of **all pairings** of integers between `nums1` and `nums2` (every integer in `...
dolphin
Please explain the reasoning behind the following solution and provide code in Erlang: You are given a string `s` consisting of the characters `'a'`, `'b'`, and `'c'` and a non-negative integer `k`. Each minute, you may take either the **leftmost** character of `s`, or the **rightmost** character of `s`. Return _the *...
dolphin
port this code from ANSI C to Groovy: ```c #include<stdio.h> #include<stdlib.h> #define mod 1000000007 int* getPowers(int n, int* size){ int* powers = (int*)malloc(sizeof(int) * 32); int i = 0; while(n > 0){ powers[i++] = n & (-n); n -= n & (-n); } *size = i; return powers; } ...
dolphin
translate this code to Kotlin: ```javascript class MyCircularDeque { constructor(k) { this.buffer = new Array(k); this.front = -1; this.rear = 0; this.capacity = k; } insertFront(value) { if (this.isFull()) { return false; } if (this.front...
dolphin
Please write the following solution using Lua: The **n-queens** puzzle is the problem of placing `n` queens on an `n x n` chessboard such that no two queens attack each other. Given an integer `n`, return _all distinct solutions to the **n-queens puzzle**_. You may return the answer in **any order**. Each solution co...
dolphin
Please write the following solution using Lua: You are given a **0-indexed** integer array `piles`, where `piles[i]` represents the number of stones in the `ith` pile, and an integer `k`. You should apply the following operation **exactly** `k` times: * Choose any `piles[i]` and **remove** `floor(piles[i] / 2)` ston...
dolphin
Please explain the following problem in detail and provide code in c++: There are several squares being dropped onto the X-axis of a 2D plane. You are given a 2D integer array `positions` where `positions[i] = [lefti, sideLengthi]` represents the `ith` square with a side length of `sideLengthi` that is dropped with it...
dolphin
Please explain the reasoning behind the following solution and provide code in Julia: Given a `m x n` `grid` filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path. **Note:** You can only move either down or right at any point in time. **Exam...
dolphin
Please write the following solution using Rust: We are given `hours`, a list of the number of hours worked per day for a given employee. A day is considered to be a _tiring day_ if and only if the number of hours worked is (strictly) greater than `8`. A _well-performing interval_ is an interval of days for which the ...
dolphin
Please write the following solution using R: Given a `m x n` binary matrix `mat`. In one step, you can choose one cell and flip it and all the four neighbors of it if they exist (Flip is changing `1` to `0` and `0` to `1`). A pair of cells are called neighbors if they share one edge. Return the _minimum number of step...
dolphin
Please explain the reasoning behind the following solution and provide code in ANSI C: A **Fibonacci** tree is a binary tree created using the order function `order(n)`: * `order(0)` is the empty tree. * `order(1)` is a binary tree with only **one node**. * `order(n)` is a binary tree that consists of a root nod...
dolphin
Please write the following solution using Elixir: Two strings `X` and `Y` are similar if we can swap two letters (in different positions) of `X`, so that it equals `Y`. Also two strings `X` and `Y` are similar if they are equal. For example, `"tars "` and `"rats "` are similar (swapping at positions `0` and `2`), and ...
dolphin
Please write the following solution using Dart: You are given an array `nums` consisting of positive integers. Split the array into **one or more** disjoint subarrays such that: * Each element of the array belongs to **exactly one** subarray, and * The **GCD** of the elements of each subarray is strictly greater ...
dolphin
convert this code to Lisp: ```go func aliceWins(colors string) bool { n := len(colors) aliceTurn := true for i := 1; i <= n-2; i++ { if aliceTurn && colors[i] == 'A' && colors[i-1] == 'A' && colors[i+1] == 'A' { colors[i] = ' ' aliceTurn = false } else if !aliceTurn &...
dolphin
translate this code to c++: ```perl sub remove_vowels { my ($s) = @_; my %vowels = ('a' => 1, 'e' => 1, 'i' => 1, 'o' => 1, 'u' => 1); my $new_s = ''; for my $i (0..length($s)-1) { my $char = substr($s, $i, 1); if (!$vowels{$char}) { $new_s .= $char; } } retur...
dolphin
port this code to Groovy: ```swift class TreeNode { var val: Int var left: TreeNode? var right: TreeNode? init(_ val: Int) { self.val = val } } func sumPaths(_ root: TreeNode?, _ val: Int) -> Int { guard let root = root else { return 0 } var val = val * 10 + root.val if roo...
dolphin
Please explain the reasoning behind the following solution and provide code in Kotlin: Given an array of `n` integers `nums` and an integer `target`, find the number of index triplets `i`, `j`, `k` with `0 <= i < j < k < n` that satisfy the condition `nums[i] + nums[j] + nums[k] < target`. **Example 1:** **Input:** n...
dolphin
Please focus on the algorithm of this problem and provide code in java: You are an ant tasked with adding `n` new rooms numbered `0` to `n-1` to your colony. You are given the expansion plan as a **0-indexed** integer array of length `n`, `prevRoom`, where `prevRoom[i]` indicates that you must build room `prevRoom[i]` ...
dolphin
Please explain the following problem in detail and provide code in java: You are given a 2D integer array `orders`, where each `orders[i] = [pricei, amounti, orderTypei]` denotes that `amounti` orders have been placed of type `orderTypei` at the price `pricei`. The `orderTypei` is: * `0` if it is a batch of `buy` or...
dolphin
Please focus on the algorithm of this problem and provide code in Objective-C: Given an `n x n` `matrix` where each of the rows and columns is sorted in ascending order, return _the_ `kth` _smallest element in the matrix_. Note that it is the `kth` smallest element **in the sorted order**, not the `kth` **distinct** e...
dolphin
Please explain the reasoning behind the following solution and provide code in Visual Basic .NET: You are given a string `s` consisting of only lowercase English letters. In one operation, you can: * Delete **the entire string** `s`, or * Delete the **first** `i` letters of `s` if the first `i` letters of `s` are ...
dolphin
Please explain the following problem in detail and provide code in Lisp: 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 the string. **Ex...
dolphin
Please focus on the algorithm of this problem and provide code in F#: Given the roots of two binary search trees, `root1` and `root2`, return `true` if and only if there is a node in the first tree and a node in the second tree whose values sum up to a given integer `target`. **Example 1:** **Input:** root1 = \[2,1,4...
dolphin
Please explain the reasoning behind the following solution and provide code in Julia: Given a `wordlist`, we want to implement a spellchecker that converts a query word into a correct word. For a given `query` word, the spell checker handles two categories of spelling mistakes: * Capitalization: If the query matche...
dolphin
convert this code from Objective-C to Fortran: ```objective-c - (NSArray<NSArray<NSNumber *> *> *)construct2DArray:(NSArray<NSNumber *> *)original withM:(int)m withN:(int)n { if (m * n != original.count) { return @[]; } NSMutableArray<NSMutableArray<NSNumber *> *> *res = [NSMutableArray arrayWithCap...
dolphin
convert this code to C#: ```mojo func can_jump(nums: List[int]) -> bool { var max_reach: int = 0; for i, num in enumerate(nums) { if i > max_reach { return false; } max_reach = max(max_reach, i + num); } return true; } ```
dolphin
Please explain the following problem in detail and provide code in Haskell: You are given an array `target` of n integers. From a starting array `arr` consisting of `n` 1's, you may perform the following procedure : * let `x` be the sum of all elements currently in your array. * choose index `i`, such that `0 <= i...
dolphin
translate this code from ANSI C to Scala: ```c #include <stdio.h> #include <stdbool.h> #define MAX_N 100005 #define MAX_VAL 105 int nums[MAX_N]; int freq[MAX_VAL]; bool divisors[MAX_VAL]; int main() { int n; scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%d", &nums[i]); } int cou...
dolphin
Please focus on the algorithm of this problem and provide code in Ruby: This is an **interactive problem**. There is a robot in a hidden grid, and you are trying to get it from its starting cell to the target cell in this grid. The grid is of size `m x n`, and each cell in the grid is either empty or blocked. It is **...
dolphin
Please explain the reasoning behind the following solution and provide code in Visual Basic .NET: You are given a **0-indexed** array `nums` that consists of `n` **distinct** positive integers. Apply `m` operations to this array, where in the `ith` operation you replace the number `operations[i][0]` with `operations[i]...
dolphin
Please write the following solution using Julia: Given an integer array `nums`, move all the even integers at the beginning of the array followed by all the odd integers. Return _**any array** that satisfies this condition_. **Example 1:** **Input:** nums = \[3,1,2,4\] **Output:** \[2,4,3,1\] **Explanation:** The ou...
dolphin
convert this code to Haskell: ```scheme (define (flowers-in-bloom flowers people) (define (increment lst idx) (set! (list-ref lst idx) (+ (list-ref lst idx) 1))) (set! flowers (sort flowers (lambda (a b) (< (cdr a) (cdr b))))) (set! people (sort people <)) (define result (make-list (length people) 0)) ...
dolphin
Please explain the reasoning behind the following solution and provide code in ANSI C: You are in a city that consists of `n` intersections numbered from `0` to `n - 1` with **bi-directional** roads between some intersections. The inputs are generated such that you can reach any intersection from any other intersection...
dolphin
port this code to Scala: ```r Twitter <- R6Class("Twitter", public = list( tweets = list(), following = list(), timeStamp = 0L, Tweet = R6Class("Tweet", public = list( ...
dolphin
Please explain the reasoning behind the following solution and provide code in Objective-C: You are given a binary array `nums` and an integer `k`. A **k-bit flip** is choosing a **subarray** of length `k` from `nums` and simultaneously changing every `0` in the subarray to `1`, and every `1` in the subarray to `0`. ...
dolphin
Please focus on the functionality of this problem and provide code in Objective-C: There are `n` people, each person has a unique _id_ between `0` and `n-1`. Given the arrays `watchedVideos` and `friends`, where `watchedVideos[i]` and `friends[i]` contain the list of watched videos and the list of friends respectively ...
dolphin
port this code from PHP to R: ```php function minCostToMoveChips($position) { $even_count = 0; $odd_count = 0; foreach ($position as $p) { if ($p % 2 == 0) { $even_count++; } else { $odd_count++; } } return min($even_count, $odd_count); } ```
dolphin
Please explain the reasoning behind the following solution and provide code in Elixir: There are `n` pieces arranged in a line, and each piece is colored either by `'A'` or by `'B'`. You are given a string `colors` of length `n` where `colors[i]` is the color of the `ith` piece. Alice and Bob are playing a game where ...
dolphin
convert this code from F# to Groovy: ```fsharp let bestCoordinate (towers: int[][]) (radius: int) = let mutable maxQuality = 0 let mutable bestX, bestY = 0, 0 for x in 0..50 do for y in 0..50 do let mutable sumQuality = 0 for tower in towers do let dist = sqr...
dolphin
Please explain the reasoning behind the following solution and provide code in Julia: 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 ...
dolphin
translate this code from Erlang to Haskell: ```erlang find_most_frequent_element(Arr) -> N = length(Arr), Quarter = N div 4, lists:foreach(fun(I) -> if lists:nth(I, Arr) =:= lists:nth(I+Quarter, Arr) -> Res = lists:nth(I, Arr), exit({found, Res}) end end, lists:seq(1, N-Quart...
dolphin
port this code from Lua to Haskell: ```lua function get_row(rowIndex) local row = {} for i=1,rowIndex+1 do row[i] = 1 end for i=2,rowIndex+1 do for j=i-1,1,-1 do row[j] = row[j] + row[j-1] end end return row end ```
dolphin
Please write the following solution using java: There exists an undirected and unrooted tree with `n` nodes indexed from `0` to `n - 1`. You are given an integer `n` and 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 a...
dolphin
Please write the following solution using Lua: There is a directed graph of `n` nodes with each node labeled from `0` to `n - 1`. The graph is represented by a **0-indexed** 2D integer array `graph` where `graph[i]` is an integer array of nodes adjacent to node `i`, meaning there is an edge from node `i` to each node i...
dolphin
Please focus on the functionality of this problem and provide code in Ruby: You are given a string `s` that contains digits `0-9`, addition symbols `'+'`, and multiplication symbols `'*'` **only**, representing a **valid** math expression of **single digit numbers** (e.g., `3+5*2`). This expression was given to `n` ele...
dolphin
port this code to Scala: ```c #include <stdio.h> int* solve(int* nums1, int* nums2, int nums1Size, int nums2Size, int** queries, int queriesSize, int* queriesColSize, int* returnSize){ int* res = (int*)malloc(queriesSize * sizeof(int)); int n = nums1Size; for (int i = 0; i < queriesSize; i++) { if ...
dolphin
Please focus on the efficiency of this problem and provide code in Fortran: Given a `matrix` and a `target`, return the number of non-empty submatrices that sum to target. A submatrix `x1, y1, x2, y2` is the set of all cells `matrix[x][y]` with `x1 <= x <= x2` and `y1 <= y <= y2`. Two submatrices `(x1, y1, x2, y2)` a...
dolphin
Please explain the following problem in detail and provide code in Ruby: Given two numbers, `hour` and `minutes`, return _the smaller angle (in degrees) formed between the_ `hour` _and the_ `minute` _hand_. Answers within `10-5` of the actual value will be accepted as correct. **Example 1:** **Input:** hour = 12, mi...
dolphin
Please explain the following problem in detail and provide code in Go: The **bitwise AND** of an array `nums` is the bitwise AND of all integers in `nums`. * For example, for `nums = [1, 5, 3]`, the bitwise AND is equal to `1 & 5 & 3 = 1`. * Also, for `nums = [7]`, the bitwise AND is `7`. You are given an array o...
dolphin
Please explain the reasoning behind the following solution and provide code in python: Given a positive integer `num`, split it into two non-negative integers `num1` and `num2` such that: * The concatenation of `num1` and `num2` is a permutation of `num`. * In other words, the sum of the number of occurrences ...
dolphin
Please write the following solution using Lisp: Given a positive integer `n`, return the number of the integers in the range `[0, n]` whose binary representations **do not** contain consecutive ones. **Example 1:** **Input:** n = 5 **Output:** 5 **Explanation:** Here are the non-negative integers <= 5 with their corr...
dolphin
Please explain the reasoning behind the following solution and provide code in COBOL: Given the `root` of a binary tree, _check whether it is a mirror of itself_ (i.e., symmetric around its center). **Example 1:** **Input:** root = \[1,2,2,3,4,4,3\] **Output:** true **Example 2:** **Input:** root = \[1,2,2,null,3,n...
dolphin
Please write the following solution using TypeScript: You are given a **0-indexed** integer array `nums`. For each index `i` (`1 <= i <= nums.length - 2`) the **beauty** of `nums[i]` equals: * `2`, if `nums[j] < nums[i] < nums[k]`, for **all** `0 <= j < i` and for **all** `i < k <= nums.length - 1`. * `1`, if `num...
dolphin
port this code from Julia to Scheme: ```julia function canFormArray(arr::Array{Int}, pieces::Array{Array{Int}})::Bool map = Dict(piece[1] => piece for piece in pieces) i = 1 while i <= length(arr) if !(arr[i] in keys(map)) return false end piece = map[arr[i]] for...
dolphin
port this code to C#: ```lisp (defun three-sum-closest (nums target) (setq nums (sort nums #'<)) (let ((closest (+ (nth 0 nums) (nth 1 nums) (nth 2 nums)))) (dotimes (i (- (length nums) 2)) (let ((left (+ i 1)) (right (- (length nums) 1))) (loop while (< left right) do (let (...
dolphin
port this code from Scala to Swift: ```scala def findComplement(n: Int): Int = { val binary = n.toBinaryString val complement = binary.map(c => if(c == '0') '1' else '0') Integer.parseInt(complement, 2) } ```
dolphin
Please explain the reasoning behind the following solution and provide code in Perl: The **alternating sum** of a **0-indexed** array is defined as the **sum** of the elements at **even** indices **minus** the **sum** of the elements at **odd** indices. * For example, the alternating sum of `[4,2,5,3]` is `(4 + 5) -...
dolphin
Please focus on the algorithm of this problem and provide code in F#: 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 text, on...
dolphin
port this code to javascript: ```rust fn is_majority_element(nums: &[i32], target: i32) -> bool { let mut count = 0; for &num in nums { if num == target { count += 1; } if count > nums.len() / 2 { return true; } } false } ```
dolphin
Please explain the following problem in detail and provide code in Haskell: There are `n` hens and `m` grains on a line. You are given the initial positions of the hens and the grains in two integer arrays `hens` and `grains` of size `n` and `m` respectively. Any hen can eat a grain if they are on the same position. T...
dolphin
Please explain the reasoning behind the following solution and provide code in java: There are `n` dominoes in a line, and we place each domino vertically upright. In the beginning, we simultaneously push some of the dominoes either to the left or to the right. After each second, each domino that is falling to the lef...
dolphin
convert this code from Haskell to Go: ```haskell mctFromLeafValues :: [Int] -> Int mctFromLeafValues arr = dp !! 0 !! (n - 1) where n = length arr dp = [[0 | _ <- [0..n-1]] | _ <- [0..n-1]] maxs = [[0 | _ <- [0..n-1]] | _ <- [0..n-1]] fillMaxs :: Int -> Int -> [[Int]] -> [[Int]] fillMaxs i j maxs...
dolphin
Please write the following solution using Elixir: There are `n` piles of `stones` arranged in a row. The `ith` pile has `stones[i]` stones. A move consists of merging exactly `k` **consecutive** piles into one pile, and the cost of this move is equal to the total number of stones in these `k` piles. Return _the minim...
dolphin
port this code to Groovy: ```scala import scala.collection.mutable.PriorityQueue def reconstructMatrix(upper: Int, lower: Int, colsum: Array[Int]): Array[Array[Int]] = { val res = Array.fill(2, colsum.length)(0) val pq1 = PriorityQueue.empty[(Int, Int)](Ordering.by[(Int, Int), Int](_._1).reverse) val pq2 = Prior...
dolphin
Please explain the reasoning behind the following solution and provide code in Haskell: You are given an array of `n` strings `strs`, all of the same length. We may choose any deletion indices, and we delete all the characters in those indices for each string. For example, if we have `strs = [ "abcdef ", "uvwxyz "]` ...
dolphin
Please explain the reasoning behind the following solution and provide code in Groovy: Given the **API** `rand7()` that generates a uniform random integer in the range `[1, 7]`, write a function `rand10()` that generates a uniform random integer in the range `[1, 10]`. You can only call the API `rand7()`, and you shoul...
dolphin
Please explain the following problem in detail and provide code in TypeScript: 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
translate this code to python: ```rust fn unguarded_cells(m: i32, n: i32, guards: Vec<Vec<i32>>, walls: Vec<Vec<i32>>) -> i32 { let mut occupied: HashSet<(i32, i32)> = HashSet::new(); for g in guards.iter() { for i in 0..m { if i != g[0] && !(walls.contains(&vec![i, g[1]])) { ...
dolphin
Please explain the reasoning behind the following solution and provide code in Erlang: Given a 2D `grid` consists of `0s` (land) and `1s` (water). An _island_ is a maximal 4-directionally connected group of `0s` and a _closed island_ is an island **totally** (all left, top, right, bottom) surrounded by `1s.` Return th...
dolphin
convert this code to Ruby: ``` type Solution = class private buffer_index: Integer; buffer_len: Integer; buf4: array[0..3] of Char; public constructor Create; function Read(buf: array of Char; n: Integer): Integer; function Read4(buf4: array of Char): Integer; end; constructor Solution....
dolphin
Please focus on the algorithm of this problem and provide code in Objective-C: Given two integer arrays, `preorder` and `postorder` where `preorder` is the preorder traversal of a binary tree of **distinct** values and `postorder` is the postorder traversal of the same tree, reconstruct and return _the binary tree_. I...
dolphin
Please explain the reasoning behind the following solution and provide code in Lua: 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 is ...
dolphin
convert this code to C#: ```pascal function FindLeftMostOccurrence(s: string; part: string): integer; var index: integer; begin index := Pos(part, s); if index >= 1 then Delete(s, index, Length(part)); Result := index; end; function RemoveAllOccurrences(s: string; part: string): string; var index: intege...
dolphin