instruction_seed
stringlengths
29
40.5k
source
stringclasses
6 values
Please explain the reasoning behind the following solution and provide code in Rust: Write an API that generates fancy sequences using the `append`, `addAll`, and `multAll` operations. Implement the `Fancy` class: * `Fancy()` Initializes the object with an empty sequence. * `void append(val)` Appends an integer `...
dolphin
Please focus on the efficiency of this problem and provide code in ANSI C: Given an array of integers `nums`, half of the integers in `nums` are **odd**, and the other half are **even**. Sort the array so that whenever `nums[i]` is odd, `i` is **odd**, and whenever `nums[i]` is even, `i` is **even**. Return _any answ...
dolphin
translate this code from Haskell to Erlang: ```haskell palindromeSubsequence :: String -> Int palindromeSubsequence s = let n = length s modVal = 10^9 + 7 dp = replicate 10 (replicate n 0) dp' = foldl (\dp'' len -> foldl (\dp''' d -> foldl (\dp'''' i -> ...
dolphin
Please focus on the functionality of this problem and provide code in Lisp: Let's say a positive integer is a **super-palindrome** if it is a palindrome, and it is also the square of a palindrome. Given two positive integers `left` and `right` represented as strings, return _the number of **super-palindromes** integer...
dolphin
translate this code to python: ```kotlin fun combinationSum(nums: IntArray, target: Int): Int { val dp = IntArray(target + 1) dp[0] = 1 for (num in nums) { for (i in num..target) { dp[i] += dp[i - num] } } return dp[target] } ```
dolphin
translate this code to C#: ```python from typing import List def allPathsSourceTarget(graph: List[List[int]]) -> List[List[int]]: def DFS(currentNode, path): path.append(currentNode) if currentNode == len(graph) - 1: result.append(path[:]) else: for neighbor in graph...
dolphin
Please explain the following problem in detail and provide code in Scheme: You are given a binary array `nums` (**0-indexed**). We define `xi` as the number whose binary representation is the subarray `nums[0..i]` (from most-significant-bit to least-significant-bit). * For example, if `nums = [1,0,1]`, then `x0 = 1...
dolphin
Please write the following solution using C#: Given an array of positive integers `nums`, remove the **smallest** subarray (possibly **empty**) such that the **sum** of the remaining elements is divisible by `p`. It is **not** allowed to remove the whole array. Return _the length of the smallest subarray that you need...
dolphin
Please explain the reasoning behind the following solution and provide code in java: Given an array of strings `words` and a width `maxWidth`, format the text such that each line has exactly `maxWidth` characters and is fully (left and right) justified. You should pack your words in a greedy approach; that is, pack as...
dolphin
convert this code from Scala to F#: ```scala object Solution { def hIndex(citations: Array[Int]): Int = { val n = citations.length var (left, right) = (0, n - 1) while (left <= right) { val mid = left + (right - left) / 2 if (citations(mid) == n - mid) { ...
dolphin
port this code from Dart to C#: ```dart int singleNumber(List<int> nums) { int ones = 0, twos = 0; for (int n in nums) { ones = (ones ^ n) & ~twos; twos = (twos ^ n) & ~ones; } return ones; } ```
dolphin
Please focus on the efficiency of this problem and provide code in R: You are given the `root` of a binary tree containing digits from `0` to `9` only. Each root-to-leaf path in the tree represents a number. * For example, the root-to-leaf path `1 -> 2 -> 3` represents the number `123`. Return _the total sum of al...
dolphin
Please explain the following problem in detail and provide code in SmallTalk: There are `n` bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb. On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the `ith` round, you to...
dolphin
convert this code to TypeScript: ```groovy def swap_kth_nodes(head, k) { def n = 0 def node = head while (node != null) { n++ node = node.next } if (k > n/2) { k = n - k + 1 } if (k > n || k < 1) { return head } def node1 = head def ...
dolphin
Please focus on the functionality of this problem and provide code in Haskell: You are given a **0-indexed** array of positive integers `nums`. Find the number of triplets `(i, j, k)` that meet the following conditions: * `0 <= i < j < k < nums.length` * `nums[i]`, `nums[j]`, and `nums[k]` are **pairwise distinct*...
dolphin
Please write the following solution using Lua: You are given a **binary string** `s`, and a **2D** integer array `queries` where `queries[i] = [firsti, secondi]`. For the `ith` query, find the **shortest substring** of `s` whose **decimal value**, `val`, yields `secondi` when **bitwise XORed** with `firsti`. In other ...
dolphin
Please write the following solution using Rust: Given an integer `n`, return _`true` if it is a power of four. Otherwise, return `false`_. An integer `n` is a power of four, if there exists an integer `x` such that `n == 4x`. **Example 1:** **Input:** n = 16 **Output:** true **Example 2:** **Input:** n = 5 **Outpu...
dolphin
translate this code to F#: ```erlang reverse_string(S) -> Left = 1, Right = length(S), reverse_string(S, Left, Right). reverse_string(S, Left, Right) when Left < Right -> {HLeft | TLeft} = S, {HRight | TRight} = lists:reverse(S), NewS = TLeft ++ [HRight] ++ TRight, reverse_string(NewS, Left...
dolphin
Please explain the following problem in detail and provide code in R: Given an array `nums` sorted in **non-decreasing** order, return _the maximum between the number of positive integers and the number of negative integers._ * In other words, if the number of positive integers in `nums` is `pos` and the number of n...
dolphin
port this code to ANSI C: ```csharp public static bool CanDestroyAll(int mass, int[] asteroids) { Array.Sort(asteroids); for (int i = 0; i < asteroids.Length; i++) { if (mass >= asteroids[i]) { mass += asteroids[i]; } else { return false; } } return true; ...
dolphin
port this code from Haskell to Erlang: ```haskell import qualified Data.Map as Map type AllOne = Map.Map String Int inc :: String -> AllOne -> AllOne inc key allOne = Map.insertWith (+) key 1 allOne dec :: String -> AllOne -> AllOne dec key allOne = if newCount == 0 then Map.delete key allOne else Map.insert key new...
dolphin
Please explain the reasoning behind the following solution and provide code in Groovy: You are given an integer array `nums`. In one move, you can pick an index `i` where `0 <= i < nums.length` and increment `nums[i]` by `1`. Return _the minimum number of moves to make every value in_ `nums` _**unique**_. The test ca...
dolphin
Please focus on the functionality of this problem and provide code in Lua: 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` represents ...
dolphin
translate this code from Julia to Perl: ```julia function max_units_on_truck(boxTypes::Array{Array{Int64,2},1}, truckSize::Int64)::Int64 boxTypes = sort(boxTypes, by=x->x[2], rev=true) total_units = 0 for box in boxTypes if truckSize >= box[1] total_units += box[1]*box[2] tru...
dolphin
convert this code from Rust to TypeScript: ```rust fn car_fleet(target: i32, position: Vec<i32>, speed: Vec<i32>) -> i32 { let n = position.len(); let mut cars: Vec<(i32, i32)> = position.into_iter().zip(speed.into_iter()).collect(); cars.sort_by(|a, b| b.0.cmp(&a.0)); let mut fleets = 0; let mut i ...
dolphin
Please explain the reasoning behind the following solution and provide code in Clojure: You are given an integer array `nums` of length `n`, and an integer array `queries` of length `m`. Return _an array_ `answer` _of length_ `m` _where_ `answer[i]` _is the **maximum** size of a **subsequence** that you can take from_...
dolphin
port this code to Fortran: ```dart bool canBeIncreasing(List<int> nums) { int count = 0; for (int i = 1; i < nums.length; i++) { if (nums[i - 1] >= nums[i]) { count++; if (count > 1) return false; if (i > 1 && nums[i - 2] >= nums[i] && i < nums.length - 1 && nums[...
dolphin
convert this code to PHP: ```clojure (defn max-subarray-sum-with-distinct-elements [nums k] (let [max-sum 0 freq-map (zipmap (distinct nums) (repeat 0)) window-sum 0] (doseq [i (range (count nums))] (let [num (nth nums i)] (update freq-map num inc) (+= window-sum num) ...
dolphin
Please explain the following problem in detail and provide code in Scheme: You are given a positive integer `num` consisting only of digits `6` and `9`. Return _the maximum number you can get by changing **at most** one digit (_`6` _becomes_ `9`_, and_ `9` _becomes_ `6`_)_. **Example 1:** **Input:** num = 9669 **Out...
dolphin
Please focus on the functionality of this problem and provide code in java: Given an array of positive integers `nums`, remove the **smallest** subarray (possibly **empty**) such that the **sum** of the remaining elements is divisible by `p`. It is **not** allowed to remove the whole array. Return _the length of the s...
dolphin
Please focus on the efficiency of this problem and provide code in Groovy: You are given an `m x n` binary matrix `grid`. An island is a group of `1`'s (representing land) connected **4-directionally** (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water. An island is considered ...
dolphin
Please explain the following problem in detail and provide code in Kotlin: You are given an array `nums` consisting of **positive** integers. Return _the number of **subarrays** of_ `nums` _that are in **strictly increasing** order._ A **subarray** is a **contiguous** part of an array. **Example 1:** **Input:** num...
dolphin
Please write the following solution using Kotlin: You are given a **0-indexed** string `word`, consisting of lowercase English letters. You need to select **one** index and **remove** the letter at that index from `word` so that the **frequency** of every letter present in `word` is equal. Return `true` _if it is poss...
dolphin
Please explain the following problem in detail and provide code in TypeScript: On a **0-indexed** `8 x 8` chessboard, there can be multiple black queens ad one white king. You are given a 2D integer array `queens` where `queens[i] = [xQueeni, yQueeni]` represents the position of the `ith` black queen on the chessboard...
dolphin
Please explain the following problem in detail and provide code in Lua: Given the `head` of a linked list, return _the list after sorting it in **ascending order**_. **Example 1:** **Input:** head = \[4,2,1,3\] **Output:** \[1,2,3,4\] **Example 2:** **Input:** head = \[-1,5,3,4,0\] **Output:** \[-1,0,3,4,5\] **Exa...
dolphin
Please focus on the efficiency of this problem and provide code in c++: Given a rectangle of size `n` x `m`, return _the minimum number of integer-sided squares that tile the rectangle_. **Example 1:** **Input:** n = 2, m = 3 **Output:** 3 **Explanation:** `3` squares are necessary to cover the rectangle. `2` (square...
dolphin
translate this code from Visual Basic .NET to Scheme: ```vb.net Function TravelCost(ByVal days As Integer(), ByVal costs As Integer()) As Integer Dim n As Integer = days.Length Dim dp(n + 1) As Integer For i As Integer = 1 To n dp(i) = dp(i - 1) + costs(0) Dim j As Integer = i - 1 Wh...
dolphin
Please explain the reasoning behind the following solution and provide code in Lisp: You are given two strings `s` and `p` where `p` is a **subsequence** of `s`. You are also given a **distinct 0-indexed** integer array `removable` containing a subset of indices of `s` (`s` is also **0-indexed**). You want to choose a...
dolphin
Please write the following solution using Julia: You are given an integer array `nums` and two integers `limit` and `goal`. The array `nums` has an interesting property that `abs(nums[i]) <= limit`. Return _the minimum number of elements you need to add to make the sum of the array equal to_ `goal`. The array must mai...
dolphin
Please focus on the algorithm of this problem and provide code in Scheme: Given an `m x n` matrix `board` where each cell is a battleship `'X'` or empty `'.'`, return _the number of the **battleships** on_ `board`. **Battleships** can only be placed horizontally or vertically on `board`. In other words, they can only ...
dolphin
Please explain the reasoning behind the following solution and provide code in Ruby: You are given two lists of closed intervals, `firstList` and `secondList`, where `firstList[i] = [starti, endi]` and `secondList[j] = [startj, endj]`. Each list of intervals is pairwise **disjoint** and in **sorted order**. Return _th...
dolphin
Please explain the following problem in detail and provide code in Rust: There are some stones in different positions on the X-axis. You are given an integer array `stones`, the positions of the stones. Call a stone an **endpoint stone** if it has the smallest or largest position. In one move, you pick up an **endpoin...
dolphin
Please explain the following problem in detail and provide code in python: With respect to a given `puzzle` string, a `word` is _valid_ if both the following conditions are satisfied: * `word` contains the first letter of `puzzle`. * For each letter in `word`, that letter is in `puzzle`. * For example, if th...
dolphin
convert this code from Scheme to Lisp: ```scheme (define (count-palindromic-substrings s) (define n (string-length s)) (define count 0) (for ((center (in-range (-( * 2 n) 1)))) (define left (quotient center 2)) (define right (+ left (modulo center 2))) (while (and (>= left 0) (< right n) (= (string-re...
dolphin
Please explain the reasoning behind the following solution and provide code in R: You are given a **binary** string `s` and a positive integer `k`. You can apply the following operation on the string **any** number of times: * Choose any substring of size `k` from `s` and **flip** all its characters, that is, turn ...
dolphin
Please write the following solution using Scheme: Given an array `nums` sorted in **non-decreasing** order, return _the maximum between the number of positive integers and the number of negative integers._ * In other words, if the number of positive integers in `nums` is `pos` and the number of negative integers is ...
dolphin
Please explain the reasoning behind the following solution and provide code in Dart: You are given an array `points` where `points[i] = [xi, yi]` represents a point on an **X-Y** plane. **Straight lines** are going to be added to the **X-Y** plane, such that every point is covered by at **least** one line. Return _th...
dolphin
port this code from Ruby to Rust: ```ruby def correct_binary_tree(root) stack = [] curr = root prev = nil while true do while curr do stack.append(curr) curr = curr.right end if stack.empty? break end node = stack.pop() ...
dolphin
Please explain the reasoning behind the following solution and provide code in Rust: 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 dr...
dolphin
Please write the following solution using java: There is a city composed of `n x n` blocks, where each block contains a single building shaped like a vertical square prism. You are given a **0-indexed** `n x n` integer matrix `grid` where `grid[r][c]` represents the **height** of the building located in the block at ro...
dolphin
Please focus on the efficiency of this problem and provide code in Object Pascal: Given an integer array `nums` and an integer `k`, return _the number of **subarrays** of_ `nums` _where the least common multiple of the subarray's elements is_ `k`. A **subarray** is a contiguous non-empty sequence of elements within an...
dolphin
Please write the following solution using Lisp: An integer `x` is **numerically balanced** if for every digit `d` in the number `x`, there are **exactly** `d` occurrences of that digit in `x`. Given an integer `n`, return _the **smallest numerically balanced** number **strictly greater** than_ `n`_._ **Example 1:** ...
dolphin
Please explain the following problem in detail and provide code in Perl: You are given two strings `firstString` and `secondString` that are **0-indexed** and consist only of lowercase English letters. Count the number of index quadruples `(i,j,a,b)` that satisfy the following conditions: * `0 <= i <= j < firstStrin...
dolphin
Please explain the following problem in detail and provide code in Erlang: Given the `root` of a binary tree, return _the preorder traversal of its nodes' values_. **Example 1:** **Input:** root = \[1,null,2,3\] **Output:** \[1,2,3\] **Example 2:** **Input:** root = \[\] **Output:** \[\] **Example 3:** **Input:**...
dolphin
Please write the following solution using Julia: You are given an array `nums` of `n` positive integers. You can perform two types of operations on any element of the array any number of times: * If the element is **even**, **divide** it by `2`. * For example, if the array is `[1,2,3,4]`, then you can do this...
dolphin
Please focus on the efficiency of this problem and provide code in Scheme: Given an `m x n` binary `matrix` filled with `0`'s and `1`'s, _find the largest square containing only_ `1`'s _and return its area_. **Example 1:** **Input:** matrix = \[\[ "1 ", "0 ", "1 ", "0 ", "0 "\],\[ "1 ", "0 ", "1 ", "1 ", "1 "\],\[ "1...
dolphin
Please focus on the algorithm of this problem and provide code in Objective-C: Given a list of folders `folder`, return _the folders after removing all **sub-folders** in those folders_. You may return the answer in **any order**. If a `folder[i]` is located within another `folder[j]`, it is called a **sub-folder** of...
dolphin
Please explain the following problem in detail and provide code in Visual Basic .NET: Let `f(x)` be the number of zeroes at the end of `x!`. Recall that `x! = 1 * 2 * 3 * ... * x` and by convention, `0! = 1`. * For example, `f(3) = 0` because `3! = 6` has no zeroes at the end, while `f(11) = 2` because `11! = 399168...
dolphin
Please focus on the efficiency of this problem and provide code in F#: The [Hamming distance](https://en.wikipedia.org/wiki/Hamming_distance) between two integers is the number of positions at which the corresponding bits are different. Given an integer array `nums`, return _the sum of **Hamming distances** between al...
dolphin
port this code to PHP: ```elixir def module CanMakeEqual do def can_make_equal(s, target) do s_count_ones = count_ones(s) target_count_ones = count_ones(target) s_count_ones >= target_count_ones end def count_ones(s) do count = 0 for i <- 0..(String.length(s) - 1) do if String.at(s, i) ...
dolphin
Please focus on the algorithm of this problem and provide code in ANSI C: You are given a string array `features` where `features[i]` is a single word that represents the name of a feature of the latest product you are working on. You have made a survey where users have reported which features they like. You are given ...
dolphin
Please focus on the efficiency of this problem and provide code in Lua: Alice has `n` balloons arranged on a rope. You are given a **0-indexed** string `colors` where `colors[i]` is the color of the `ith` balloon. Alice wants the rope to be **colorful**. She does not want **two consecutive balloons** to be of the same...
dolphin
convert this code to Scheme: ```scala def stringWithDifferentDifference(words: Array[String]): String = { def getDifferenceArray(word: String): Array[Int] = { (0 until word.length - 1).map(i => word(i + 1) - word(i)).toArray } val diffArrays = words.map(getDifferenceArray) var oddArrayIndex = -1 for (i ...
dolphin
port this code from R to javascript: ```R sum_of_digits <- function(n) { total <- 0 positive <- TRUE while (n > 0) { digit <- n %% 10 n <- n %/% 10 if (positive) { total <- total + digit } else { total <- total - digit } positive <- !positive } return(total)...
dolphin
Please explain the following problem in detail and provide code in Haskell: Given a string `path`, where `path[i] = 'N'`, `'S'`, `'E'` or `'W'`, each representing moving one unit north, south, east, or west, respectively. You start at the origin `(0, 0)` on a 2D plane and walk on the path specified by `path`. Return `...
dolphin
convert this code to PHP: ```lua function maxSubArrayLen(nums, k) local sumIndex = {} local maxLength, sum = 0, 0 for i = 1, #nums do sum = sum + nums[i] if sum == k then maxLength = i end if sum - k ~= nil and sumIndex[sum - k] ~= nil then maxLength = math.max(maxLength, i - sumIndex[...
dolphin
port this code from Groovy to Ruby: ```groovy class Bank { long[] balance Bank(long[] balance) { this.balance = balance } boolean transfer(int account1, int account2, long money) { if (account1 < 1 || account1 > balance.size() || account2 < 1 || account2 > balance.size() || bal...
dolphin
Please explain the reasoning behind the following solution and provide code in Kotlin: Given a 2D integer array `matrix`, return _the **transpose** of_ `matrix`. The **transpose** of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices. **Example 1:** **Input:** matrix...
dolphin
Please focus on the algorithm of this problem and provide code in python: You are playing a solitaire game with **three piles** of stones of sizes `a`​​​​​​, `b`,​​​​​​ and `c`​​​​​​ respectively. Each turn you choose two **different non-empty** piles, take one stone from each, and add `1` point to your score. The game...
dolphin
Please explain the following problem in detail and provide code in R: You have a **browser** of one tab where you start on the `homepage` and you can visit another `url`, get back in the history number of `steps` or move forward in the history number of `steps`. Implement the `BrowserHistory` class: * `BrowserHisto...
dolphin
Please explain the following problem in detail and provide code in python: Given two integers `tomatoSlices` and `cheeseSlices`. The ingredients of different burgers are as follows: * **Jumbo Burger:** `4` tomato slices and `1` cheese slice. * **Small Burger:** `2` Tomato slices and `1` cheese slice. Return `[tot...
dolphin
Please focus on the algorithm of this problem and provide code in PHP: There is a **bi-directional** graph with `n` vertices, where each vertex is labeled from `0` to `n - 1` (**inclusive**). The edges in the graph are represented as a 2D integer array `edges`, where each `edges[i] = [ui, vi]` denotes a bi-directional ...
dolphin
Please explain the reasoning behind the following solution and provide code in ANSI C: You are given a 2D integer array `intervals` where `intervals[i] = [lefti, righti]` represents the **inclusive** interval `[lefti, righti]`. You have to divide the intervals into one or more **groups** such that each interval is in ...
dolphin
Please write the following solution using java: Given an array of **unique** strings `words`, return _all the_ **[word squares](https://en.wikipedia.org/wiki/Word_square)** _you can build from_ `words`. The same word from `words` can be used **multiple times**. You can return the answer in **any order**. A sequence of...
dolphin
Please explain the reasoning behind the following solution and provide code in Julia: You are given an undirected graph (the **"original graph "**) with `n` nodes labeled from `0` to `n - 1`. You decide to **subdivide** each edge in the graph into a chain of nodes, with the number of new nodes varying between each edge...
dolphin
Please focus on the efficiency of this problem and provide code in Rust: Given a string `expression` of numbers and operators, return _all possible results from computing all the different possible ways to group numbers and operators_. You may return the answer in **any order**. The test cases are generated such that ...
dolphin
Please explain the reasoning behind the following solution and provide code in Object Pascal: Given an array `arr` of 4 digits, find the latest 24-hour time that can be made using each digit **exactly once**. 24-hour times are formatted as `"HH:MM "`, where `HH` is between `00` and `23`, and `MM` is between `00` and `...
dolphin
Please write the following solution using Scheme: You are given an integer `num`. You can swap two digits at most once to get the maximum valued number. Return _the maximum valued number you can get_. **Example 1:** **Input:** num = 2736 **Output:** 7236 **Explanation:** Swap the number 2 and the number 7. **Exampl...
dolphin
Please write the following solution using Julia: There is only one character `'A'` on the screen of a notepad. You can perform one of two operations on this notepad for each step: * Copy All: You can copy all the characters present on the screen (a partial copy is not allowed). * Paste: You can paste the character...
dolphin
convert this code from Object Pascal to Perl: ```pascal type TCell = record H, R, C: Integer; end; TMinHeap = specialize THeap<TCell, THeapMin>; function TrapRainWater(const HeightMap: array of array of Integer): Integer; const Dirs: array[0..3] of TPoint = ((X: 0; Y: 1), (X: 0; Y: -1), (X: 1; Y: 0), (X: ...
dolphin
Please write the following solution using Perl: The **complement** of an integer is the integer you get when you flip all the `0`'s to `1`'s and all the `1`'s to `0`'s in its binary representation. * For example, The integer `5` is `"101 "` in binary and its **complement** is `"010 "` which is the integer `2`. Give...
dolphin
Please write the following solution using Fortran: You are given an empty 2D binary grid `grid` of size `m x n`. The grid represents a map where `0`'s represent water and `1`'s represent land. Initially, all the cells of `grid` are water cells (i.e., all the cells are `0`'s). We may perform an add land operation which...
dolphin
Please write the following solution using SmallTalk: Given a string containing just the characters `'('` and `')'`, return _the length of the longest valid (well-formed) parentheses_ _substring_. **Example 1:** **Input:** s = "(() " **Output:** 2 **Explanation:** The longest valid parentheses substring is "() ". *...
dolphin
Please focus on the algorithm of this problem and provide code in python: You are given an elevation map represents as an integer array `heights` where `heights[i]` representing the height of the terrain at index `i`. The width at each index is `1`. You are also given two integers `volume` and `k`. `volume` units of wa...
dolphin
Please explain the following problem in detail and provide code in Julia: Given `head`, the head of a linked list, determine if the linked list has a cycle in it. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the `next` pointer. Internally, `pos...
dolphin
translate this code to javascript: ```fortran MODULE TreeNodeModule TYPE TreeNode INTEGER :: val TYPE(TreeNode), POINTER :: left => NULL(), right => NULL() END TYPE TreeNode END MODULE TreeNodeModule FUNCTION generate_trees(start, end) RESULT(trees) USE TreeNodeModule INTEGER, INTENT(IN...
dolphin
Please write the following solution using Perl: There is a **hidden** integer array `arr` that consists of `n` non-negative integers. It was encoded into another integer array `encoded` of length `n - 1`, such that `encoded[i] = arr[i] XOR arr[i + 1]`. For example, if `arr = [1,0,2,1]`, then `encoded = [1,2,3]`. You ...
dolphin
Please write the following solution using java: 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 java: You are given a 2D array of integers `envelopes` where `envelopes[i] = [wi, hi]` represents the width and the height of an envelope. One envelope can fit into another if and only if both the width and height of one envelope are greater than the other envelope's width and...
dolphin
Please explain the reasoning behind the following solution and provide code in ANSI C: 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 focus on the algorithm of this problem and provide code in c++: 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 mo...
dolphin
Please explain the following problem in detail and provide code in Objective-C: Given a **binary tree** `root`, return _the maximum sum of all keys of **any** sub-tree which is also a Binary Search Tree (BST)_. Assume a BST is defined as follows: * The left subtree of a node contains only nodes with keys **less tha...
dolphin
port this code from Lisp to Clojure: ```lisp (defun minimum-total (triangle) (loop for row downfrom (1- (length triangle)) to 0 do (loop for col below (length (nth row triangle)) do (setf (nth col (nth row triangle)) (+ (nth col (nth row triangle)) (min...
dolphin
translate this code from C# to PHP: ```csharp public static int RatioSubstringCount(string s, int num1, int num2) { int count0 = 0, count1 = 0, result = 0; Dictionary<int, int> frequency = new Dictionary<int, int>(); frequency[0] = 1; foreach (char c in s) { if (c == '0') { ...
dolphin
Please explain the reasoning behind the following solution and provide code in Perl: An **ugly number** is a positive integer that is divisible by `a`, `b`, or `c`. Given four integers `n`, `a`, `b`, and `c`, return the `nth` **ugly number**. **Example 1:** **Input:** n = 3, a = 2, b = 3, c = 5 **Output:** 4 **Expla...
dolphin
Please focus on the functionality of this problem and provide code in Elixir: Given an integer array `nums` of size `n`, return _the minimum number of moves required to make all array elements equal_. In one move, you can increment or decrement an element of the array by `1`. Test cases are designed so that the answe...
dolphin
Please focus on the functionality of this problem and provide code in TypeScript: You have been tasked with writing a program for a popular bank that will automate all its incoming transactions (transfer, deposit, and withdraw). The bank has `n` accounts numbered from `1` to `n`. The initial balance of each account is ...
dolphin
port this code from Clojure to PHP: ```clojure (defn gcd [a b] (if (zero? b) a (recur b (mod a b)))) (defn max-score [nums] (let [n (quot (count nums) 2)] (let [dp (vec (repeat (bit-shift-left 1 n) (vec (repeat (inc n) 0)))) ; initialize dp table gcd (vec (repeat n (vec (repeat n 0))))] ; ini...
dolphin
Please explain the reasoning behind the following solution and provide code in R: You are given an integer array `nums` and an integer `target`. You want to build an **expression** out of nums by adding one of the symbols `'+'` and `'-'` before each integer in nums and then concatenate all the integers. * For examp...
dolphin
convert this code to Visual Basic .NET: ```clojure (defn max-ramp-width [nums] (let [n (count nums) max-width (atom 0) min-left (make-array Long/TYPE n) max-right (make-array Long/TYPE n)] (aset min-left 0 (aget nums 0)) (doseq [i (range 1 n)] (aset min-left i (min (aget nums i) ...
dolphin