instruction_seed
stringlengths
29
40.5k
source
stringclasses
6 values
convert this code from Fortran to Kotlin: ```fortran function reverse_bits(n) result(res) implicit none integer(kind=4), intent(in) :: n integer(kind=4) :: res integer :: i res = 0 do i = 1, 32 res = iand(res, lshift(1, 31)) + iand(n, 1) n = shift_right(n, 1) end do end function reverse_bits ```
dolphin
translate this code to F#: ```rust fn make_fancy_string(s: String) -> String { let mut ans: Vec<char> = vec![s.chars().next().unwrap()]; let mut count = 1; for c in s.chars().skip(1) { if c == ans[ans.len() - 1] { count += 1; } else { count = 1; } if...
dolphin
Please focus on the algorithm of this problem and provide code in Perl: Given an unsorted array of integers `nums`, return _the length of the longest consecutive elements sequence._ You must write an algorithm that runs in `O(n)` time. **Example 1:** **Input:** nums = \[100,4,200,1,3,2\] **Output:** 4 **Explanation:...
dolphin
Please explain the reasoning behind the following solution and provide code in Elixir: Given an integer `n` (in base `10`) and a base `k`, return _the **sum** of the digits of_ `n` _**after** converting_ `n` _from base_ `10` _to base_ `k`. After converting, each digit should be interpreted as a base `10` number, and t...
dolphin
translate this code from Groovy to Object Pascal: ```groovy class ValidWordAbbr { def word_map = [:] ValidWordAbbr(def dictionary) { dictionary.each { word -> def abbr = getAbbreviation(word) if (!word_map.containsKey(abbr)) { word_map[abbr] = [word] ...
dolphin
Please explain the reasoning behind the following solution and provide code in c++: Given the `root` of a binary search tree and a node `p` in it, return _the in-order successor of that node in the BST_. If the given node has no in-order successor in the tree, return `null`. The successor of a node `p` is the node wit...
dolphin
Please focus on the algorithm of this problem and provide code in Mojo: Given a balanced parentheses string `s`, return _the **score** of the string_. The **score** of a balanced parentheses string is based on the following rule: * `"() "` has score `1`. * `AB` has score `A + B`, where `A` and `B` are balanced pa...
dolphin
port this code from Groovy to Fortran: ```groovy def full_chess_rounds(loginTime, logoutTime) { if (logoutTime < loginTime) { logoutTime += "24:00" } def loginRound = roundUpToNearestFifteenMinutes(loginTime) def logoutRound = roundDownToNearestFifteenMinutes(logoutTime) def numRou...
dolphin
Please focus on the algorithm of this problem and provide code in java: Given a binary tree `root` and an integer `target`, delete all the **leaf nodes** with value `target`. Note that once you delete a leaf node with value `target`**,** if its parent node becomes a leaf node and has the value `target`, it should also...
dolphin
Please explain the following problem in detail and provide code in Go: You are given a string `sentence` that consist of words separated by spaces. Each word consists of lowercase and uppercase letters only. We would like to convert the sentence to "Goat Latin " (a made-up language similar to Pig Latin.) The rules of ...
dolphin
Please explain the reasoning behind the following solution and provide code in R: You are given an array `pairs`, where `pairs[i] = [xi, yi]`, and: * There are no duplicates. * `xi < yi` Let `ways` be the number of rooted trees that satisfy the following conditions: * The tree consists of nodes whose values ap...
dolphin
translate this code from R to Erlang: ```R get_hint <- function(secret, guess) { bulls <- 0 cows <- 0 secret_count <- rep(0, 10) guess_count <- rep(0, 10) for (i in 1:nchar(secret)) { if (substr(secret, i, i) == substr(guess, i, i)) { bulls <- bulls + 1 } else { secret_count[as.integer(...
dolphin
convert this code from Ruby to TypeScript: ```ruby def is_shortest_and_unique_supersequence(nums, sequences) pos = {} nums.each_with_index { |val, idx| pos[val] = idx } sequences.each do |seq| return false if pos[seq[0]] > pos[seq[-1]] end return true end ```
dolphin
convert this code to Clojure: ```javascript function minKeypresses(s) { const keypresses = Array.from({length: 26}, (_, i) => (i % 9) + 1); let result = 0; for (const c of s) { result += keypresses[c.charCodeAt(0) - 'a'.charCodeAt(0)]; } return result; } ```
dolphin
Please write the following solution using Objective-C: For an integer array `nums`, an **inverse pair** is a pair of integers `[i, j]` where `0 <= i < j < nums.length` and `nums[i] > nums[j]`. Given two integers n and k, return the number of different arrays consist of numbers from `1` to `n` such that there are exact...
dolphin
Please explain the following problem in detail and provide code in Fortran: You have `n` boxes. You are given a binary string `boxes` of length `n`, where `boxes[i]` is `'0'` if the `ith` box is **empty**, and `'1'` if it contains **one** ball. In one operation, you can move **one** ball from a box to an adjacent box....
dolphin
convert this code from Ruby to Lisp: ```ruby def maximize_bob_points(num_arrows, alice_arrows) bob_arrows = Array.new(12, 0) alice_arrows.each_with_index do |alice_arrow, i| next if alice_arrow.zero? remaining_arrows = num_arrows - alice_arrow bob_arrows[i] = [rema...
dolphin
translate this code from Go to c++: ```go func isPowerOfTwo(n int) bool { if n <= 0 { return false } return (n & (n - 1)) == 0 } ```
dolphin
Please explain the following problem in detail and provide code in Mojo: You are given an integer array `cards` of length `4`. You have four cards, each containing a number in the range `[1, 9]`. You should arrange the numbers on these cards in a mathematical expression using the operators `['+', '-', '*', '/']` and th...
dolphin
Please explain the following problem in detail and provide code in Lisp: You are given an integer array `nums`. The adjacent integers in `nums` will perform the float division. * For example, for `nums = [2,3,4]`, we will evaluate the expression `"2/3/4 "`. However, you can add any number of parenthesis at any posi...
dolphin
Please write the following solution using Mojo: The string `"PAYPALISHIRING "` is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line: `"PAHNAPLSIIGYIR "` Write t...
dolphin
convert this code from Objective-C to F#: ```Objective-C #import <Foundation/Foundation.h> @interface MyStack : NSObject - (void)push:(int)x; - (int)pop; - (int)top; - (BOOL)empty; @end @implementation MyStack { NSMutableArray *_q1; NSMutableArray *_q2; } - (instancetype)init { self = [super init]; ...
dolphin
Please write the following solution using Perl: There are `n` couples sitting in `2n` seats arranged in a row and want to hold hands. The people and seats are represented by an integer array `row` where `row[i]` is the ID of the person sitting in the `ith` seat. The couples are numbered in order, the first couple bein...
dolphin
Please explain the reasoning behind the following solution and provide code in javascript: You are given a **0-indexed** `m x n` **binary** matrix `grid`. In one operation, you can choose any `i` and `j` that meet the following conditions: * `0 <= i < m` * `0 <= j < n` * `grid[i][j] == 1` and change the values...
dolphin
convert this code to python: ```R hasValidPath <- function(grid) { m <- nrow(grid) n <- ncol(grid) directions <- list(c(0,-1), c(-1,0), c(0,1), c(1,0)) allowed <- list( c(), c(1,3), c(0,2), c(3,2), c(0,1), c(1,2), c(0,3) ) visited <- matrix(FALSE, m, n) dfs <- function...
dolphin
translate this code from C# to Scala: ```csharp public int CountVowelStrings(int n) { int[] dp = new int[5] {1, 1, 1, 1, 1}; for (int i = 1; i < n; i++) { for (int j = 3; j >= 0; j--) { dp[j] += dp[j + 1]; } } int sum = 0; for (int i = 0; i < 5; i++) { sum += dp...
dolphin
Please explain the reasoning behind the following solution and provide code in Clojure: You have `n` coins and you want to build a staircase with these coins. The staircase consists of `k` rows where the `ith` row has exactly `i` coins. The last row of the staircase **may be** incomplete. Given the integer `n`, return...
dolphin
translate this code from Swift to Ruby: ```swift import Foundation import SortedCollections func stockSpanner() -> () -> Int { var prices = SortedArray<Int>() var spans = [Int]() return { let price = Int(readLine()!)! var span = 1 while !prices.isEmpty && prices.last! ...
dolphin
Please write the following solution using Swift: Given an array of **unique** integers `preorder`, return `true` _if it is the correct preorder traversal sequence of a binary search tree_. **Example 1:** **Input:** preorder = \[5,2,1,3,6\] **Output:** true **Example 2:** **Input:** preorder = \[5,2,6,1,3\] **Output...
dolphin
Please explain the reasoning behind the following solution and provide code in java: You are given an integer `n` denoting the number of cities in a country. The cities are numbered from `0` to `n - 1`. You are also given a 2D integer array `roads` where `roads[i] = [ai, bi]` denotes that there exists a **bidirectiona...
dolphin
Please write the following solution using Perl: 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 node with the left subtree as `order(n - 2...
dolphin
convert this code to PHP: ```objective-c -(int)maxCoins:(NSArray *)nums { NSMutableArray *newNums = [NSMutableArray arrayWithObject:@1]; [newNums addObjectsFromArray:nums]; [newNums addObject:@1]; NSInteger n = newNums.count; NSMutableArray *dp = [NSMutableArray arrayWithCapacity:n]; for (int i=...
dolphin
Please explain the reasoning behind the following solution and provide code in Dart: You are given a **0-indexed** binary string `s` and two integers `minJump` and `maxJump`. In the beginning, you are standing at index `0`, which is equal to `'0'`. You can move from index `i` to index `j` if the following conditions ar...
dolphin
Please explain the reasoning behind the following solution and provide code in Dart: Given two sparse vectors, compute their dot product. Implement class `SparseVector`: * `SparseVector(nums)` Initializes the object with the vector `nums` * `dotProduct(vec)` Compute the dot product between the instance of _Sparse...
dolphin
Please write the following solution using Groovy: You are given the `root` of a binary tree where each node has a value `0` or `1`. Each root-to-leaf path represents a binary number starting with the most significant bit. * For example, if the path is `0 -> 1 -> 1 -> 0 -> 1`, then this could represent `01101` in bin...
dolphin
translate this code to PHP: ```kotlin fun xorSum(arr1: IntArray, arr2: IntArray): Int { var result = 0 for (i in arr1.indices) { for (j in arr2.indices) { result = result xor (arr1[i] and arr2[j]) } } return result } ```
dolphin
Please focus on the efficiency of this problem and provide code in Perl: You are given a positive integer `n`. Continuously replace `n` with the sum of its **prime factors**. * Note that if a prime factor divides `n` multiple times, it should be included in the sum as many times as it divides `n`. Return _the smal...
dolphin
Please explain the reasoning behind the following solution and provide code in F#: You are given two string arrays, `queries` and `dictionary`. All words in each array comprise of lowercase English letters and have the same length. In one **edit** you can take a word from `queries`, and change any letter in it to any ...
dolphin
Please focus on the algorithm of this problem and provide code in javascript: You are given an array of `events` where `events[i] = [startDayi, endDayi]`. Every event `i` starts at `startDayi` and ends at `endDayi`. You can attend an event `i` at any day `d` where `startTimei <= d <= endTimei`. You can only attend one...
dolphin
Please write the following solution using Ruby: Given an integer array of even length `arr`, return `true` _if it is possible to reorder_ `arr` _such that_ `arr[2 * i + 1] = 2 * arr[2 * i]` _for every_ `0 <= i < len(arr) / 2`_, or_ `false` _otherwise_. **Example 1:** **Input:** arr = \[3,1,3,6\] **Output:** false **...
dolphin
Please focus on the functionality of this problem and provide code in Visual Basic .NET: A **sentence** is a list of words that are separated by a single space with no leading or trailing spaces. Each word consists of lowercase and uppercase English letters. A sentence can be **shuffled** by appending the **1-indexed ...
dolphin
port this code to Lisp: ```php function min_xor_sum($nums1, $nums2) { $n = count($nums1); sort($nums1); rsort($nums2); $sum = 0; for ($i = 0; $i < $n; $i++) { $sum += ($nums1[$i] ^ $nums2[$i]); } return $sum; } ``` The function `min_xor_sum` takes in two arrays, `nums1` and `nums2`,...
dolphin
translate this code to C#: ```lua function distribute_candies(candies, num_people) local result = {} for i=1,num_people do result[i] = 0 end local i = 1 local count = 1 while candies > 0 do result[i] = result[i] + math.min(candies, count) candies = candies - count ...
dolphin
Please write the following solution using F#: You are given an inclusive range `[lower, upper]` and a **sorted unique** integer array `nums`, where all elements are in the inclusive range. A number `x` is considered **missing** if `x` is in the range `[lower, upper]` and `x` is not in `nums`. Return _the **smallest s...
dolphin
Please explain the reasoning behind the following solution and provide code in javascript: You are given an `m x n` grid `rooms` initialized with these three possible values. * `-1` A wall or an obstacle. * `0` A gate. * `INF` Infinity means an empty room. We use the value `231 - 1 = 2147483647` to represent `IN...
dolphin
Please write the following solution using python: Given two strings `str1` and `str2` of the same length, determine whether you can transform `str1` into `str2` by doing **zero or more** _conversions_. In one conversion you can convert **all** occurrences of one character in `str1` to **any** other lowercase English c...
dolphin
Please focus on the efficiency of this problem and provide code in java: Given the `root` of an N-ary tree of unique values, and two nodes of the tree `p` and `q`. You should move the subtree of the node `p` to become a direct child of node `q`. If `p` is already a direct child of `q`, do not change anything. Node `p`...
dolphin
Please write the following solution using Objective-C: Given the `root` of a binary tree, _determine if it is a valid binary search tree (BST)_. A **valid BST** is defined as follows: * The left subtree of a node contains only nodes with keys **less than** the node's key. * The right subtree of a node contains on...
dolphin
Please write the following solution using Haskell: There is a group of `n` members, and a list of various crimes they could commit. The `ith` crime generates a `profit[i]` and requires `group[i]` members to participate in it. If a member participates in one crime, that member can't participate in another crime. Let's ...
dolphin
Please explain the following problem in detail and provide code in Ruby: You are given an integer array `cards` of length `4`. You have four cards, each containing a number in the range `[1, 9]`. You should arrange the numbers on these cards in a mathematical expression using the operators `['+', '-', '*', '/']` and th...
dolphin
Please write the following solution using Erlang: Under the grammar given below, strings can represent a set of lowercase words. Let `R(expr)` denote the set of words the expression represents. The grammar can best be understood through simple examples: * Single letters represent a singleton set containing that wor...
dolphin
Please explain the following problem in detail and provide code in c++: A decimal number is called **deci-binary** if each of its digits is either `0` or `1` without any leading zeros. For example, `101` and `1100` are **deci-binary**, while `112` and `3001` are not. Given a string `n` that represents a positive decim...
dolphin
Please explain the reasoning behind the following solution and provide code in Groovy: Given a string `s` and an integer `k`, return `true` _if you can use all the characters in_ `s` _to construct_ `k` _palindrome strings or_ `false` _otherwise_. **Example 1:** **Input:** s = "annabelle ", k = 2 **Output:** true **E...
dolphin
Please explain the reasoning behind the following solution and provide code in java: This question is about implementing a basic elimination algorithm for Candy Crush. Given an `m x n` integer array `board` representing the grid of candy where `board[i][j]` represents the type of candy. A value of `board[i][j] == 0` r...
dolphin
translate this code to C#: ```kotlin fun reverseString(s: String): String { var i = 0 var j = s.length - 1 val arr = s.toCharArray() while (i < j) { if (!arr[i].isLetter()) { i++ } else if (!arr[j].isLetter()) { j-- } else { val temp = arr[i] ...
dolphin
Please focus on the efficiency of this problem and provide code in Julia: On a 2D plane, we place `n` stones at some integer coordinate points. Each coordinate point may have at most one stone. A stone can be removed if it shares either **the same row or the same column** as another stone that has not been removed. G...
dolphin
Please focus on the algorithm of this problem and provide code in python: In an alien language, surprisingly, they also use English lowercase letters, but possibly in a different `order`. The `order` of the alphabet is some permutation of lowercase letters. Given a sequence of `words` written in the alien language, an...
dolphin
convert this code from Mojo to Objective-C: ``` sub findPermutation(s) { my $n = length($s) + 1; my @perm = (0) x $n; my $left = 1; my $i = 0; while ($i < $n - 1) { if (substr($s, $i, 1) eq 'I') { $perm[$i] = $left; $left += 1; while ($i + 1 < $n - 1 && su...
dolphin
Please focus on the algorithm of this problem and provide code in Fortran: The Leetcode file system keeps a log each time some user performs a _change folder_ operation. The operations are described below: * `"../ "` : Move to the parent folder of the current folder. (If you are already in the main folder, **remain...
dolphin
translate this code from PHP to Haskell: ```php function findMin($nums) { $low = 0; $high = count($nums) - 1; while ($low < $high) { $mid = $low + intval(($high - $low) / 2); if ($nums[$mid] > $nums[$high]) { $low = $mid + 1; } elseif ($nums[$mid] < $nums[$high]) { ...
dolphin
Please write the following solution using Haskell: A string is a _valid parentheses string_ (denoted VPS) if and only if it consists of `"( "` and `") "` characters only, and: * It is the empty string, or * It can be written as `AB` (`A` concatenated with `B`), where `A` and `B` are VPS's, or * It can be written...
dolphin
Please explain the reasoning behind the following solution and provide code in Kotlin: You are given a string `sentence` that consist of words separated by spaces. Each word consists of lowercase and uppercase letters only. We would like to convert the sentence to "Goat Latin " (a made-up language similar to Pig Latin...
dolphin
Please write the following solution using python: Given a `file` and assume that you can only read the file using a given method `read4`, implement a method `read` to read `n` characters. Your method `read` may be **called multiple times**. **Method read4:** The API `read4` reads **four consecutive characters** from ...
dolphin
Please focus on the efficiency of this problem and provide code in Rust: Given an integer array `nums` of **positive** integers, return _the average value of all even integers that are divisible by_ `3`_._ Note that the **average** of `n` elements is the **sum** of the `n` elements divided by `n` and **rounded down** ...
dolphin
Please explain the following problem in detail and provide code in R: 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
convert this code from python to Swift: ```python def maximum_wealth(accounts): return max(sum(customer) for customer in accounts) ```
dolphin
Please explain the reasoning behind the following solution and provide code in C#: Alice and Bob take turns playing a game, with **Alice starting first**. There are `n` stones arranged in a row. On each player's turn, while the number of stones is **more than one**, they will do the following: 1. Choose an integer `...
dolphin
port this code from Kotlin to Swift: ```kotlin fun smallestMissingValueSubtree(parents: IntArray, nums: IntArray): IntArray { val n = parents.size val children = Array(n) { mutableSetOf<Int>() } for (i in 1 until n) { children[parents[i]].add(nums[i]) } val ans = IntArray(n) dfs(0, pare...
dolphin
Please explain the reasoning behind the following solution and provide code in Clojure: Given the `root` of a binary tree, return _the number of nodes where the value of the node is equal to the **average** of the values in its **subtree**_. **Note:** * The **average** of `n` elements is the **sum** of the `n` elem...
dolphin
Please explain the following problem in detail and provide code in java: You are given a license key represented as a string `s` that consists of only alphanumeric characters and dashes. The string is separated into `n + 1` groups by `n` dashes. You are also given an integer `k`. We want to reformat the string `s` suc...
dolphin
translate this code to Ruby: ```perl use strict; use warnings; use List::Util qw(sum); sub largest_multiple_of_three { my @digits = @_; my @mod; my $sum_digits = sum(@digits); my $result = ""; return "" if scalar(@digits) == 0; @digits = sort { $b <=> $a } @digits; if ($sum_digits % 3 ==...
dolphin
Please write the following solution using Swift: You are given an `m x n` matrix `mat` that has its rows sorted in non-decreasing order and an integer `k`. You are allowed to choose **exactly one element** from each row to form an array. Return _the_ `kth` _smallest array sum among all possible arrays_. **Example 1:...
dolphin
Please explain the following problem in detail and provide code in Lisp: Let's play the minesweeper game ([Wikipedia](https://en.wikipedia.org/wiki/Minesweeper_(video_game)), [online game](http://minesweeperonline.com))! You are given an `m x n` char matrix `board` representing the game board where: * `'M'` represe...
dolphin
port this code to java: ```erlang maximum_score(Nums, Multipliers) -> N = length(Nums), M = length(Multipliers), DP = lists:duplicate(M + 1, lists:duplicate(M + 1, 0)), MaxScore = -1 * math:inf(), lists:foreach( fun(I) -> lists:foreach( fun(J) -> ...
dolphin
convert this code to Lisp: ```scheme (define (numPoints darts r) (define (distance p1 p2) (sqrt (+ (expt (- (car p1) (car p2)) 2) (expt (- (cdr p1) (cdr p2)) 2)))) (define (count-center i j) (let ((center-x (/ (+ (car (list-ref darts i)) (car (list-ref darts j))) 2...
dolphin
Please explain the following problem in detail and provide code in C#: You and a gang of thieves are planning on robbing a bank. You are given a **0-indexed** integer array `security`, where `security[i]` is the number of guards on duty on the `ith` day. The days are numbered starting from `0`. You are also given an in...
dolphin
Please focus on the functionality of this problem and provide code in Rust: 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 **a...
dolphin
Please write the following solution using Dart: You are painting a fence of `n` posts with `k` different colors. You must paint the posts following these rules: * Every post must be painted **exactly one** color. * There **cannot** be three or more **consecutive** posts with the same color. Given the two integers...
dolphin
convert this code from C# to Erlang: ```csharp public int MaxScore(int[][] grid) { int m = grid.Length, n = grid[0].Length; for (int i = 1; i < n; i++) { grid[0][i] = Math.Min(grid[0][i], grid[0][i - 1]); } for (int i = 1; i < m; i++) { grid[i][0] = Math.Min(grid[i][0], grid[i ...
dolphin
port this code from Visual Basic .NET to C#: ```vb.net Public Function MinRepeatsToSubstring(ByVal a As String, ByVal b As String) As Integer Dim times As Integer = Math.Ceiling((b.Length + a.Length - 1) / a.Length) For i As Integer = 0 To 1 Dim repeated_a As String = "" For j As Integer = ...
dolphin
Please focus on the efficiency of this problem and provide code in javascript: Given a collection of numbers, `nums`, that might contain duplicates, return _all possible unique permutations **in any order**._ **Example 1:** **Input:** nums = \[1,1,2\] **Output:** \[\[1,1,2\], \[1,2,1\], \[2,1,1\]\] **Example 2:** ...
dolphin
Please focus on the algorithm of this problem and provide code in Erlang: You are given a string `allowed` consisting of **distinct** characters and an array of strings `words`. A string is **consistent** if all characters in the string appear in the string `allowed`. Return _the number of **consistent** strings in th...
dolphin
Please explain the reasoning behind the following solution and provide code in Haskell: Given a directed acyclic graph (**DAG**) of `n` nodes labeled from `0` to `n - 1`, find all possible paths from node `0` to node `n - 1` and return them in **any order**. The graph is given as follows: `graph[i]` is a list of all n...
dolphin
translate this code to Objective-C: ```python from math import gcd def findGCD(nums): return gcd(min(nums), max(nums)) ```
dolphin
Please explain the reasoning behind the following solution and provide code in PHP: Given a `pattern` and a string `s`, find if `s` follows the same pattern. Here **follow** means a full match, such that there is a bijection between a letter in `pattern` and a **non-empty** word in `s`. **Example 1:** **Input:** pat...
dolphin
Please write the following solution using python: You are given an integer array `nums` (**0-indexed**). In one operation, you can choose an element of the array and increment it by `1`. * For example, if `nums = [1,2,3]`, you can choose to increment `nums[1]` to make `nums = [1,**3**,3]`. Return _the **minimum** n...
dolphin
Please explain the reasoning behind the following solution and provide code in Clojure: Given an `m x n` matrix `matrix` and an integer `k`, return _the max sum of a rectangle in the matrix such that its sum is no larger than_ `k`. It is **guaranteed** that there will be a rectangle with a sum no larger than `k`. **E...
dolphin
port this code from Erlang to TypeScript: ```erlang sumEvenGrandparent(undefined) -> 0; sumEvenGrandparent({_, undefined, undefined}) -> 0; sumEvenGrandparent({Val, {_, {_, Gg}, _}, {_, _, _}}) when Gg rem 2 == 0 -> Val + sumEvenGrandparent(_, {_, Gg}, _); sumEvenGrandparent({_, Left, Right}) -> sumEven...
dolphin
Please explain the following problem in detail and provide code in PHP: 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** i...
dolphin
Please explain the following problem in detail and provide code in c++: You are given a nested list of integers `nestedList`. Each element is either an integer or a list whose elements may also be integers or other lists. The **depth** of an integer is the number of lists that it is inside of. For example, the nested ...
dolphin
translate this code to Scheme: ```clojure (defn num-subsequences [source target] (let [m (count source) n (count target) dp (vec (repeat (inc m) (vec (repeat (inc n) 0))))] (dotimes [j (inc n)] (aset (aget dp 0) j (if (< j 1) 0 Integer/MAX_VALUE))) (dotimes [i (inc m)] (dotimes [...
dolphin
Please focus on the efficiency of this problem and provide code in Object Pascal: An **alphabetical continuous string** is a string consisting of consecutive letters in the alphabet. In other words, it is any substring of the string `"abcdefghijklmnopqrstuvwxyz "`. * For example, `"abc "` is an alphabetical continuo...
dolphin
Please focus on the efficiency of this problem and provide code in Haskell: Given the `root` of a binary tree, return `true` _if you can partition the tree into two trees with equal sums of values after removing exactly one edge on the original tree_. **Example 1:** **Input:** root = \[5,10,10,null,null,2,3\] **Outpu...
dolphin
port this code to R: ```rust fn dfs(matrix: &Vec<Vec<i32>>, memo: &mut Vec<Vec<i32>>, i: usize, j: usize) -> i32 { if memo[i][j] != 0 { return memo[i][j]; } let mut max_len = 0; let dx = [0, 0, 1, -1]; let dy = [1, -1, 0, 0]; for k in 0..4 { let ni = (i as i32 + dx[k]) as usize;...
dolphin
Please explain the following problem in detail and provide code in F#: In some array `arr`, the values were in arithmetic progression: the values `arr[i + 1] - arr[i]` are all equal for every `0 <= i < arr.length - 1`. A value from `arr` was removed that **was not the first or last value in the array**. Given `arr`, ...
dolphin
convert this code from javascript to Perl: ```javascript function minOperations(nums, start, goal) { const seen = new Set([start]); const queue = [start]; let level = 0; while (queue.length > 0) { const size = queue.length; for (let i = 0; i < size; i++) { const x = queue.sh...
dolphin
Please focus on the algorithm of this problem and provide code in Object Pascal: Given the `root` of a binary tree, return _the same tree where every subtree (of the given tree) not containing a_ `1` _has been removed_. A subtree of a node `node` is `node` plus every node that is a descendant of `node`. **Example 1:*...
dolphin
convert this code from Visual Basic .NET to Swift: ```vb.net Function minAbsSum(nums As Integer(), goal As Integer) As Integer Dim n As Integer = nums.Length Dim dp(2000000) As Boolean dp(0) = True Dim currSum As Integer = 0 For i As Integer = 0 To n-1 If nums(i) < 0 Then Fo...
dolphin
Please explain the reasoning behind the following solution and provide code in F#: **Run-length encoding** is a compression algorithm that allows for an integer array `nums` with many segments of **consecutive repeated** numbers to be represented by a (generally smaller) 2D array `encoded`. Each `encoded[i] = [vali, fr...
dolphin
Please focus on the algorithm of this problem and provide code in c++: You are given a string `allowed` consisting of **distinct** characters and an array of strings `words`. A string is **consistent** if all characters in the string appear in the string `allowed`. Return _the number of **consistent** strings in the a...
dolphin