instruction_seed
stringlengths
29
40.5k
source
stringclasses
6 values
Please focus on the efficiency of this problem and provide code in Haskell: Given a positive integer `n`, there exists a **0-indexed** array called `powers`, composed of the **minimum** number of powers of `2` that sum to `n`. The array is sorted in **non-decreasing** order, and there is **only one** way to form the ar...
dolphin
translate this code from Perl to Groovy: ```perl sub longestWellPerformingInterval { my ($hours) = @_; my $sum = 0; my $longest = 0; my %first_sum_index; for my $i (0..scalar(@$hours)-1) { my $hour = $hours->[$i]; $sum += $hour > 8 ? 1 : -1; if ($sum > 0) { $long...
dolphin
Please explain the reasoning behind the following solution and provide code in Rust: Given a string `s` containing only lowercase English letters and the `'?'` character, convert **all** the `'?'` characters into lowercase letters such that the final string does not contain any **consecutive repeating** characters. You...
dolphin
Please explain the following problem in detail and provide code in Erlang: You are given a **0-indexed** integer array `nums`. The **effective value** of three indices `i`, `j`, and `k` is defined as `((nums[i] | nums[j]) & nums[k])`. The **xor-beauty** of the array is the XORing of **the effective values of all the ...
dolphin
port this code to PHP: ```swift class TreeNode { var val: Int var left: TreeNode? var right: TreeNode? init(_ val: Int) { self.val = val self.left = nil self.right = nil } } func deleteNode(_ root: TreeNode?, _ key: Int) -> TreeNode? { guard let root = root else { ...
dolphin
Please explain the reasoning behind the following solution and provide code in python: Given `n` orders, each order consist in pickup and delivery services. Count all valid pickup/delivery possible sequences such that delivery(i) is always after of pickup(i). Since the answer may be too large, return it modulo 10^9 +...
dolphin
convert this code from Lisp to Kotlin: ```lisp (defun find-destination-city (paths) (let ((sources (make-hash-table)) (destinations (make-hash-table))) (dolist (path paths) (setf (gethash (first path) sources) t) (setf (gethash (second path) destinations) t)) (car (set-difference (hash-tab...
dolphin
translate this code from java to Scheme: ```java import java.util.*; class Solution { public int minFuel(int[][] roads, int seats) { int n = roads.length + 1; List<List<Integer>> graph = new ArrayList<>(n); for (int i = 0; i < n; i++) { graph.add(new ArrayList<>()); } ...
dolphin
port this code to F#: ```groovy def pathSumHelper(node, targetSum, currentSum) { if (node == null) { return 0 } currentSum += node.val def totalPaths = currentSum == targetSum ? 1 : 0 totalPaths += pathSumHelper(node.left, targetSum, currentSum) totalPaths += pathSumHelper(node.right, ta...
dolphin
Please explain the reasoning behind the following solution and provide code in Fortran: There is a knight on an `n x n` chessboard. In a valid configuration, the knight starts **at the top-left cell** of the board and visits every cell on the board **exactly once**. You are given an `n x n` integer matrix `grid` consi...
dolphin
Please write the following solution using Elixir: Given two integer arrays `inorder` and `postorder` where `inorder` is the inorder traversal of a binary tree and `postorder` is the postorder traversal of the same tree, construct and return _the binary tree_. **Example 1:** **Input:** inorder = \[9,3,15,20,7\], posto...
dolphin
Please write the following solution using Julia: You are given an integer `num.` **Rearrange** the digits of `num` such that its value is **minimized** and it does not contain **any** leading zeros. Return _the rearranged number with minimal value_. Note that the sign of the number does not change after rearranging t...
dolphin
port this code to Groovy: ```clojure (defn exclusive-time [n logs] (let [stack [] res (vec (repeat n 0)) prev-time 0] (doseq [log logs] (let [[id type time] (clojure.string/split log #":")] (if (= type "start") (do (when (seq stack) (let [top (peek...
dolphin
Please explain the reasoning behind the following solution and provide code in C#: You are given an integer array `nums` and an integer `k`. Append `k` **unique positive** integers that do **not** appear in `nums` to `nums` such that the resulting total sum is **minimum**. Return _the sum of the_ `k` _integers appende...
dolphin
Please explain the reasoning behind the following solution and provide code in Scheme: You have `n` `tiles`, where each tile has one letter `tiles[i]` printed on it. Return _the number of possible non-empty sequences of letters_ you can make using the letters printed on those `tiles`. **Example 1:** **Input:** tiles...
dolphin
convert this code to Kotlin: ```javascript function minNonExpressibleInteger(nums) { let result = 1; nums.sort((a, b) => a - b); for (const num of nums) { if (num > result) break; result += num; } return result; } ```
dolphin
Please write the following solution using Rust: Given two integers `num1` and `num2`, return _the **sum** of the two integers_. **Example 1:** **Input:** num1 = 12, num2 = 5 **Output:** 17 **Explanation:** num1 is 12, num2 is 5, and their sum is 12 + 5 = 17, so 17 is returned. **Example 2:** **Input:** num1 = -10, ...
dolphin
convert this code from Clojure to C#: ```clojure (defn max-number [nums1 nums2 k] (let [max-array (fn [nums k] (loop [ans [] nums nums i 0] (when (seq nums) (let [n (first nums) ...
dolphin
port this code from c++ to TypeScript: ```cpp std::string addStrings(std::string num1, std::string num2) { int i = num1.size() - 1, j = num2.size() - 1, carry = 0; std::string result; while (i >= 0 || j >= 0 || carry) { int sum = carry; if (i >= 0) { sum += num1[i] - '0'; ...
dolphin
Please write the following solution using Scheme: There are `n` rings and each ring is either red, green, or blue. The rings are distributed **across ten rods** labeled from `0` to `9`. You are given a string `rings` of length `2n` that describes the `n` rings that are placed onto the rods. Every two characters in `ri...
dolphin
Please explain the following problem in detail and provide code in Haskell: 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. The **area** of an isla...
dolphin
port this code from c++ to java: ```cpp #include <map> class MyCalendarThree { public: std::map<int, int> timeline; int book(int start, int end) { timeline[start]++; timeline[end]--; int ongoing = 0, k = 0; for (auto& t : timeline) { k = std::max(k, ongoing += t.sec...
dolphin
Please write the following solution using java: You are given a **0-indexed** positive integer array `nums` and a positive integer `k`. A pair of numbers `(num1, num2)` is called **excellent** if the following conditions are satisfied: * **Both** the numbers `num1` and `num2` exist in the array `nums`. * The sum ...
dolphin
Please explain the reasoning behind the following solution and provide code in Fortran: Given a data stream input of non-negative integers `a1, a2, ..., an`, summarize the numbers seen so far as a list of disjoint intervals. Implement the `SummaryRanges` class: * `SummaryRanges()` Initializes the object with an emp...
dolphin
Please write the following solution using Objective-C: Your task is to calculate `ab` mod `1337` where `a` is a positive integer and `b` is an extremely large positive integer given in the form of an array. **Example 1:** **Input:** a = 2, b = \[3\] **Output:** 8 **Example 2:** **Input:** a = 2, b = \[1,0\] **Outpu...
dolphin
Please focus on the functionality of this problem and provide code in Haskell: Return the number of permutations of 1 to `n` so that prime numbers are at prime indices (1-indexed.) _(Recall that an integer is prime if and only if it is greater than 1, and cannot be written as a product of two positive integers both sm...
dolphin
Please explain the following problem in detail and provide code in Scala: Given a binary tree where each path going from the root to any leaf form a **valid sequence**, check if a given string is a **valid sequence** in such binary tree. We get the given string from the concatenation of an array of integers `arr` and ...
dolphin
Please focus on the algorithm of this problem and provide code in Erlang: You are given an integer `n`. There are `n` rooms numbered from `0` to `n - 1`. You are given a 2D integer array `meetings` where `meetings[i] = [starti, endi]` means that a meeting will be held during the **half-closed** time interval `[starti,...
dolphin
Please explain the reasoning behind the following solution and provide code in Elixir: You are given an `m x n` binary matrix `mat` of `1`'s (representing soldiers) and `0`'s (representing civilians). The soldiers are positioned **in front** of the civilians. That is, all the `1`'s will appear to the **left** of all th...
dolphin
Please explain the following problem in detail and provide code in Perl: You are given an integer array `nums` and an integer `k`. You want to find a **subsequence** of `nums` of length `k` that has the **largest** sum. Return _**any** such subsequence as an integer array of length_ `k`. A **subsequence** is an array...
dolphin
port this code from Perl to Fortran: ```perl sub longestSubsequence { my ($arr, $difference) = @_; my %dp; my $maxLength = 0; foreach my $num (@$arr) { $dp{$num} = $dp{$num - $difference} // 0 + 1; $maxLength = $dp{$num} if $dp{$num} > $maxLength; } return $maxLength; } ```
dolphin
Please explain the following problem in detail and provide code in Kotlin: Given the array `nums`, obtain a subsequence of the array whose sum of elements is **strictly greater** than the sum of the non included elements in such subsequence. If there are multiple solutions, return the subsequence with **minimum size**...
dolphin
convert this code from Swift to Rust: ```swift class SORTracker { var locations: [(String, Int)] = [] var queries = 0 func add(_ name: String, _ score: Int) { let location = (name, score) var insertIndex = 0 while insertIndex < locations.count && (locations[insertIndex].1 > scor...
dolphin
Please explain the reasoning behind the following solution and provide code in Fortran: Given an integer array `nums` sorted in **non-decreasing order**, remove some duplicates [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm) such that each unique element appears **at most twice**. The **relative order*...
dolphin
port this code to Perl: ```objective-c #import <Foundation/Foundation.h> void dfs(NSArray<NSArray<NSNumber *> *> *tree, NSMutableSet<NSNumber *> *restricted, NSNumber *node, NSNumber *parent, NSUInteger depth, NSUInteger *maxNodes) { if ([restricted containsObject:node]) { return; } *maxNodes = MAX...
dolphin
Please focus on the algorithm of this problem and provide code in c++: A parentheses string is valid if and only if: * It is the empty string, * It can be written as `AB` (`A` concatenated with `B`), where `A` and `B` are valid strings, or * It can be written as `(A)`, where `A` is a valid string. You are given...
dolphin
Please focus on the algorithm of this problem and provide code in ANSI C: Given the `root` of a binary tree and an integer `limit`, delete all **insufficient nodes** in the tree simultaneously, and return _the root of the resulting binary tree_. A node is **insufficient** if every root to **leaf** path intersecting th...
dolphin
Please explain the following problem in detail and provide code in Elixir: Given an integer `n` and an integer array `rounds`. We have a circular track which consists of `n` sectors labeled from `1` to `n`. A marathon will be held on this track, the marathon consists of `m` rounds. The `ith` round starts at sector `rou...
dolphin
Please write the following solution using Clojure: 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 color, so she asks B...
dolphin
translate this code from Groovy to Go: ```groovy def maxSum(numOnes, numZeros, numNegOnes, k) { def max_sum = 0 (0..k).each { i -> def ones = Math.min(i, numOnes) def neg_ones = Math.min(k - i, numNegOnes) max_sum = Math.max(max_sum, ones - neg_ones) } return max_sum } ```
dolphin
convert this code from R to PHP: ```R minOperations <- function(nums, start, goal) { seen <- set(start) q <- queue() enqueue(q, start) level <- 0 while (length(q) > 0) { size <- length(q) for (i in 1:size) { x <- dequeue(q) if (x == goal) { return(level) } for (num i...
dolphin
Please explain the reasoning behind the following solution and provide code in F#: A **transformation sequence** from word `beginWord` to word `endWord` using a dictionary `wordList` is a sequence of words `beginWord -> s1 -> s2 -> ... -> sk` such that: * Every adjacent pair of words differs by a single letter. * ...
dolphin
Please explain the following problem in detail and provide code in Fortran: There are `n` students in a class numbered from `0` to `n - 1`. The teacher will give each student a problem starting with the student number `0`, then the student number `1`, and so on until the teacher reaches the student number `n - 1`. Afte...
dolphin
convert this code to Lua: ```csharp public static string FindSmallestNum(string pattern) { string num = "123456789"; int i = 0; while (i < pattern.Length) { if (pattern[i] == 'D') { int j = i; while (j < pattern.Length && pattern[j] == 'D') { ...
dolphin
Please write the following solution using Objective-C: Given the array `orders`, which represents the orders that customers have done in a restaurant. More specifically `orders[i]=[customerNamei,tableNumberi,foodItemi]` where `customerNamei` is the name of the customer, `tableNumberi` is the table customer sit at, and ...
dolphin
Please explain the reasoning behind the following solution and provide code in Lua: You are given an array `arr` which consists of only zeros and ones, divide the array into **three non-empty parts** such that all of these parts represent the same binary value. If it is possible, return any `[i, j]` with `i + 1 < j`, ...
dolphin
convert this code to Erlang: ```php function flipAndInvertImage($image) { $n = count($image); for ($i = 0; $i < $n; $i++) { $image[$i] = array_reverse($image[$i]); for ($j = 0; $j < $n; $j++) { $image[$i][$j] = 1 - $image[$i][$j]; } } return $image; } ```
dolphin
convert this code from Mojo to C#: ``` use Heap::Binary; sub get_minimum_cost(Int $maxTime, Array[Int] @edges, Array[Int] @passingFees) returns Int { my $n = @passingFees.elems; my %G = (); for @edges -> [$x, $y, $time] { %G.push($x => []) unless %G{$x}; %G.push($y => []) unless %G{$y}; ...
dolphin
translate this code from F# to Objective-C: ```f# let divide(dividend: int, divisor: int) : int = if dividend = -pown(2, 31) && divisor = -1 then pown(2, 31) - 1 else let sign = if (dividend > 0) <> (divisor > 0) then -1 else 1 let mutable dvd = abs(dividend) let mutable dvs = ab...
dolphin
Please focus on the algorithm of this problem and provide code in Fortran: Given an integer `x`, return `true` _if_ `x` _is a_ _**palindrome**__, and_ `false` _otherwise_. **Example 1:** **Input:** x = 121 **Output:** true **Explanation:** 121 reads as 121 from left to right and from right to left. **Example 2:** *...
dolphin
Please explain the reasoning behind the following solution and provide code in R: There are `n` employees, each with a unique id from `0` to `n - 1`. You are given a 2D integer array `logs` where `logs[i] = [idi, leaveTimei]` where: * `idi` is the id of the employee that worked on the `ith` task, and * `leaveTime...
dolphin
Please explain the reasoning behind the following solution and provide code in Rust: You are given an integer array `coins` (**1-indexed**) of length `n` and an integer `maxJump`. You can jump to any index `i` of the array `coins` if `coins[i] != -1` and you have to pay `coins[i]` when you visit index `i`. In addition ...
dolphin
Please write the following solution using Rust: Given an integer array `nums`, find a subarray that has the largest product, and return _the product_. The test cases are generated so that the answer will fit in a **32-bit** integer. **Example 1:** **Input:** nums = \[2,3,-2,4\] **Output:** 6 **Explanation:** \[2,3\]...
dolphin
translate this code to Objective-C: ```mojo sub maximum_requests(n: int, requests: List[List[int]]) -> int { var req_size = len(requests) var max_requests = 0 for i in 0..(1 << req_size) { var net_transfers = [0] * n var count = 0 for j in 0..req_size { if i & (1 << j) ...
dolphin
port this code to c++: ```php function countMatches($items, $ruleKey, $ruleValue) { $count = 0; $index = ["type" => 0, "color" => 1, "name" => 2][$ruleKey]; foreach ($items as $item) { if ($item[$index] == $ruleValue) { $count++; } } return $count; } ```
dolphin
Please focus on the algorithm of this problem and provide code in Go: You have a data structure of employee information, including the employee's unique ID, importance value, and direct subordinates' IDs. You are given an array of employees `employees` where: * `employees[i].id` is the ID of the `ith` employee. * ...
dolphin
port this code from Mojo to java: ```mojo sub find_duplicate(@paths) { my %content_map; for my $path (@paths) { my ($directory, @files) = split ' ', $path; for my $file (@files) { my ($name, $content) = $file =~ /(.+)\((.+)\)/; my $file_path = "$directory/$name"; ...
dolphin
translate this code from Kotlin to java: ```kotlin fun busiestServers(k: Int, arrival: IntArray, load: IntArray): List<Int> { val serverStatus = IntArray(k) { -1 } val serverRequestCount = IntArray(k) for (i in arrival.indices) { var index = i % k repeat(k) { if (serverStatus[in...
dolphin
Please explain the following problem in detail and provide code in Perl: Given an integer array `nums` and an integer `k`, return _the number of **good subarrays** of_ `nums`. A **good array** is an array where the number of different integers in that array is exactly `k`. * For example, `[1,2,3,1,2]` has `3` diffe...
dolphin
Please explain the following problem in detail and provide code in javascript: Given the `head` of a singly linked list and two integers `left` and `right` where `left <= right`, reverse the nodes of the list from position `left` to position `right`, and return _the reversed list_. **Example 1:** **Input:** head = \[...
dolphin
port this code to TypeScript: ```scheme (define (sequential-digits low high) (define (iter i) (cond ((> i 9) '()) (else (let loop ((j (+ i 1)) (num i) (res '())) (cond ((> j 9) res) ((and (>= num low) (<= num high)) (loop (+ j 1) (+ (* n...
dolphin
Please write the following solution using Lisp: There is an integer array `perm` that is a permutation of the first `n` positive integers, where `n` is always **odd**. It was encoded into another integer array `encoded` of length `n - 1`, such that `encoded[i] = perm[i] XOR perm[i + 1]`. For example, if `perm = [1,3,2...
dolphin
translate this code from Elixir to Fortran: ```elixir def min_pair_sum(nums) do nums = Enum.sort(nums) max_sum = 0 for i <- 0..(length(nums) - 1) div 2 do pair_sum = Enum.at(nums,i) + Enum.at(Enum.reverse(nums),i) max_sum = max(max_sum, pair_sum) end max_sum end ```
dolphin
Please explain the following problem in detail and provide code in Kotlin: Assume the following rules are for the tic-tac-toe game on an `n x n` board between two players: 1. A move is guaranteed to be valid and is placed on an empty block. 2. Once a winning condition is reached, no more moves are allowed. 3. A pla...
dolphin
translate this code from Lua to Kotlin: ```lua function maximumUnits(boxTypes, truckSize) table.sort(boxTypes, function(a,b) return a[2] > b[2] end) local totalUnits = 0 for _, box in ipairs(boxTypes) do local boxCount = math.min(truckSize, box[1]) totalUnits = totalUnits + boxCount * b...
dolphin
port this code from Objective-C to Mojo: ```objective-c -(int)smallestNumberWithAtLeastOneDigitFromEachArray:(NSArray*)nums1 nums2:(NSArray*)nums2 { int min1 = [nums1[0] intValue]; int min2 = [nums2[0] intValue]; for (NSNumber *num1 in nums1) { for (NSNumber *num2 in nums2) { if ([num1 i...
dolphin
Please explain the following problem in detail and provide code in R: You are given an array of integers `nums`. You are also given an integer `original` which is the first number that needs to be searched for in `nums`. You then do the following steps: 1. If `original` is found in `nums`, **multiply** it by two (i....
dolphin
Please write the following solution using Scala: You are given a **0-indexed** `m x n` binary matrix `matrix` and an integer `numSelect`, which denotes the number of **distinct** columns you must select from `matrix`. Let us consider `s = {c1, c2, ...., cnumSelect}` as the set of columns selected by you. A row `row` i...
dolphin
convert this code from Haskell to java: ```haskell minOperations :: [Int] -> [Int] -> Int minOperations nums target = let n = length nums sum_nums = sum nums sum_target = sum target diff = (sum_target - sum_nums) `div` 2 cnt = foldl (\acc (i, num) -> if num > target !! i then acc + (num - targ...
dolphin
port this code from Lisp to Scala: ```lisp (defclass Solution () ((rects :accessor rects :initarg :rects) (areas :accessor areas :initarg :areas) (total-area :accessor total-area :initarg :total-area))) (defmethod initialize-instance :after ((solution Solution) &key) (with-slots (rects areas) solution (s...
dolphin
Please explain the reasoning behind the following solution and provide code in Fortran: Given two strings `s1` and `s2`, return _the lowest **ASCII** sum of deleted characters to make two strings equal_. **Example 1:** **Input:** s1 = "sea ", s2 = "eat " **Output:** 231 **Explanation:** Deleting "s " from "sea " ...
dolphin
Please explain the following problem in detail and provide code in Object Pascal: Given the `root` of a binary tree, return _its maximum depth_. A binary tree's **maximum depth** is the number of nodes along the longest path from the root node down to the farthest leaf node. **Example 1:** **Input:** root = \[3,9,20...
dolphin
Please focus on the algorithm of this problem and provide code in Perl: We call a positive integer **special** if all of its digits are **distinct**. Given a **positive** integer `n`, return _the number of special integers that belong to the interval_ `[1, n]`. **Example 1:** **Input:** n = 20 **Output:** 19 **Expla...
dolphin
Please explain the following problem in detail and provide code in Kotlin: A dieter consumes `calories[i]` calories on the `i`\-th day. Given an integer `k`, for **every** consecutive sequence of `k` days (`calories[i], calories[i+1], ..., calories[i+k-1]` for all `0 <= i <= n-k`), they look at _T_, the total calories...
dolphin
Please explain the reasoning behind the following solution and provide code in python: Given the `root` of a binary tree and a `leaf` node, reroot the tree so that the `leaf` is the new root. You can reroot the tree with the following steps for each node `cur` on the path **starting from the** `leaf` up to the `root`​...
dolphin
Please write the following solution using Haskell: You are given a **0-indexed** array `nums` comprising of `n` non-negative integers. In one operation, you must: * Choose an integer `i` such that `1 <= i < n` and `nums[i] > 0`. * Decrease `nums[i]` by 1. * Increase `nums[i - 1]` by 1. Return _the **minimum** ...
dolphin
Please explain the following problem in detail and provide code in Kotlin: Given an integer array `nums`, return _the number of elements that have **both** a strictly smaller and a strictly greater element appear in_ `nums`. **Example 1:** **Input:** nums = \[11,7,2,15\] **Output:** 2 **Explanation:** The element 7 h...
dolphin
Please write the following solution using Haskell: Given an input string `s` and a pattern `p`, implement regular expression matching with support for `'.'` and `'*'` where: * `'.'` Matches any single character.​​​​ * `'*'` Matches zero or more of the preceding element. The matching should cover the **entire** in...
dolphin
Please explain the reasoning behind the following solution and provide code in Kotlin: You are given a 0-indexed integer array `nums`. You are allowed to permute `nums` into a new array `perm` of your choosing. We define the **greatness** of `nums` be the number of indices `0 <= i < nums.length` for which `perm[i] > n...
dolphin
Please focus on the algorithm of this problem and provide code in Ruby: There is a one-dimensional garden on the x-axis. The garden starts at the point `0` and ends at the point `n`. (i.e The length of the garden is `n`). There are `n + 1` taps located at points `[0, 1, ..., n]` in the garden. Given an integer `n` an...
dolphin
Please write the following solution using Visual Basic .NET: Given a **0-indexed** integer array `nums`, find a **0-indexed** integer array `answer` where: * `answer.length == nums.length`. * `answer[i] = |leftSum[i] - rightSum[i]|`. Where: * `leftSum[i]` is the sum of elements to the left of the index `i` in ...
dolphin
Please focus on the algorithm of this problem and provide code in C#: Given an array of integers `arr`, you are initially positioned at the first index of the array. In one step you can jump from index `i` to index: * `i + 1` where: `i + 1 < arr.length`. * `i - 1` where: `i - 1 >= 0`. * `j` where: `arr[i] == ar...
dolphin
Please focus on the efficiency of this problem and provide code in TypeScript: 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` represe...
dolphin
Please explain the reasoning behind the following solution and provide code in PHP: Implement [pow(x, n)](http://www.cplusplus.com/reference/valarray/pow/), which calculates `x` raised to the power `n` (i.e., `xn`). **Example 1:** **Input:** x = 2.00000, n = 10 **Output:** 1024.00000 **Example 2:** **Input:** x = 2...
dolphin
Please explain the reasoning behind the following solution and provide code in Ruby: 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 Lisp to Erlang: ```lisp (defun find-strobogrammatic (n) (labels ((helper (n m) (cond ((= n 0) '("")) ((= n 1) '("0" "1" "8")) (t (let ((lst (helper (- n 2) m)) (res '())) (dolist (s lst res) ...
dolphin
port this code from java to javascript: ```java final int MOD = 1000000007; final int MAX = 1001; int ways(int startPos, int endPos, int k, int[][] dp) { if (k == 0) return startPos == endPos ? 1 : 0; if (startPos < 0 || endPos < 0 || startPos >= MAX || endPos >= MAX) return 0; if (dp[startPos][k] != ...
dolphin
Please explain the following problem in detail and provide code in java: 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...
dolphin
Please explain the reasoning behind the following solution and provide code in Visual Basic .NET: You are given a string `s`. A split is called **good** if you can split `s` into two non-empty strings `sleft` and `sright` where their concatenation is equal to `s` (i.e., `sleft + sright = s`) and the number of distinct...
dolphin
port this code from Kotlin to Elixir: ```kotlin fun diffWaysToCompute(input: String): List<Int> { val result = mutableListOf<Int>() for (i in input.indices) { val c = input[i] if (c in listOf('+', '-', '*')) { val left = diffWaysToCompute(input.substring(0, i)) val right ...
dolphin
translate this code to Object Pascal: ```julia function kSmallestPairs(nums1::Vector{Int}, nums2::Vector{Int}, k::Int)::Vector{Vector{Int}} if isempty(nums1) || isempty(nums2) return [] end heap = [(nums1[i] + nums2[1], i, 1) for i in 1:min(k, length(nums1))] heapify!(heap) result = [] ...
dolphin
Please explain the reasoning behind the following solution and provide code in Clojure: Given a `n * n` matrix `grid` of `0's` and `1's` only. We want to represent `grid` with a Quad-Tree. Return _the root of the Quad-Tree representing_ `grid`. A Quad-Tree is a tree data structure in which each internal node has exac...
dolphin
translate this code from R to Perl: ```R largestTimeFromDigits <- function(arr) { max_time <- -1 perms <- unique(permutations(arr)) for (perm in perms) { hour <- perm[1] * 10 + perm[2] minute <- perm[3] * 10 + perm[4] time <- hour * 60 + minute if (hour < 24 && minute < 60 && time > max_time) { ...
dolphin
convert this code from Erlang to C#: ```erlang construct_from_pre_post(Preorder, Postorder) -> build_tree(Preorder, Postorder, 1, length(Preorder), 1, length(Postorder)). build_tree(_, _, PreStart, PreEnd, PostStart, PostEnd) when PreStart > PreEnd -> nil; build_tree(_, _, PreStart, PreEnd, PostStart, PostEnd)...
dolphin
convert this code from Scala to Dart: ```scala def find132pattern(nums: Array[Int]): Boolean = { var third = Int.MinValue val stack = scala.collection.mutable.Stack[Int]() for (num <- nums.reverse) { if (num < third) { return true } while (stack.nonEmpty && stack.top < nu...
dolphin
port this code from Ruby to Scala: ```ruby class ListNode attr_accessor :val, :next def initialize(val = 0, _next = nil) @val = val @next = _next end end class Solution def merge_k_lists(lists) return nil if lists.empty? while lists.length > 1 do lists.push(merge_2_lists(lists.shift, list...
dolphin
Please focus on the algorithm of this problem and provide code in R: You are given a **0-indexed** string `num` of length `n` consisting of digits. Return `true` _if for **every** index_ `i` _in the range_ `0 <= i < n`_, the digit_ `i` _occurs_ `num[i]` _times in_ `num`_, otherwise return_ `false`. **Example 1:** **...
dolphin
translate this code to Haskell: ```objective-c #import <Foundation/Foundation.h> NSArray* shuffleString(NSString* s, NSArray* indices) { NSMutableArray* shuffled = [NSMutableArray arrayWithCapacity:[s length]]; for (int i = 0; i < [s length]; i++) { [shuffled addObject:@""]; } for (int i = 0; i...
dolphin
Please write the following solution using Object Pascal: You are playing a game involving a **circular** array of non-zero integers `nums`. Each `nums[i]` denotes the number of indices forward/backward you must move if you are located at index `i`: * If `nums[i]` is positive, move `nums[i]` steps **forward**, and * ...
dolphin
Please write the following solution using Julia: You are given a 2D integer array `ranges` where `ranges[i] = [starti, endi]` denotes that all integers between `starti` and `endi` (both **inclusive**) are contained in the `ith` range. You are to split `ranges` into **two** (possibly empty) groups such that: * Each ...
dolphin