instruction_seed
stringlengths
29
40.5k
source
stringclasses
6 values
convert this code to Haskell: ```vb.net Public Function MaxSideLength(mat As Integer(,), threshold As Integer) As Integer Dim m As Integer = mat.GetLength(0) Dim n As Integer = mat.GetLength(1) Dim preSum(m, n) As Integer For i As Integer = 1 To m For j As Integer = 1 To n preSum(i,...
dolphin
Please explain the reasoning behind the following solution and provide code in Mojo: Alice and Bob are opponents in an archery competition. The competition has set the following rules: 1. Alice first shoots `numArrows` arrows and then Bob shoots `numArrows` arrows. 2. The points are then calculated as follows: 1...
dolphin
Please write the following solution using c++: You are given a string `s` consisting of lowercase English letters. A **duplicate removal** consists of choosing two **adjacent** and **equal** letters and removing them. We repeatedly make **duplicate removals** on `s` until we no longer can. Return _the final string af...
dolphin
Please explain the following problem in detail and provide code in Julia: 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 ...
dolphin
port this code to R: ```dart bool isInterleave(String s1, String s2, String s3) { int m = s1.length, n = s2.length; if (m + n != s3.length) return false; List<List<bool>> dp = List.generate(m + 1, (_) => List.filled(n + 1, false)); dp[0][0] = true; for (int i = 1; i <= m; i++) { dp[i][0] = dp[i - 1][0] &...
dolphin
Please focus on the efficiency of this problem and provide code in Elixir: Given an array of strings `strs`, return _the length of the **longest uncommon subsequence** between them_. If the longest uncommon subsequence does not exist, return `-1`. An **uncommon subsequence** between an array of strings is a string tha...
dolphin
Please write the following solution using Scheme: There are `n` friends that are playing a game. The friends are sitting in a circle and are numbered from `1` to `n` in **clockwise order**. More formally, moving clockwise from the `ith` friend brings you to the `(i+1)th` friend for `1 <= i < n`, and moving clockwise fr...
dolphin
port this code from Ruby to Lisp: ```ruby def rotate_grid(grid, k) return grid if grid.empty? m, n = grid.length, grid[0].length num_layers = [m, n].min / 2 (0...num_layers).each do |layer| num_to_rotate = (m - 2 * layer) * 2 + (n - 2 * layer - 2) * 2 effective_k = k % num_to_rotat...
dolphin
Please explain the following problem in detail and provide code in python: In a string composed of `'L'`, `'R'`, and `'X'` characters, like `"RXXLRXRXL "`, a move consists of either replacing one occurrence of `"XL "` with `"LX "`, or replacing one occurrence of `"RX "` with `"XR "`. Given the starting string `start` a...
dolphin
convert this code to Scheme: ```julia function fraction_to_decimal(numerator::Int, denominator::Int)::String if numerator == 0 return "0" end res = [] if xor(numerator > 0, denominator > 0) push!(res, "-") end num = abs(numerator) den = abs(denominator) push!(res, string(...
dolphin
convert this code from Kotlin to R: ```kotlin class Node(var `val`: Int, var children: List<Node> = listOf()) fun levelOrder(root: Node?): List<List<Int>> { if (root == null) return emptyList() val result = mutableListOf<List<Int>>() val queue = mutableListOf<Node>() queue.add(root) while...
dolphin
Please write the following solution using c++: There is a 1 million by 1 million grid on an XY-plane, and the coordinates of each grid square are `(x, y)`. We start at the `source = [sx, sy]` square and want to reach the `target = [tx, ty]` square. There is also an array of `blocked` squares, where each `blocked[i] = ...
dolphin
translate this code to Perl: ```php define("MOD", 1000000007); function add_rooms($idx, $children, &$memo) { if (empty($children[$idx])) { return 1; } if ($memo[$idx] != -1) { return $memo[$idx]; } $res = 1; $cnt = 0; foreach ($children[$idx] as $child) { $cnt++; ...
dolphin
port this code from Scala to Ruby: ```scala def visiblePoints(points: Array[Array[Int]], angle: Int, location: Array[Int]): Int = { var visiblePoints = 0 for (p <- points) { val x = p(0) - location(0) val y = p(1) - location(1) if (x == 0 && y == 0) { visiblePoints += 1 ...
dolphin
Please explain the reasoning behind the following solution and provide code in javascript: You are given an integer array `ranks` and a character array `suits`. You have `5` cards where the `ith` card has a rank of `ranks[i]` and a suit of `suits[i]`. The following are the types of **poker hands** you can make from be...
dolphin
Please explain the following problem in detail and provide code in Erlang: Given an integer array `instructions`, you are asked to create a sorted array from the elements in `instructions`. You start with an empty container `nums`. For each element from **left to right** in `instructions`, insert it into `nums`. The **...
dolphin
Please explain the following problem in detail and provide code in F#: You are given a 2D integer array `intervals`, where `intervals[i] = [lefti, righti]` describes the `ith` interval starting at `lefti` and ending at `righti` **(inclusive)**. The **size** of an interval is defined as the number of integers it contain...
dolphin
Please focus on the functionality of this problem and provide code in Fortran: Given an integer array `nums` and an integer `k`, return _the_ `k` _most frequent elements_. You may return the answer in **any order**. **Example 1:** **Input:** nums = \[1,1,1,2,2,3\], k = 2 **Output:** \[1,2\] **Example 2:** **Input:*...
dolphin
Please explain the following problem in detail and provide code in Mojo: Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values. **Example 1:** **Input:** n = 5 **Output:** true **Explanation:** The binary representation of 5 is: 101 **Example ...
dolphin
Please focus on the algorithm of this problem and provide code in TypeScript: Given a string `s`, return `true` _if the_ `s` _can be palindrome after deleting **at most one** character from it_. **Example 1:** **Input:** s = "aba " **Output:** true **Example 2:** **Input:** s = "abca " **Output:** true **Explanat...
dolphin
convert this code from Fortran to Kotlin: ```fortran function countEqualRowColumnPairs(grid) result(ans) integer :: n, i, j, k, ans integer, dimension(:,:) :: grid n = size(grid, 1) ans = 0 do i = 1, n do j = 1, n logical :: equal equal = .true. do k = 1, n if (grid(i,k) /=...
dolphin
Please write the following solution using Kotlin: Given the `root` of a binary tree and an integer `targetSum`, return _all **root-to-leaf** paths where the sum of the node values in the path equals_ `targetSum`_. Each path should be returned as a list of the node **values**, not node references_. A **root-to-leaf** p...
dolphin
Please explain the reasoning behind the following solution and provide code in Elixir: 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, they can **remove** either the leftmost stone or the rightmost stone from the row and receive poi...
dolphin
Please focus on the efficiency of this problem and provide code in java: Given a string `s`, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order. **Example 1:** **Input:** s = "Let's take LeetCode contest" **Output:** "s'teL ekat edoCteeL tsetnoc" *...
dolphin
Please write the following solution using python: Given two string arrays `words1` and `words2`, return _the number of strings that appear **exactly once** in **each** of the two arrays._ **Example 1:** **Input:** words1 = \[ "leetcode ", "is ", "amazing ", "as ", "is "\], words2 = \[ "amazing ", "leetcode ", "is "\]...
dolphin
Please focus on the algorithm of this problem and provide code in Kotlin: You are given a **0-indexed** integer array `nums`. The **concatenation** of two numbers is the number formed by concatenating their numerals. * For example, the concatenation of `15`, `49` is `1549`. The **concatenation value** of `nums` is...
dolphin
Please explain the following problem in detail and provide code in Haskell: You are given two `m x n` binary matrices `grid1` and `grid2` containing only `0`'s (representing water) and `1`'s (representing land). An **island** is a group of `1`'s connected **4-directionally** (horizontal or vertical). Any cells outside ...
dolphin
Please focus on the efficiency of this problem and provide code in Kotlin: Given an integer array `nums` and an integer `k`, return `true` _if there are two **distinct indices**_ `i` _and_ `j` _in the array such that_ `nums[i] == nums[j]` _and_ `abs(i - j) <= k`. **Example 1:** **Input:** nums = \[1,2,3,1\], k = 3 **...
dolphin
Please focus on the efficiency of this problem and provide code in ANSI C: You are given a 2D integer array `ranges` and two integers `left` and `right`. Each `ranges[i] = [starti, endi]` represents an **inclusive** interval between `starti` and `endi`. Return `true` _if each integer in the inclusive range_ `[left, ri...
dolphin
port this code from Elixir to Scala: ```elixir defmodule Solution do def two_lists(matches) do loss_count = Map.new participants = MapSet.new Enum.each(matches, fn [winner, loser] -> Map.update!(loss_count, loser, 1, &(&1 + 1)) Enum.each([winner, loser], fn participant -> MapSet.put(p...
dolphin
Please write the following solution using Rust: Given a `rows x cols` binary `matrix` filled with `0`'s and `1`'s, find the largest rectangle containing only `1`'s and return _its area_. **Example 1:** **Input:** matrix = \[\[ "1 ", "0 ", "1 ", "0 ", "0 "\],\[ "1 ", "0 ", "1 ", "1 ", "1 "\],\[ "1 ", "1 ", "1 ", "1 ",...
dolphin
Please explain the reasoning behind the following solution and provide code in Elixir: Given an integer `n`, return _the **decimal value** of the binary string formed by concatenating the binary representations of_ `1` _to_ `n` _in order, **modulo**_ `109 + 7`. **Example 1:** **Input:** n = 1 **Output:** 1 **Explanat...
dolphin
Please explain the following problem in detail and provide code in ANSI C: Given an integer array `nums` sorted in non-decreasing order and an integer `k`, return `true` _if this array can be divided into one or more disjoint increasing subsequences of length at least_ `k`_, or_ `false` _otherwise_. **Example 1:** **...
dolphin
Please focus on the functionality of this problem and provide code in Scala: A **good meal** is a meal that contains **exactly two different food items** with a sum of deliciousness equal to a power of two. You can pick **any** two different foods to make a good meal. Given an array of integers `deliciousness` where ...
dolphin
translate this code from Kotlin to Fortran: ```kotlin fun minDeletionSize(strs: Array<String>): Int { var count = 0 for (i in strs[0].indices) { for (j in 0 until strs.size - 1) { if (strs[j][i] > strs[j+1][i]) { count++ break } } } ...
dolphin
convert this code to Lua: ``` def findLatestStep(int[] arr, int m) { int n = arr.length int[] binaryString = new int[n] int latestStep = -1 int groupStart = -1 for (int i = 0; i < n; i++) { binaryString[arr[i]-1] = 1 if (groupStart == -1 && countOnes(binaryString) == m) { ...
dolphin
Please write the following solution using Rust: Given the integers `zero`, `one`, `low`, and `high`, we can construct a string by starting with an empty string, and then at each step perform either of the following: * Append the character `'0'` `zero` times. * Append the character `'1'` `one` times. This can be p...
dolphin
Please write the following solution using javascript: Given two arrays `arr1` and `arr2`, the elements of `arr2` are distinct, and all elements in `arr2` are also in `arr1`. Sort the elements of `arr1` such that the relative ordering of items in `arr1` are the same as in `arr2`. Elements that do not appear in `arr2` s...
dolphin
Please focus on the efficiency of this problem and provide code in Clojure: Given a string `expression` representing arbitrarily nested ternary expressions, evaluate the expression, and return _the result of it_. You can always assume that the given expression is valid and only contains digits, `'?'`, `':'`, `'T'`, an...
dolphin
convert this code from Perl to Visual Basic .NET: ````perl sub find_disappeared_numbers { my ($nums) = @_; my @result; foreach my $num (@$nums) { my $index = abs($num) - 1; $nums->[$index] = -abs($nums->[$index]); } foreach my $i (0 .. @$nums-1) { push @result, $i+1 if $num...
dolphin
translate this code from Scheme to Groovy: ```scheme (define (add-rooms idx children memo) (cond ((null? (car (cdr (assoc idx children)))) 1) ((not (eq? -1 (car (cdr (assoc idx memo))))) (car (cdr (assoc idx memo)))) (else (let* ((res 1) (cnt 0) (child...
dolphin
Please explain the reasoning behind the following solution and provide code in Visual Basic .NET: Given a set of **distinct** positive integers `nums`, return the largest subset `answer` such that every pair `(answer[i], answer[j])` of elements in this subset satisfies: * `answer[i] % answer[j] == 0`, or * `answer...
dolphin
Please explain the reasoning behind the following solution and provide code in Perl: You are given a list of strings of the **same length** `words` and a string `target`. Your task is to form `target` using the given `words` under the following rules: * `target` should be formed from left to right. * To form the ...
dolphin
port this code from Lua to Scheme: ```lua function to_hex(num) if num == 0 then return '0' end local hex_str = '' local hex_digits = '0123456789abcdef' local n = num & 0xffffffff while n ~= 0 do hex_str = hex_digits:sub(n & 0xf + 1, n & 0xf + 1) .. hex_str n = n >> 4 ...
dolphin
port this code from Elixir to Haskell: ```elixir defmodule Solution do def spellchecker(wordlist, queries) do word_map = %{word => word || _ -> word} word_map_lower_case = Enum.reduce(wordlist, %{}, fn word, map -> case Map.has_key?(map, String.downcase(word)) do true -> map false -> Map...
dolphin
translate this code to Go: ```groovy import java.util.ArrayDeque def minSwaps(nums1, nums2) { def n = nums1.size() def swaps = 0 for (int i = 1; i < n; i++) { if (nums1[i] <= nums1[i-1] || nums2[i] <= nums2[i-1]) { if (nums1[i] > nums2[i-1] && nums2[i] > nums1[i-1]) { de...
dolphin
convert this code to c++: ```ruby def max_size_slices(slices) def max_sum(slices, start, end_, n, memo) return 0 if n == 0 return -Float::INFINITY if end_ - start + 1 < n * 2 return memo[start][n] if memo[start][n] != -1 pick = max_sum(slices, start + 2, end_, n - 1, memo) + slices[...
dolphin
Please explain the reasoning behind the following solution and provide code in Dart: We are playing the Guessing Game. The game will work as follows: 1. I pick a number between `1` and `n`. 2. You guess a number. 3. If you guess the right number, **you win the game**. 4. If you guess the wrong number, then I will ...
dolphin
port this code from Object Pascal to C#: ``` function solve(nums1: array of integer; nums2: array of integer; queries: array of array of integer): array of integer; var res: array of integer; n, i, j, l, r, p: integer; begin n := length(nums1); setlength(res, 0); for j := 0 to length(queries) - 1 do begin ...
dolphin
convert this code to Groovy: ```rust fn large_groups(s: String) -> Vec<[usize; 2]> { let n = s.len(); let mut result = Vec::new(); let mut start = 0; for i in 1..n { if s.chars().nth(i).unwrap() != s.chars().nth(i-1).unwrap() { if i-1 - start >= 2 { result.push([start...
dolphin
Please write the following solution using C#: Given a string `s` consisting of lowercase English letters, return _the first letter to appear **twice**_. **Note**: * A letter `a` appears twice before another letter `b` if the **second** occurrence of `a` is before the **second** occurrence of `b`. * `s` will conta...
dolphin
translate this code from F# to Lua: ```fsharp let shortestPalindrome (s: string) : string = let n = s.Length let rev_s = new string(Array.rev (s.ToCharArray())) for i in 0 .. n-1 do if s.Substring(0, n-i) = rev_s.Substring(i) then return rev_s.Substring(0,i) + s return ...
dolphin
Please write the following solution using Rust: 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 that the cell is empty. Th...
dolphin
port this code from Swift to java: ```swift class TreeNode { var val: Int var left: TreeNode? var right: TreeNode? init(_ val: Int) { self.val = val } } func delNodes(_ root: TreeNode?, _ to_delete: [Int]) -> [TreeNode?] { var forest = [TreeNode?]() let to_delete_set = Set(to_d...
dolphin
Please explain the following problem in detail and provide code in Groovy: You are given an `m x n` grid `grid` of values `0`, `1`, or `2`, where: * each `0` marks **an empty land** that you can pass by freely, * each `1` marks **a building** that you cannot pass through, and * each `2` marks **an obstacle** tha...
dolphin
port this code to PHP: ```cpp #include <string> std::string toHexspeak(std::string num) { long n = std::stol(num); std::string hex = ""; while (n) { int rem = n % 16; if (rem == 1) hex = "I" + hex; else if (rem == 0) hex = "O" + hex; else if (rem > 9) hex = (char)(rem - 10 +...
dolphin
Please explain the following problem in detail and provide code in Fortran: Given a string `s`, return `true` _if a permutation of the string could form a_ _**palindrome**_ _and_ `false` _otherwise_. **Example 1:** **Input:** s = "code " **Output:** false **Example 2:** **Input:** s = "aab " **Output:** true **E...
dolphin
convert this code from Go to Dart: ```go func sortColors(nums []int) { red, white, blue := 0, 0, len(nums)-1 for white <= blue { if nums[white] == 0 { nums[red], nums[white] = nums[white], nums[red] red++ white++ } else if nums[white] == 1 { white+...
dolphin
Please focus on the efficiency of this problem and provide code in Scheme: You are given a string `num` representing a large integer. An integer is **good** if it meets the following conditions: * It is a **substring** of `num` with length `3`. * It consists of only one unique digit. Return _the **maximum good** ...
dolphin
Please write the following solution using javascript: Given an integer array `nums` and two integers `firstLen` and `secondLen`, return _the maximum sum of elements in two non-overlapping **subarrays** with lengths_ `firstLen` _and_ `secondLen`. The array with length `firstLen` could occur before or after the array wi...
dolphin
Please write the following solution using Fortran: You are given a 2D integer array `trees` where `trees[i] = [xi, yi]` represents the location of the `ith` tree in the garden. You are asked to fence the entire garden using the minimum length of rope possible. The garden is well-fenced only if **all the trees are encl...
dolphin
Please explain the reasoning behind the following solution and provide code in Lua: Given a string `s` that contains parentheses and letters, remove the minimum number of invalid parentheses to make the input string valid. Return _a list of **unique strings** that are valid with the minimum number of removals_. You ma...
dolphin
Please explain the following problem in detail and provide code in Fortran: You are given a binary string `binary`. A **subsequence** of `binary` is considered **good** if it is **not empty** and has **no leading zeros** (with the exception of `"0 "`). Find the number of **unique good subsequences** of `binary`. * ...
dolphin
port this code to Swift: ```cpp int minDifference(vector<int>& nums, int k) { if(nums.size() <= 1) return 0; sort(nums.begin(), nums.end()); int min_diff = nums.back() - nums.front(); for(int i=1; i<nums.size(); i++) { int high = max(nums[i-1] + k, nums.back() - k); int low = min(nums[i]...
dolphin
Please explain the following problem in detail and provide code in Groovy: You are given an array `trees` where `trees[i] = [xi, yi]` represents the location of a tree in the garden. Fence the entire garden using the minimum length of rope, as it is expensive. The garden is well-fenced only if **all the trees are encl...
dolphin
convert this code to Objective-C: ```python class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def tree2str(t): if not t: return "" if not t.left and not t.right: return str(t.val) if not t.right: return "{}({})".format...
dolphin
Please explain the reasoning behind the following solution and provide code in Clojure: 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`...
dolphin
Please write the following solution using Scala: In the world of Dota2, there are two parties: the Radiant and the Dire. The Dota2 senate consists of senators coming from two parties. Now the Senate wants to decide on a change in the Dota2 game. The voting for this change is a round-based procedure. In each round, eac...
dolphin
Please write the following solution using java: Given a string `s`, determine if it is **valid**. A string `s` is **valid** if, starting with an empty string `t = " "`, you can **transform** `t` **into** `s` after performing the following operation **any number of times**: * Insert string `"abc "` into any position...
dolphin
Please write the following solution using Haskell: `n` passengers board an airplane with exactly `n` seats. The first passenger has lost the ticket and picks a seat randomly. But after that, the rest of the passengers will: * Take their own seat if it is still available, and * Pick other seats randomly when they f...
dolphin
Please explain the following problem in detail and provide code in Perl: 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 n...
dolphin
Please explain the following problem in detail and provide code in TypeScript: Given the `root` of a binary tree, imagine yourself standing on the **right side** of it, return _the values of the nodes you can see ordered from top to bottom_. **Example 1:** **Input:** root = \[1,2,3,null,5,null,4\] **Output:** \[1,3,4...
dolphin
convert this code to Swift: ```ruby def reverse(num) num_str = num.to_s reversed1 = num_str.reverse.to_i reversed2_str = reversed1.to_s reversed2 = reversed2_str.reverse.to_i return reversed2 == num end ```
dolphin
Please explain the following problem in detail and provide code in R: A **k-mirror number** is a **positive** integer **without leading zeros** that reads the same both forward and backward in base-10 **as well as** in base-k. * For example, `9` is a 2-mirror number. The representation of `9` in base-10 and base-2 a...
dolphin
Please focus on the algorithm of this problem and provide code in Rust: 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 to ...
dolphin
Please write the following solution using Groovy: The **product difference** between two pairs `(a, b)` and `(c, d)` is defined as `(a * b) - (c * d)`. * For example, the product difference between `(5, 6)` and `(2, 7)` is `(5 * 6) - (2 * 7) = 16`. Given an integer array `nums`, choose four **distinct** indices `w`...
dolphin
Please write the following solution using Kotlin: Given a binary string `s`, return _the number of substrings with all characters_ `1`_'s_. Since the answer may be too large, return it modulo `109 + 7`. **Example 1:** **Input:** s = "0110111 " **Output:** 9 **Explanation:** There are 9 substring in total with only 1...
dolphin
Please explain the following problem in detail and provide code in javascript: You are given two **non-empty** linked lists representing two non-negative integers. The digits are stored in **reverse order**, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. You m...
dolphin
Please focus on the functionality of this problem and provide code in TypeScript: There are `n` kids with candies. You are given an integer array `candies`, where each `candies[i]` represents the number of candies the `ith` kid has, and an integer `extraCandies`, denoting the number of extra candies that you have. Ret...
dolphin
Please explain the reasoning behind the following solution and provide code in PHP: An experiment is being conducted in a lab. To ensure accuracy, there are **two** sensors collecting data simultaneously. You are given two arrays `sensor1` and `sensor2`, where `sensor1[i]` and `sensor2[i]` are the `ith` data points col...
dolphin
Please explain the reasoning behind the following solution and provide code in Julia: Given a string `s`, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. **Example 1:** **Input:** s = "abab " **Output:** true **Explanation:** It is the substring "a...
dolphin
Please explain the following problem in detail and provide code in Lisp: You are given an integer array `nums` and an integer `k`. You can partition the array into **at most** `k` non-empty adjacent subarrays. The **score** of a partition is the sum of the averages of each subarray. Note that the partition must use ev...
dolphin
Please explain the following problem in detail and provide code in Object Pascal: There is a ball in a `maze` with empty spaces (represented as `0`) and walls (represented as `1`). The ball can go through the empty spaces by rolling **up, down, left or right**, but it won't stop rolling until hitting a wall. When the b...
dolphin
convert this code from TypeScript to Scheme: ```typescript function nthUglyNumber(n: number, a: number, b: number, c: number): number { let left: number = 1; let right: number = 2 * 10 ** 9; const lcm_ab: number = (a * b) / gcd(a, b); const lcm_ac: number = (a * c) / gcd(a, c); const lcm_bc: number ...
dolphin
translate this code from Go to Groovy: ```go func formatTime(hour int, minute int) string { return fmt.Sprintf("%02d:%02d", hour, minute) } func Latest24hrTime(arr []int) string { permutations := make([][]int, 0) var perm func([]int, int) perm = func(a []int, k int) { if k == len(a) { ...
dolphin
convert this code from Clojure to Scala: ```clojure (defn max-consecutive-robots [charge-times running-costs budget] (let [n (count charge-times)] (loop [i 0 max-robots 0] (if (< i n) (loop [j i max-charge 0 running-sum 0] (if (< j n) (let [max-charge (max max-charge (nth charg...
dolphin
Please explain the following problem in detail and provide code in Dart: You are given the string `croakOfFrogs`, which represents a combination of the string `"croak "` from different frogs, that is, multiple frogs can croak at the same time, so multiple `"croak "` are mixed. _Return the minimum number of_ different ...
dolphin
Please explain the reasoning behind the following solution and provide code in ANSI C: A train line going through a city has two routes, the regular route and the express route. Both routes go through the **same** `n + 1` stops labeled from `0` to `n`. Initially, you start on the regular route at stop `0`. You are giv...
dolphin
port this code from Rust to Haskell: ```rust fn largest_number(cost: Vec<i32>, target: i32) -> String { let target = target as usize; let mut dp = vec!["".to_string(); target + 1]; dp[0] = "".to_string(); for i in 0..9 { for j in cost[i] as usize..=target { if dp[j - cost[i] as usiz...
dolphin
port this code to R: ```pascal function maxSatisfied(customers: array of integer; grumpy: array of integer; minutes: integer): integer; var total_customers, max_extra_customers, extra_customers, i: integer; begin total_customers := 0; max_extra_customers := 0; extra_customers := 0; for i := 0 to Length(custom...
dolphin
translate this code to Perl: ```scala def maxGoodInteger(num: String): String = { var maxGood = "" for (i <- 0 until num.length - 2) { if (num(i) == num(i+1) && num(i+1) == num(i+2)) { if (num(i).toString.toInt > maxGood.toString.toInt) { maxGood = num.substring(i, i+3) ...
dolphin
Please focus on the efficiency of this problem and provide code in Perl: Given a string `s` consisting only of characters _a_, _b_ and _c_. Return the number of substrings containing **at least** one occurrence of all these characters _a_, _b_ and _c_. **Example 1:** **Input:** s = "abcabc " **Output:** 10 **Explan...
dolphin
Please explain the reasoning behind the following solution and provide code in Lua: Given an array of integers, return the maximum sum for a **non-empty** subarray (contiguous elements) with at most one element deletion. In other words, you want to choose a subarray and optionally delete one element from it so that the...
dolphin
Please focus on the efficiency of this problem and provide code in Rust: We run a preorder depth-first search (DFS) on the `root` of a binary tree. At each node in this traversal, we output `D` dashes (where `D` is the depth of this node), then we output the value of this node. If the depth of a node is `D`, the depth...
dolphin
Please write the following solution using Fortran: Given a binary array `nums`, return _the maximum length of a contiguous subarray with an equal number of_ `0` _and_ `1`. **Example 1:** **Input:** nums = \[0,1\] **Output:** 2 **Explanation:** \[0, 1\] is the longest contiguous subarray with an equal number of 0 and ...
dolphin
convert this code to Groovy: ```csharp public int NumOfWays(int[] nums, int k) { int left = 0; int right = 0; foreach (int num in nums) { if (num < k) { left++; } if (num <= k) { right++; } } if (left == nums.Length) { return 0; } ...
dolphin
translate this code to Dart: ```R minJumps <- function(arr) { n <- length(arr) if (n <= 1) { return(0) } value_indices <- list() for (i in 1:n) { if (!(arr[i] %in% names(value_indices))) { value_indices[[as.character(arr[i])]] <- list(i) } else { value_indices[[as.character(arr[i...
dolphin
port this code from javascript to Julia: ```javascript function findUnsortedSubarray(nums) { const sortedNums = [...nums].sort((a, b) => a - b); let start = 0, end = nums.length - 1; while (start < nums.length && nums[start] === sortedNums[start]) start++; while (end > start && nums[end] === sortedNums[...
dolphin
convert this code to Swift: ```clojure (defn num-ways [s] (let [number-of-ones (count (filter #(= % \1) s)) target (quot number-of-ones 3)] (if (not= 0 (mod number-of-ones 3)) 0 (if (= 0 target) (let [n (count s)] (mod (* (- n 1) (- n 2)) 1000000007)) (let [ones-so-fa...
dolphin
Please write the following solution using Clojure: Given the `root` of a binary tree, return _the number of **uni-value**_ _subtrees_. A **uni-value subtree** means all nodes of the subtree have the same value. **Example 1:** **Input:** root = \[5,1,5,5,5,null,5\] **Output:** 4 **Example 2:** **Input:** root = \[\...
dolphin