instruction_seed
stringlengths
29
40.5k
source
stringclasses
6 values
port this code from Dart to Lua: ```dart int minDifference(List<int> nums) { int n = nums.length; if (n <= 4) return 0; nums.sort(); int res = double.infinity.toInt(); for (int i = 0; i < 4; i++) { res = res < nums[n - 4 + i] - nums[i] ? res : nums[n - 4 + i] - nums[i]; } return res; } ```
dolphin
convert this code from Lua to R: ```lua function Latest24hrTime(arr) local max_time = "00:00" local function swap(arr, i, j) local temp = arr[i] arr[i] = arr[j] arr[j] = temp end local function permute(arr, l, r) if l == r then local hour = arr[1]*10 + arr[2] ...
dolphin
Please explain the reasoning behind the following solution and provide code in Julia: Given the `head` of a linked list, return _the node where the cycle begins. If there is no cycle, return_ `null`. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following...
dolphin
Please explain the reasoning behind the following solution and provide code in Swift: 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...
dolphin
Please explain the following problem in detail and provide code in Object Pascal: Given two strings `a` and `b`, return _the minimum number of times you should repeat string_ `a` _so that string_ `b` _is a substring of it_. If it is impossible for `b`​​​​​​ to be a substring of `a` after repeating it, return `-1`. **N...
dolphin
Please explain the following problem in detail and provide code in Groovy: A **sentence** is a list of words that are separated by a single space with no leading or trailing spaces. Each word consists of lowercase and uppercase English letters. A sentence can be **shuffled** by appending the **1-indexed word position*...
dolphin
port this code from Scheme to PHP: ```scheme (define (find-triplets nums) (let ((first +inf.0) (second +inf.0)) (do ((i 0 (+ i 1))) ((= i (length nums)) #f) (let ((num (list-ref nums i))) (cond ((<= num first) (set! first num)) ((<= num second) (set! second num)) ...
dolphin
convert this code from Swift to Elixir: ```swift func totalHammingDistance(_ nums: [Int]) -> Int { var totalDistance = 0 let n = nums.count for i in 0..<32 { var bitCount = 0 for num in nums { bitCount += ((num >> i) & 1) } totalDistance += bitCount * (n - bi...
dolphin
Please write the following solution using Go: You are given a 2D integer array `rectangles` where `rectangles[i] = [li, hi]` indicates that `ith` rectangle has a length of `li` and a height of `hi`. You are also given a 2D integer array `points` where `points[j] = [xj, yj]` is a point with coordinates `(xj, yj)`. The ...
dolphin
convert this code from javascript to Visual Basic .NET: ```javascript var maxAreaOfIsland = function(grid) { let maxArea = 0; function dfs(i, j) { if (i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || grid[i][j] === 0) { return 0; } grid[i][j] = 0; ret...
dolphin
translate this code to Dart: ```vb.net Function countDistinctSubsequences(s As String) As Integer Dim n As Integer = s.Length Dim mod_num As Integer = 1000000007 Dim dp(n) As Integer Dim last(26) As Integer dp(0) = 1 For i As Integer = 0 To n - 1 dp(i + 1) = (dp(i) * 2) Mod mod_num ...
dolphin
translate this code from Go to Rust: ```go func numOfBurgers(tomatoSlices int, cheeseSlices int) []int { totalJumbo := (tomatoSlices - 2 * cheeseSlices) / 2 totalSmall := cheeseSlices - totalJumbo if tomatoSlices < 0 || cheeseSlices < 0 || tomatoSlices % 2 == 1 || totalJumbo < 0 || totalSmall < 0 { ...
dolphin
Please explain the following problem in detail and provide code in Scheme: You are given a **0-indexed** integer array `nums` of length `n`. You are initially standing at index `0`. You can jump from index `i` to index `j` where `i < j` if: * `nums[i] <= nums[j]` and `nums[k] < nums[i]` for all indexes `k` in the ra...
dolphin
Please explain the following problem in detail and provide code in ANSI C: Given a sentence `text` (A _sentence_ is a string of space-separated words) in the following format: * First letter is in upper case. * Each word in `text` are separated by a single space. Your task is to rearrange the words in text such t...
dolphin
Please explain the following problem in detail and provide code in Swift: Consider all the leaves of a binary tree, from left to right order, the values of those leaves form a **leaf value sequence**_._ For example, in the given tree above, the leaf value sequence is `(6, 7, 4, 9, 8)`. Two binary trees are considered...
dolphin
Please explain the following problem in detail and provide code in Scala: We are given `n` different types of `stickers`. Each sticker has a lowercase English word on it. You would like to spell out the given string `target` by cutting individual letters from your collection of stickers and rearranging them. You can u...
dolphin
Please explain the following problem in detail and provide code in Julia: You are given an undirected weighted graph of `n` nodes (0-indexed), represented by an edge list where `edges[i] = [a, b]` is an undirected edge connecting the nodes `a` and `b` with a probability of success of traversing that edge `succProb[i]`....
dolphin
Please explain the following problem in detail and provide code in R: In a project, you have a list of required skills `req_skills`, and a list of people. The `ith` person `people[i]` contains a list of skills that the person has. Consider a sufficient team: a set of people such that for every required skill in `req_s...
dolphin
convert this code to Swift: ```clojure (defn find-min-moves [machines] (let [n (count machines) total-dresses (reduce + machines) average (quot total-dresses n)] (if (not (= 0 (mod total-dresses n))) -1 (let [moves (atom 0) imbalance (atom 0)] (doseq [i (range n)] ...
dolphin
Please explain the reasoning behind the following solution and provide code in Visual Basic .NET: Given a string `s` and an integer `k`, return _the length of the longest substring of_ `s` _such that the frequency of each character in this substring is greater than or equal to_ `k`. **Example 1:** **Input:** s = "aa...
dolphin
Please explain the following problem in detail and provide code in Fortran: You are playing a game that has `n` levels numbered from `0` to `n - 1`. You are given a **0-indexed** integer array `damage` where `damage[i]` is the amount of health you will lose to complete the `ith` level. You are also given an integer `a...
dolphin
Please focus on the functionality of this problem and provide code in Scheme: Given 3 positives numbers `a`, `b` and `c`. Return the minimum flips required in some bits of `a` and `b` to make ( `a` OR `b` == `c` ). (bitwise OR operation). Flip operation consists of change **any** single bit 1 to 0 or change the bit 0...
dolphin
Please write the following solution using python: You are given a **0-indexed** integer array `forts` of length `n` representing the positions of several forts. `forts[i]` can be `-1`, `0`, or `1` where: * `-1` represents there is **no fort** at the `ith` position. * `0` indicates there is an **enemy** fort at the...
dolphin
Please explain the reasoning behind the following solution and provide code in Scala: 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 exactl...
dolphin
Please explain the following problem in detail and provide code in Elixir: You are given a string `s` consisting of digits and an integer `k`. A **round** can be completed if the length of `s` is greater than `k`. In one round, do the following: 1. **Divide** `s` into **consecutive groups** of size `k` such that the...
dolphin
translate this code from Lua to ANSI C: ```lua function findStrobogrammatic(n) local function helper(n, m) if n == 0 then return {""} elseif n == 1 then return {"0", "1", "8"} end local list = helper(n - 2, m) local res = {} for i=1, #list do local s = list[i] ...
dolphin
Please explain the following problem in detail and provide code in python: Given two integer arrays `nums1` and `nums2`, sorted in non-decreasing order, return _the **minimum integer common** to both arrays_. If there is no common integer amongst `nums1` and `nums2`, return `-1`. Note that an integer is said to be **c...
dolphin
Please explain the following problem in detail and provide code in Objective-C: Given an integer `num`, return _a string of its **base 7** representation_. **Example 1:** **Input:** num = 100 **Output:** "202" **Example 2:** **Input:** num = -7 **Output:** "-10" **Constraints:** * `-107 <= num <= 107`
dolphin
translate this code to Lisp: ```scala def minimumCost(expression: String): Int = { val n = expression.length val dp = Array.ofDim[Int](n, n) for (i <- n - 1 to 0 by -1) { for (j <- i until n) { if (i == j) { dp(i)(j) = if (expression(i) == '0') 1 else 0 } else { dp(i)(j) = Int.Max...
dolphin
Please explain the following problem in detail and provide code in Kotlin: Given an integer `columnNumber`, return _its corresponding column title as it appears in an Excel sheet_. For example: A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28 ... **Example 1:** **Input:** columnNumber = 1 **Output:** "A " **Ex...
dolphin
translate this code to Perl: ```scheme (define (inorderTraversalHelper root result) (cond ((null? root) '()) (else (begin (inorderTraversalHelper (left root) result) (set! result (append result (list (val root)))) (inorderTraversalHelper (right root) r...
dolphin
Please explain the following problem in detail and provide code in ANSI C: A **sentence** is a list of **words** that are separated by a single space with no leading or trailing spaces. You are given an array of strings `sentences`, where each `sentences[i]` represents a single **sentence**. Return _the **maximum num...
dolphin
convert this code to Lisp: ```scala def subsetXORSum(nums: Array[Int]): Int = { var ans = 0 val n = nums.length val max_val = 1 << n for (i <- 1 until max_val) { var xor_total = 0 for (j <- 0 until n) { if ((i & (1 << j)) != 0) { xor_total ^= nums(j) } } ans += xor_total } ...
dolphin
port this code to Fortran: ```go func fullJustify(words []string, maxWidth int) []string { result := []string{} idx := 0 for idx < len(words) { totalChars := len(words[idx]) last := idx + 1 for last < len(words) { if totalChars+1+len(words[last]) > maxWidth { ...
dolphin
port this code from Fortran to Julia: ```fortran MODULE DistanceLimitedPathsExist PRIVATE INTEGER, PARAMETER :: MaxN = 10000, MaxE = 10000, Inf = 1000000000 INTEGER :: id(MaxN), sz(MaxN) INTEGER, DIMENSION(3, MaxE) :: edgeList, mst CONTAINS SUBROUTINE UnionSet(x, y) INTEGER, INTENT...
dolphin
Please focus on the efficiency of this problem and provide code in Lisp: Consider a matrix `M` with dimensions `width * height`, such that every cell has value `0` or `1`, and any **square** sub-matrix of `M` of size `sideLength * sideLength` has at most `maxOnes` ones. Return the maximum possible number of ones that ...
dolphin
Please explain the following problem in detail and provide code in Ruby: Given an integer `n`, return _a list of all **simplified** fractions between_ `0` _and_ `1` _(exclusive) such that the denominator is less-than-or-equal-to_ `n`. You can return the answer in **any order**. **Example 1:** **Input:** n = 2 **Outpu...
dolphin
port this code from Clojure to Lua: ```clojure (defn k-concatenation-max-sum [arr k] (let [M (mod (+ 1e9 7) 1e9) s (apply + arr) max-sum (loop [i 0 max-ending-here 0 max-sum 0] (if (= i (* (count arr) (min 2 k))) max-sum (let [new-max-ending-he...
dolphin
Please focus on the functionality of this problem and provide code in F#: You are given an array `nums` of non-negative integers. `nums` is considered **special** if there exists a number `x` such that there are **exactly** `x` numbers in `nums` that are **greater than or equal to** `x`. Notice that `x` **does not** h...
dolphin
Please explain the following problem in detail and provide code in Haskell: Given an integer array `nums`, you need to find one **continuous subarray** that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order. Return _the shortest such subarray and output its lengt...
dolphin
translate this code from Julia to Visual Basic .NET: ```julia function min_operations(target::Vector{Int}, initial::Vector{Int})::Int n = length(target) operations = 0 for i in 1:n diff = target[i] - initial[i] if diff > 0 for j in i:n if initial[j] < target[j] &&...
dolphin
port this code to python: ```perl sub count_stars_except_between_pair { my ($s) = @_; my $count = 0; my $pipe_count = 0; for my $c (split //, $s) { if ($c eq '|') { $pipe_count += 1; } elsif ($c eq '*' and $pipe_count % 2 == 0) { $count += 1; } ...
dolphin
Please focus on the algorithm of this problem and provide code in javascript: Given an integer array `nums` sorted in non-decreasing order and an integer `target`, return `true` _if_ `target` _is a **majority** element, or_ `false` _otherwise_. A **majority** element in an array `nums` is an element that appears more ...
dolphin
Please explain the reasoning behind the following solution and provide code in Mojo: There is a strange printer with the following two special requirements: * On each turn, the printer will print a solid rectangular pattern of a single color on the grid. This will cover up the existing colors in the rectangle. * O...
dolphin
convert this code from Fortran to Julia: ```fortran function longest_palindromic_substring(s) result(res) character(*), intent(in) :: s character(*), allocatable :: res integer :: n, i, l, r, start, max_length, length n = len(s) if (n == 0) then res = "" return end if st...
dolphin
convert this code from javascript to R: ```javascript function countSmaller(nums) { function mergeSort(indices, start, end) { if (start >= end) { return; } let mid = start + ((end - start) >> 1); mergeSort(indices, start, mid); mergeSort(indices, mid + 1, end); ...
dolphin
Please explain the following problem in detail and provide code in Object Pascal: Suppose an array of length `n` sorted in ascending order is **rotated** between `1` and `n` times. For example, the array `nums = [0,1,2,4,5,6,7]` might become: * `[4,5,6,7,0,1,2]` if it was rotated `4` times. * `[0,1,2,4,5,6,7]` if ...
dolphin
Please focus on the efficiency of this problem and provide code in R: Given two integers representing the `numerator` and `denominator` of a fraction, return _the fraction in string format_. If the fractional part is repeating, enclose the repeating part in parentheses. If multiple answers are possible, return **any ...
dolphin
Please write the following solution using Perl: You have `n` coins and you want to build a staircase with these coins. The staircase consists of `k` rows where the `ith` row has exactly `i` coins. The last row of the staircase **may be** incomplete. Given the integer `n`, return _the number of **complete rows** of the...
dolphin
translate this code from ANSI C to Object Pascal: ```c #include <stdio.h> int min_operations(int nums[], int n) { int even = 0, odd = 0; for (int i = 0; i < n; i++) { if (i % 2 == 0 && nums[i] % 2 != 0) { even++; } else if (i % 2 != 0 && nums[i] % 2 == 0) { odd++; ...
dolphin
Please write the following solution using Scheme: Given an integer `num`, find the closest two integers in absolute difference whose product equals `num + 1` or `num + 2`. Return the two integers in any order. **Example 1:** **Input:** num = 8 **Output:** \[3,3\] **Explanation:** For num + 1 = 9, the closest divisor...
dolphin
translate this code to Ruby: ```swift class Node { var val: Bool var isLeaf: Bool var topLeft: Node? var topRight: Node? var bottomLeft: Node? var bottomRight: Node? init(val: Bool, isLeaf: Bool, topLeft: Node?, topRight: Node?, bottomLeft: Node?, bottomRight: Node?) { self.val ...
dolphin
Please focus on the efficiency of this problem and provide code in python: Given an integer `num`, return _a string representing its hexadecimal representation_. For negative integers, [two's complement](https://en.wikipedia.org/wiki/Two%27s_complement) method is used. All the letters in the answer string should be lo...
dolphin
Please focus on the efficiency of this problem and provide code in c++: 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 **uni...
dolphin
convert this code to Dart: ``` function equivalent(root1, root2) if root1 == nil and root2 == nil then return true elseif root1 == nil or root2 == nil then return false elseif root1.val ~= root2.val then return false else return equivalent(root1.left, root2.left) and equi...
dolphin
Please explain the reasoning behind the following solution and provide code in Rust: You are given an integer array `nums`. In one move, you can pick an index `i` where `0 <= i < nums.length` and increment `nums[i]` by `1`. Return _the minimum number of moves to make every value in_ `nums` _**unique**_. The test case...
dolphin
Please write the following solution using R: There is only one character `'A'` on the screen of a notepad. You can perform one of two operations on this notepad for each step: * Copy All: You can copy all the characters present on the screen (a partial copy is not allowed). * Paste: You can paste the characters wh...
dolphin
Please focus on the efficiency of this problem and provide code in Lisp: You are **building** a string `s` of length `n` **one** character at a time, **prepending** each new character to the **front** of the string. The strings are labeled from `1` to `n`, where the string with length `i` is labeled `si`. * For exam...
dolphin
Please explain the following problem in detail and provide code in Elixir: You are given an integer array `nums` where the `ith` bag contains `nums[i]` balls. You are also given an integer `maxOperations`. You can perform the following operation at most `maxOperations` times: * Take any bag of balls and divide it i...
dolphin
port this code to c++: ```rust fn max_catch(team: &mut [i32], dist: i32) -> i32 { let n = team.len(); let mut num_caught = 0; for i in 0..n { if team[i] == 1 { let j = i - dist.max(0); let k = i + dist.min(n as i32 - 1) as usize; for l in j..=k { i...
dolphin
Please focus on the efficiency of this problem and provide code in Scala: The thief has found himself a new place for his thievery again. There is only one entrance to this area, called `root`. Besides the `root`, each house has one and only one parent house. After a tour, the smart thief realized that all houses in t...
dolphin
Please explain the reasoning behind the following solution and provide code in Erlang: You are given two binary trees `root1` and `root2`. Imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge the two trees into a new binary tre...
dolphin
Please explain the reasoning behind the following solution and provide code in ANSI C: You are given an integer array `nums` and a **positive** integer `k`. The **frequency score** of an array is the sum of the **distinct** values in the array raised to the power of their **frequencies**, taking the sum **modulo** `10...
dolphin
Please focus on the algorithm of this problem and provide code in python: You are given an integer array `bloomDay`, an integer `m` and an integer `k`. You want to make `m` bouquets. To make a bouquet, you need to use `k` **adjacent flowers** from the garden. The garden consists of `n` flowers, the `ith` flower will ...
dolphin
Please explain the following problem in detail and provide code in javascript: You are given a string `s` of even length. Split this string into two halves of equal lengths, and let `a` be the first half and `b` be the second half. Two strings are **alike** if they have the same number of vowels (`'a'`, `'e'`, `'i'`, ...
dolphin
port this code to Rust: ```python def can_destroy_all_asteroids(mass, asteroids): asteroids.sort() for asteroid in asteroids: if mass >= asteroid: mass += asteroid else: return False return True ```
dolphin
translate this code from F# to Kotlin: ```fsharp let minOperations n = let mutable count = 1 let mutable temp = 1 while temp % n <> 0 do temp <- (temp * 2) % n count <- count + 1 count ```
dolphin
translate this code to TypeScript: ```erlang -module(spiral_matrix). -export([spiral_matrix/3]). spiral_matrix(M, N, Head) -> %% Initialize matrix with -1 Matrix = lists:duplicate(M, lists:duplicate(N, -1)), %% Set curr_node to head CurrNode = Head, %% Initialize variables for the four sides of the...
dolphin
Please explain the following problem in detail and provide code in Fortran: Given an integer `n` (in base `10`) and a base `k`, return _the **sum** of the digits of_ `n` _**after** converting_ `n` _from base_ `10` _to base_ `k`. After converting, each digit should be interpreted as a base `10` number, and the sum shou...
dolphin
port this code from Rust to Ruby: ```rust fn bad_pairs(nums: &[i32]) -> i32 { let mut count = 0; for i in 0..nums.len() { for j in (i+1)..nums.len() { if j as i32 - i as i32 != nums[j] - nums[i] { count += 1; } } } count } ```
dolphin
Please write the following solution using Julia: You are playing a game of tag with your friends. In tag, people are divided into two teams: people who are "it ", and people who are not "it ". The people who are "it " want to catch as many people as possible who are not "it ". You are given a **0-indexed** integer arr...
dolphin
Please write the following solution using 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 ball stops, it could choos...
dolphin
port this code from Erlang to Rust: ```erlang -module(biker). -export([highest_altitude/1]). highest_altitude(Gain) -> MaxAltitude = 0, CurrentAltitude = 0, [H|T] = Gain, CurrentAltitude = H, lists:foldl(fun(G, Acc) -> Altitude = Acc + G, if Altitude > CurrentAltitude -...
dolphin
convert this code from java to python: ```java public boolean validTicTacToe(String[] board) { int xCount = 0, oCount = 0; for (String row : board) { for (char c : row.toCharArray()) { if (c == 'X') xCount++; else if (c == 'O') oCount++; } } if (xCount != oCount &...
dolphin
translate this code from Go to Clojure: ```go func mergePiles(stones []int, k int) int { n := len(stones) if n < k { return -1 } cost := make([][]int, n) for i := range cost { cost[i] = make([]int, n) } prefixSum := make([]int, n+1) for i := 1; i <= n; i++ { prefi...
dolphin
Please focus on the efficiency of this problem and provide code in Object Pascal: You are given an `m x n` integer matrix `grid`, and three integers `row`, `col`, and `color`. Each value in the grid represents the color of the grid square at that location. Two squares belong to the same **connected component** if they...
dolphin
Please explain the following problem in detail and provide code in Clojure: Given an array of `digits` which is sorted in **non-decreasing** order. You can write numbers using each `digits[i]` as many times as we want. For example, if `digits = ['1','3','5']`, we may write numbers such as `'13'`, `'551'`, and `'1351315...
dolphin
Please explain the following problem in detail and provide code in Lua: Given a string `s`, _find the first non-repeating character in it and return its index_. If it does not exist, return `-1`. **Example 1:** **Input:** s = "leetcode" **Output:** 0 **Example 2:** **Input:** s = "loveleetcode" **Output:** 2 **Exa...
dolphin
Please explain the reasoning behind the following solution and provide code in Elixir: You are given two strings `word1` and `word2`. Merge the strings by adding letters in alternating order, starting with `word1`. If a string is longer than the other, append the additional letters onto the end of the merged string. R...
dolphin
Please focus on the functionality of this problem and provide code in Go: For a binary tree **T**, we can define a **flip operation** as follows: choose any node, and swap the left and right child subtrees. A binary tree **X** is _flip equivalent_ to a binary tree **Y** if and only if we can make **X** equal to **Y** ...
dolphin
Please explain the following problem in detail and provide code in Ruby: Given a string `s` consisting of words and spaces, return _the length of the **last** word in the string._ A **word** is a maximal substring consisting of non-space characters only. **Example 1:** **Input:** s = "Hello World " **Output:** 5 **...
dolphin
Please explain the following problem in detail and provide code in TypeScript: You are given `n` rectangles represented by a **0-indexed** 2D integer array `rectangles`, where `rectangles[i] = [widthi, heighti]` denotes the width and height of the `ith` rectangle. Two rectangles `i` and `j` (`i < j`) are considered **...
dolphin
Please write the following solution using Ruby: A **subarray** of a **0-indexed** integer array is a contiguous **non-empty** sequence of elements within an array. The **alternating subarray sum** of a subarray that ranges from index `i` to `j` (**inclusive**, `0 <= i <= j < nums.length`) is `nums[i] - nums[i+1] + num...
dolphin
Please explain the reasoning behind the following solution and provide code in Lua: Given an array of digits `digits`, return _the largest multiple of **three** that can be formed by concatenating some of the given digits in **any order**_. If there is no answer return an empty string. Since the answer may not fit in ...
dolphin
Please write the following solution using Julia: Given the `head` of a singly linked list and an integer `k`, split the linked list into `k` consecutive linked list parts. The length of each part should be as equal as possible: no two parts should have a size differing by more than one. This may lead to some parts bei...
dolphin
convert this code to C#: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> char* addBoldTag(char* s, char** words, int wordsSize) { int n = strlen(s); bool* marked = (bool*)calloc(n, sizeof(bool)); for (int i = 0; i < wordsSize; i++) { char* pos = s; while...
dolphin
translate this code to C#: ```c int minTimeToVisitAllPoints(int** points, int pointsSize, int* pointsColSize){ int time = 0; for(int i=1; i<pointsSize; i++){ int dx = abs(points[i][0] - points[i-1][0]); int dy = abs(points[i][1] - points[i-1][1]); time += (dx > dy ? dx : dy); } r...
dolphin
Please explain the reasoning behind the following solution and provide code in Object Pascal: Given the `root` of a binary search tree and the lowest and highest boundaries as `low` and `high`, trim the tree so that all its elements lies in `[low, high]`. Trimming the tree should **not** change the relative structure o...
dolphin
convert this code to Erlang: ```dart int nAryTreeDiameter(List<Node> root) { int diameter = 0; int dfs(Node node) { if (node.children.isEmpty) { return 0; } int firstMax = 0, secondMax = 0; for (Node child in node.children) { int height = dfs(child); if (height > firstMax) { ...
dolphin
port this code to Lua: ```scheme (define (min-operations nums target) (let* ((n (length nums)) (sum-nums (apply + nums)) (sum-target (apply + target)) (diff (floor (/ (- sum-target sum-nums) 2))) (cnt 0)) (do ((i 0 (+ i 1))) ((= i n) cnt) (when (> (list-ref nums i...
dolphin
Please write the following solution using Go: We can represent a sentence as an array of words, for example, the sentence `"I am happy with leetcode "` can be represented as `arr = [ "I ", "am ",happy ", "with ", "leetcode "]`. Given two sentences `sentence1` and `sentence2` each represented as a string array and give...
dolphin
port this code to Visual Basic .NET: ```go type TrieNode struct { children [26]*TrieNode value int } type MapSum struct { root *TrieNode mp map[string]int } func Constructor() MapSum { root := &TrieNode{} return MapSum{root, make(map[string]int)} } func (this *MapSum) Insert(key string, val i...
dolphin
Please write the following solution using R: We have an integer array `nums`, where all the integers in `nums` are **0** or **1**. You will not be given direct access to the array, instead, you will have an **API** `ArrayReader` which have the following functions: * `int query(int a, int b, int c, int d)`: where `0 ...
dolphin
Please write the following solution using SmallTalk: You are given an integer array `nums`. You are initially positioned at the array's **first index**, and each element in the array represents your maximum jump length at that position. Return `true` _if you can reach the last index, or_ `false` _otherwise_. **Exampl...
dolphin
Please write the following solution using Ruby: 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** are created by leaning two ...
dolphin
port this code from ANSI C to Go: ```c #include <stdio.h> #include <stdlib.h> #include <stdbool.h> typedef struct TreeNode { int val; struct TreeNode* left; struct TreeNode* right; } TreeNode; bool isValidSequence(TreeNode* root, int* arr, int arrSize, int index) { if (!root || index >= arrSize || arr...
dolphin
translate this code from c++ to Rust: ```cpp #include <string> #include <sstream> std::string complexNumberMultiply(std::string num1, std::string num2) { int real1, imag1, real2, imag2; sscanf(num1.c_str(), "%d+%di", &real1, &imag1); sscanf(num2.c_str(), "%d+%di", &real2, &imag2); int real = real1 ...
dolphin
convert this code to Erlang: ```vb.net Public Function LongestPathWithDifferentCharacters(parent() As Integer, s As String) As Integer Dim n As Integer = parent.Length Dim dp(n - 1) As Integer Dim maxLength As Integer = 0 For i As Integer = 0 To n - 1 If s(i) <> s(0) Then dp(i) ...
dolphin
Please write the following solution using python: 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:** **Input:** nums = \[-4,-2,2,4\], ...
dolphin
Please explain the following problem in detail and provide code in Mojo: There are a row of `n` houses, each house can be painted with one of the `k` colors. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color. The cos...
dolphin