instruction_seed
stringlengths
29
40.5k
source
stringclasses
6 values
port this code from Julia to Dart: ```julia function findItinerary(tickets) flights = Dict{String, Vector{String}}() itinerary = Vector{String}() for ticket in tickets if haskey(flights, ticket[1]) push!(flights[ticket[1]], ticket[2]) else flights[ticket[1]] = [ticke...
dolphin
Please focus on the functionality of this problem and provide code in java: 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 give...
dolphin
Please write the following solution using Scheme: You are given an `m x n` binary matrix `grid`, where `0` represents a sea cell and `1` represents a land cell. A **move** consists of walking from one land cell to another adjacent (**4-directionally**) land cell or walking off the boundary of the `grid`. Return _the ...
dolphin
Please explain the reasoning behind the following solution and provide code in Groovy: You are given a **0-indexed** string `s` consisting of only lowercase English letters, where each letter in `s` appears **exactly** **twice**. You are also given a **0-indexed** integer array `distance` of length `26`. Each letter i...
dolphin
Please explain the reasoning behind the following solution and provide code in Erlang: Given two arrays `nums1` and `nums2`. Return the maximum dot product between **non-empty** subsequences of nums1 and nums2 with the same length. A subsequence of a array is a new array which is formed from the original array by del...
dolphin
Please explain the reasoning behind the following solution and provide code in ANSI C: You are given a stream of **records** about a particular stock. Each record contains a **timestamp** and the corresponding **price** of the stock at that timestamp. Unfortunately due to the volatile nature of the stock market, the r...
dolphin
translate this code to Groovy: ```java public boolean isCovered(int[][] ranges, int left, int right) { for (int i = left; i <= right; i++) { boolean found = false; for (int[] range : ranges) { if (i >= range[0] && i <= range[1]) { found = true; break; ...
dolphin
translate this code to Kotlin: ```python def countSubIslands(grid1, grid2): def dfs(i, j): if i < 0 or i >= len(grid1) or j < 0 or j >= len(grid1[0]) or grid2[i][j] == 0: return True grid2[i][j] = 0 isSubIsland = grid1[i][j] == 1 isSubIsland &= dfs(i + 1, j) isS...
dolphin
Please explain the following problem in detail and provide code in Haskell: You are given an integer array `nums` and an integer `k`. Split the array into some number of non-empty subarrays. The **cost** of a split is the sum of the **importance value** of each subarray in the split. Let `trimmed(subarray)` be the ve...
dolphin
Please explain the following problem in detail and provide code in Go: You are given two string arrays `username` and `website` and an integer array `timestamp`. All the given arrays are of the same length and the tuple `[username[i], website[i], timestamp[i]]` indicates that the user `username[i]` visited the website ...
dolphin
translate this code to javascript: ```clojure (defn monotone-increasing-digits [n] (let [n-str (str n) len (count n-str)] (loop [i (- len 1) n-str n-str] (cond (<= i 0) (Integer/parseInt n-str) (< (int (get n-str i)) (int (get n-str (- i 1)))) (recur (dec i) ...
dolphin
Please explain the following problem in detail and provide code in R: Given an array of integers `arr`, return `true` _if the number of occurrences of each value in the array is **unique** or_ `false` _otherwise_. **Example 1:** **Input:** arr = \[1,2,2,1,1,3\] **Output:** true **Explanation:** The value 1 has 3 occu...
dolphin
Please write the following solution using PHP: You are given `n` balloons, indexed from `0` to `n - 1`. Each balloon is painted with a number on it represented by an array `nums`. You are asked to burst all the balloons. If you burst the `ith` balloon, you will get `nums[i - 1] * nums[i] * nums[i + 1]` coins. If `i - ...
dolphin
Please explain the reasoning behind the following solution and provide code in java: A string can be **abbreviated** by replacing any number of **non-adjacent** substrings with their lengths. For example, a string such as `"substitution "` could be abbreviated as (but not limited to): * `"s10n "` ( `"s ubstitutio n ...
dolphin
convert this code to Object Pascal: ```kotlin fun lengthOfCycle(n: Int, queries: Array<IntArray>): IntArray { val result = IntArray(queries.size) for (i in queries.indices) { var (a, b) = queries[i] var depthA = 0 var depthB = 0 while (a != b) { if (a < b) { ...
dolphin
translate this code from Scala to python: ```scala def findMaxForm(strs: Array[String], m: Int, n: Int): Int = { val dp = Array.ofDim[Int](m + 1, n + 1) for (s <- strs) { val ones = s.count(_ == '1') val zeros = s.length - ones for (i <- m to zeros by -1; j <- n to ones by -1) { ...
dolphin
Please explain the reasoning behind the following solution and provide code in R: You are given two strings `a` and `b` that consist of lowercase letters. In one operation, you can change any character in `a` or `b` to **any lowercase letter**. Your goal is to satisfy **one** of the following three conditions: * **...
dolphin
Please explain the reasoning behind the following solution and provide code in Kotlin: A linked list of length `n` is given such that each node contains an additional random pointer, which could point to any node in the list, or `null`. Construct a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy...
dolphin
Please explain the following problem in detail and provide code in Visual Basic .NET: A string `s` can be partitioned into groups of size `k` using the following procedure: * The first group consists of the first `k` characters of the string, the second group consists of the next `k` characters of the string, and so...
dolphin
Please explain the reasoning behind the following solution and provide code in C#: Design a data structure that will be initialized with a string array, and then it should answer queries of the shortest distance between two different strings from the array. Implement the `WordDistance` class: * `WordDistance(String...
dolphin
Please focus on the efficiency of this problem and provide code in Haskell: You have `n` computers. You are given the integer `n` and a **0-indexed** integer array `batteries` where the `ith` battery can **run** a computer for `batteries[i]` minutes. You are interested in running **all** `n` computers **simultaneously*...
dolphin
convert this code to F#: ```csharp public int CountPrefixes(string[] words, string pref) { int count = 0; foreach (string word in words) { if (word.StartsWith(pref)) { count++; } } return count; } ```
dolphin
Please focus on the algorithm of this problem and provide code in Groovy: You are given an undirected graph defined by an integer `n`, the number of nodes, and a 2D integer array `edges`, the edges in the graph, where `edges[i] = [ui, vi]` indicates that there is an **undirected** edge between `ui` and `vi`. You are al...
dolphin
Please write the following solution using Elixir: You are given an array of positive integers `nums` and want to erase a subarray containing **unique elements**. The **score** you get by erasing the subarray is equal to the **sum** of its elements. Return _the **maximum score** you can get by erasing **exactly one** s...
dolphin
Please explain the reasoning behind the following solution and provide code in Fortran: Given a **0-indexed** integer array `nums`, return _the **smallest** index_ `i` _of_ `nums` _such that_ `i mod 10 == nums[i]`_, or_ `-1` _if such index does not exist_. `x mod y` denotes the **remainder** when `x` is divided by `y`...
dolphin
Please write the following solution using Erlang: A virus is spreading rapidly, and your task is to quarantine the infected area by installing walls. The world is modeled as an `m x n` binary grid `isInfected`, where `isInfected[i][j] == 0` represents uninfected cells, and `isInfected[i][j] == 1` represents cells cont...
dolphin
convert this code from PHP to Groovy: ```php function leftmostOne($binaryMatrix) { $dimensions = $binaryMatrix->dimensions(); $rows = $dimensions[0]; $cols = $dimensions[1]; $row = 0; $col = $cols - 1; $leftmost = -1; while ($row < $rows && $col >= 0) { if ($binaryMatrix->get($r...
dolphin
Please explain the following problem in detail and provide code in Lisp: You are given a non-negative integer array `nums`. In one operation, you must: * Choose a positive integer `x` such that `x` is less than or equal to the **smallest non-zero** element in `nums`. * Subtract `x` from every **positive** element ...
dolphin
Please explain the reasoning behind the following solution and provide code in java: Given a **sorted** integer array `nums` and three integers `a`, `b` and `c`, apply a quadratic function of the form `f(x) = ax2 + bx + c` to each element `nums[i]` in the array, and return _the array in a sorted order_. **Example 1:**...
dolphin
translate this code to Dart: ```Objective-C #define mod 1000000007 int count[3]; int dp[3]; int specialSubsequences(NSArray <NSNumber *> *nums) { int n = (int)[nums count]; memset(count, 0, sizeof(count)); memset(dp, 0, sizeof(dp)); for (int i = 0; i < n; i++) { int num = [nums[i] intValu...
dolphin
Please explain the reasoning behind the following solution and provide code in Mojo: You have `k` lists of sorted integers in **non-decreasing order**. Find the **smallest** range that includes at least one number from each of the `k` lists. We define the range `[a, b]` is smaller than range `[c, d]` if `b - a < d - c...
dolphin
convert this code to Clojure: ```julia function sort_by_frequency(s::AbstractString) freq = Dict{Char, Int}() for c in s freq[c] = get(freq, c, 0) + 1 end chars = collect(s) sort!(chars, by = c -> freq[c], rev = true) return join(chars) end ```
dolphin
Please write the following solution using Rust: Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST. According to the [definition of LCA on Wikipedia](https://en.wikipedia.org/wiki/Lowest_common_ancestor): "The lowest common ancestor is defined between two nodes `...
dolphin
Please explain the following problem in detail and provide code in Scala: Given a string `s`, return _the number of **palindromic substrings** in it_. A string is a **palindrome** when it reads the same backward as forward. A **substring** is a contiguous sequence of characters within the string. **Example 1:** **I...
dolphin
translate this code to Objective-C: ```clojure (defn is-covered [ranges left right] (let [covered (vec (repeat 51 0))] (doseq [range ranges i (range (first range) (inc (second range)))] (aset covered i 1)) (every? true? (map (fn [i] (if (not= (aget covered i) 1) false true)) ...
dolphin
Please focus on the efficiency of this problem and provide code in Dart: 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*...
dolphin
Please focus on the efficiency of this problem and provide code in Lua: Given `n` `points` on a 2D plane where `points[i] = [xi, yi]`, Return _the **widest vertical area** between two points such that no points are inside the area._ A **vertical area** is an area of fixed-width extending infinitely along the y-axis (i...
dolphin
convert this code from Lua to python: ```lua -- Definition for a binary tree node. -- struct TreeNode { -- int val; -- TreeNode *left; -- TreeNode *right; -- TreeNode(int x) : val(x), left(NULL), right(NULL) {} -- }; function inorder_successor(root, p) local successor = nil while root do ...
dolphin
Please focus on the functionality of this problem and provide code in Elixir: A game on an **undirected** graph is played by two players, Mouse and Cat, who alternate turns. The graph is given as follows: `graph[a]` is a list of all nodes `b` such that `ab` is an edge of the graph. The mouse starts at node `1` and go...
dolphin
port this code to Haskell: ```pascal function optimalPlay(n: integer): boolean; var dp: array[0..1000] of boolean; i, j: integer; begin dp[0] := false; dp[1] := true; for i := 2 to n do begin dp[i] := false; for j := 1 to i div 2 do begin if (i mod j = 0) and (not dp[i-j]) then begin...
dolphin
port this code from Perl to Dart: ```perl use List::Util qw(sum); use Algorithm::Combinatorics qw(variations_with_repetition); sub closest_cost { my ($base_costs, $topping_costs, $target) = @_; my $closest = 1e9; my $m = scalar(@$topping_costs); my $combinations = variations_with_repetition([0, 1, 2], ...
dolphin
Please explain the reasoning behind the following solution and provide code in ANSI C: Suppose you have `n` integers labeled `1` through `n`. A permutation of those `n` integers `perm` (**1-indexed**) is considered a **beautiful arrangement** if for every `i` (`1 <= i <= n`), **either** of the following is true: * `...
dolphin
Please explain the reasoning behind the following solution and provide code in Lisp: 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 ...
dolphin
Please write the following solution using Perl: Given two integer arrays `startTime` and `endTime` and given an integer `queryTime`. The `ith` student started doing their homework at the time `startTime[i]` and finished it at time `endTime[i]`. Return _the number of students_ doing their homework at time `queryTime`....
dolphin
Please explain the reasoning behind the following solution and provide code in Groovy: Given the `root` of a binary tree, split the binary tree into two subtrees by removing one edge such that the product of the sums of the subtrees is maximized. Return _the maximum product of the sums of the two subtrees_. Since the ...
dolphin
Please write the following solution using Ruby: Given two vectors of integers `v1` and `v2`, implement an iterator to return their elements alternately. Implement the `ZigzagIterator` class: * `ZigzagIterator(List v1, List v2)` initializes the object with the two vectors `v1` and `v2`. * `boolean hasNext()` retur...
dolphin
Please write the following solution using Ruby: There is a hotel with `n` rooms. The rooms are represented by a 2D integer array `rooms` where `rooms[i] = [roomIdi, sizei]` denotes that there is a room with room number `roomIdi` and size equal to `sizei`. Each `roomIdi` is guaranteed to be **unique**. You are also giv...
dolphin
Please explain the reasoning behind the following solution and provide code in Mojo: You are given an integer `n`. You have an `n x n` binary grid `grid` with all values initially `1`'s except for some indices given in the array `mines`. The `ith` element of the array `mines` is defined as `mines[i] = [xi, yi]` where `...
dolphin
Please explain the following problem in detail and provide code in python: You are given an integer `n` representing the number of playing cards you have. A **house of cards** meets the following conditions: * A **house of cards** consists of one or more rows of **triangles** and horizontal cards. * **Triangles** ...
dolphin
translate this code from Haskell to Kotlin: ```haskell import Data.List (sort) closestRoom :: [[Int]] -> [[Int]] -> [Int] closestRoom rooms queries = result where rooms' = sortBy (\a b -> compare (snd b) (snd a)) rooms queries' = map (\(a,b) -> (b,a)) (zip queries [0..]) queries'' = sortBy (\a b -> comp...
dolphin
Please explain the following problem in detail and provide code in F#: You are given the array `paths`, where `paths[i] = [cityAi, cityBi]` means there exists a direct path going from `cityAi` to `cityBi`. _Return the destination city, that is, the city without any path outgoing to another city._ It is guaranteed that...
dolphin
Please write the following solution using Scheme: 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 the number of _closed islands_. **Exam...
dolphin
convert this code from F# to javascript: ```fsharp let longestPalindrome(s: string) : int = let charCount = Array.zeroCreate 128 let mutable result = 0 for c in s do charCount.[int c] <- charCount.[int c] + 1 for count in charCount do result <- result + count / 2 * 2 if result % ...
dolphin
Please focus on the algorithm of this problem and provide code in SmallTalk: Given two strings `needle` and `haystack`, return the index of the first occurrence of `needle` in `haystack`, or `-1` if `needle` is not part of `haystack`. **Example 1:** **Input:** haystack = "sadbutsad ", needle = "sad " **Output:** 0 ...
dolphin
Please write the following solution using Mojo: You are given a 2D integer array `items` where `items[i] = [pricei, beautyi]` denotes the **price** and **beauty** of an item respectively. You are also given a **0-indexed** integer array `queries`. For each `queries[j]`, you want to determine the **maximum beauty** of ...
dolphin
Please write the following solution using Julia: Given a string `n` representing an integer, return _the closest integer (not including itself), which is a palindrome_. If there is a tie, return _**the smaller one**_. The closest is defined as the absolute difference minimized between two integers. **Example 1:** **...
dolphin
Please write the following solution using Groovy: You are given a stream of `n` videos, each represented by a **distinct** number from `1` to `n` that you need to "upload " to a server. You need to implement a data structure that calculates the length of the **longest uploaded prefix** at various points in the upload p...
dolphin
port this code from Julia to C#: ```julia function countNegatives(grid::Array{Int, 2}) m, n, count, i, j = size(grid, 1), size(grid, 2), 0, 1, size(grid, 2) while i <= m && j >= 1 if grid[i, j] < 0 count += j i += 1 else j -= 1 end end return c...
dolphin
Please explain the reasoning behind the following solution and provide code in Lisp: Given a string `s`. In one step you can insert any character at any index of the string. Return _the minimum number of steps_ to make `s` palindrome. A **Palindrome String** is one that reads the same backward as well as forward. **...
dolphin
Please explain the following problem in detail and provide code in C#: Given two strings `s1` and `s2`, return `true` _if_ `s2` _contains a permutation of_ `s1`_, or_ `false` _otherwise_. In other words, return `true` if one of `s1`'s permutations is the substring of `s2`. **Example 1:** **Input:** s1 = "ab ", s2 =...
dolphin
Please explain the reasoning behind the following solution and provide code in Lisp: You are given an `n x n` `grid` representing a field of cherries, each cell is one of three possible integers. * `0` means the cell is empty, so you can pass through, * `1` means the cell contains a cherry that you can pick up and...
dolphin
Please focus on the algorithm of this problem and provide code in ANSI C: Alice is a caretaker of `n` gardens and she wants to plant flowers to maximize the total beauty of all her gardens. You are given a **0-indexed** integer array `flowers` of size `n`, where `flowers[i]` is the number of flowers already planted in...
dolphin
translate this code from Kotlin to Go: ```kotlin class TreeNode(var `val`: Int) { var left: TreeNode? = null var right: TreeNode? = null } fun lowestCommonAncestor(root: TreeNode?, nodes: Array<TreeNode>): TreeNode? { if (root == null || root in nodes) { return root } val left = lowestCommo...
dolphin
Please focus on the functionality of this problem and provide code in F#: Given two non-negative integers `num1` and `num2` represented as strings, return the product of `num1` and `num2`, also represented as a string. **Note:** You must not use any built-in BigInteger library or convert the inputs to integer directly...
dolphin
Please write the following solution using Visual Basic .NET: 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`, `x1 = 2`, a...
dolphin
Please focus on the algorithm of this problem and provide code in Lisp: Given a single-digit integer `d` and two integers `low` and `high`, return _the number of times that_ `d` _occurs as a digit in all integers in the inclusive range_ `[low, high]`. **Example 1:** **Input:** d = 1, low = 1, high = 13 **Output:** 6 ...
dolphin
Please write the following solution using ANSI C: Write an algorithm to determine if a number `n` is happy. A **happy number** is a number defined by the following process: * Starting with any positive integer, replace the number by the sum of the squares of its digits. * Repeat the process until the number equal...
dolphin
Please explain the reasoning behind the following solution and provide code in ANSI C: Given the `root` of a binary search tree, and an integer `k`, return _the_ `kth` _smallest value (**1-indexed**) of all the values of the nodes in the tree_. **Example 1:** **Input:** root = \[3,1,4,null,2\], k = 1 **Output:** 1 *...
dolphin
convert this code from Object Pascal to Julia: ``` function poorPigs(buckets, minutesToDie, minutesToTest: Integer): Integer; var pigs, testsPerPig, totalTests: Integer; begin pigs := 0; testsPerPig := minutesToTest div minutesToDie + 1; totalTests := 1; while totalTests < buckets do begin totalTests :...
dolphin
translate this code to PHP: ```dart List<int> flowersInBloom(List<List<int>> flowers, List<int> people) { flowers.sort((a, b) => a[1] - b[1]); people.sort(); List<int> result = List.filled(people.length, 0); int flowerIdx = 0; for (int person in people) { while (flowerIdx < flowers.length && flowers[flowe...
dolphin
Please write the following solution using Elixir: You are given a string `s` and a **positive** integer `k`. Select a set of **non-overlapping** substrings from the string `s` that satisfy the following conditions: * The **length** of each substring is **at least** `k`. * Each substring is a **palindrome**. Retu...
dolphin
Please focus on the algorithm of this problem and provide code in Swift: You are given an integer array `nums` and an integer `k`. In one operation, you can pick two numbers from the array whose sum equals `k` and remove them from the array. Return _the maximum number of operations you can perform on the array_. **E...
dolphin
Please focus on the algorithm of this problem and provide code in Lua: You are given an integer array `nums` of size `n` containing **each** element from `0` to `n - 1` (**inclusive**). Each of the elements from `1` to `n - 1` represents an item, and the element `0` represents an empty space. In one operation, you can...
dolphin
Please explain the following problem in detail and provide code in python: You have a `RecentCounter` class which counts the number of recent requests within a certain time frame. Implement the `RecentCounter` class: * `RecentCounter()` Initializes the counter with zero recent requests. * `int ping(int t)` Adds a...
dolphin
Please explain the reasoning behind the following solution and provide code in Groovy: You are given an integer array `nums` and an integer `threshold`. Find any subarray of `nums` of length `k` such that **every** element in the subarray is **greater** than `threshold / k`. Return _the **size** of **any** such subar...
dolphin
Please explain the following problem in detail and provide code in SmallTalk: Roman numerals are represented by seven different symbols: `I`, `V`, `X`, `L`, `C`, `D` and `M`. **Symbol** **Value** I 1 V 5 X 10 L 50 C 100 D 500 M 1...
dolphin
Please write the following solution using Julia: Two strings `word1` and `word2` are considered **almost equivalent** if the differences between the frequencies of each letter from `'a'` to `'z'` between `word1` and `word2` is **at most** `3`. Given two strings `word1` and `word2`, each of length `n`, return `true` _i...
dolphin
convert this code to Groovy: ```php function findTheLongestSubstring($s) { $pos = [-1 => 0]; $ans = $cur = 0; for ($i = 0; $i < strlen($s); $i++) { $cur ^= 1 << (strpos("aeiou", $s[$i]) + 1) >> 1; if (!array_key_exists($cur, $pos)) { $pos[$cur] = $i + 1; } $ans = ...
dolphin
convert this code to Julia: ```perl sub minimum_path_cost { my ($stones) = @_; my $n = scalar(@$stones); my $max_cost = $stones->[-1]; for (my $i = 1; $i < $n-1; $i++) { my $current_cost = max($stones->[$i], $stones->[-1]-$stones->[$i]); $max_cost = min($max_cost, $current_cost); } ...
dolphin
Please explain the reasoning behind the following solution and provide code in PHP: Given the `root` of a binary tree, return _the lowest common ancestor of its deepest leaves_. Recall that: * The node of a binary tree is a leaf if and only if it has no children * The depth of the root of the tree is `0`. if the ...
dolphin
convert this code to Scheme: ```lua function majority_element(nums) local count = 0 local candidate = nil for _, num in ipairs(nums) do if count == 0 then candidate = num end count = count + (num == candidate and 1 or -1) end return candidate end ```
dolphin
Please focus on the efficiency of this problem and provide code in R: Given an `m x n` `matrix`, return _all elements of the_ `matrix` _in spiral order_. **Example 1:** **Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\] **Output:** \[1,2,3,6,9,8,7,4,5\] **Example 2:** **Input:** matrix = \[\[1,2,3,4\],\[5,6,7,8\...
dolphin
Please explain the following problem in detail and provide code in javascript: Given an integer array `nums` and an integer `k`, return the maximum sum of a **non-empty** subsequence of that array such that for every two **consecutive** integers in the subsequence, `nums[i]` and `nums[j]`, where `i < j`, the condition ...
dolphin
Please focus on the efficiency of this problem and provide code in Mojo: You are given an array of positive integers `nums` and want to erase a subarray containing **unique elements**. The **score** you get by erasing the subarray is equal to the **sum** of its elements. Return _the **maximum score** you can get by er...
dolphin
Please write the following solution using Go: Given an integer array `nums` and an integer `val`, remove all occurrences of `val` in `nums` [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm). The order of the elements may be changed. Then return _the number of elements in_ `nums` _which are not equal to_ ...
dolphin
Please explain the following problem in detail and provide code in Ruby: Given the `head` of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return _the reordered list_. The **first** node is considered **odd**, and the **second** node is **even**, and s...
dolphin
convert this code to Dart: ```typescript function findReplaceString(s: string, indices: number[], sources: string[], targets: string[]): string { const n = indices.length; const arr = Array.from({ length: n }, (_, i) => i).sort((a, b) => indices[a] - indices[b]); let offset = 0; for (const i of arr) { ...
dolphin
Please explain the following problem in detail and provide code in Erlang: You would like to make dessert and are preparing to buy the ingredients. You have `n` ice cream base flavors and `m` types of toppings to choose from. You must follow these rules when making your dessert: * There must be **exactly one** ice c...
dolphin
Please explain the following problem in detail and provide code in Go: Given a **0-indexed** integer array `nums` of size `n`, find the **maximum difference** between `nums[i]` and `nums[j]` (i.e., `nums[j] - nums[i]`), such that `0 <= i < j < n` and `nums[i] < nums[j]`. Return _the **maximum difference**._ If no such...
dolphin
Please focus on the efficiency of this problem and provide code in Elixir: A **valid cut** in a circle can be: * A cut that is represented by a straight line that touches two points on the edge of the circle and passes through its center, or * A cut that is represented by a straight line that touches one point on ...
dolphin
convert this code to Object Pascal: ```c int max_fruits(int* fruits, int fruitsSize){ int first_fruit = -1, second_fruit = -1, last_fruit = -1, max_fruits = 0, current_max = 0; for(int i = 0; i < fruitsSize; i++){ if(fruits[i] == first_fruit || fruits[i] == second_fruit){ current_max++; ...
dolphin
Please explain the reasoning behind the following solution and provide code in Rust: Winter is coming! During the contest, your first job is to design a standard heater with a fixed warm radius to warm all the houses. Every house can be warmed, as long as the house is within the heater's warm radius range. Given the ...
dolphin
convert this code to Rust: ```fortran recursive function range_sum(root, low, high) result(res) implicit none class(node),intent(in) :: root integer,intent(in) :: low,high integer :: res if (associated(root)) then if (root%val > high) then res = range_sum(root%left,low,high) else if (root%val < ...
dolphin
Please write the following solution using Erlang: You are given a **0-indexed** array of string `words` and two integers `left` and `right`. A string is called a **vowel string** if it starts with a vowel character and ends with a vowel character where vowel characters are `'a'`, `'e'`, `'i'`, `'o'`, and `'u'`. Retur...
dolphin
Please write the following solution using Go: Given the heads of two singly linked-lists `headA` and `headB`, return _the node at which the two lists intersect_. If the two linked lists have no intersection at all, return `null`. For example, the following two linked lists begin to intersect at node `c1`: The test ca...
dolphin
port this code from Ruby to ANSI C: ```ruby def new_integer(n) result = 0 base = 1 while n > 0 result += (n % 9) * base n /= 9 base *= 10 end result end ```
dolphin
translate this code from Mojo to PHP: ```mojo sub replace_with_rank(arr as int[]) as int[] sorted_arr = sort(arr) ranks = new Map() rank = 1 for i in 0..(len(sorted_arr)-1) if i > 0 and sorted_arr[i] != sorted_arr[i - 1] rank = rank + 1 ranks[sorted_arr[i]] = rank for i i...
dolphin
Please focus on the functionality of this problem and provide code in Erlang: You are given an `m x n` matrix `M` initialized with all `0`'s and an array of operations `ops`, where `ops[i] = [ai, bi]` means `M[x][y]` should be incremented by one for all `0 <= x < ai` and `0 <= y < bi`. Count and return _the number of ...
dolphin
Please explain the reasoning behind the following solution and provide code in Erlang: You are given an `m x n` integer matrix `grid`, where you can move from a cell to any adjacent cell in all `4` directions. Return _the number of **strictly** **increasing** paths in the grid such that you can start from **any** cell...
dolphin
Please explain the reasoning behind the following solution and provide code in Elixir: You are given a string `s` consisting only of lowercase English letters. In one **move**, you can select any two **adjacent** characters of `s` and swap them. Return _the **minimum number of moves** needed to make_ `s` _a palindrom...
dolphin