instruction_seed
stringlengths
29
40.5k
source
stringclasses
6 values
Please explain the reasoning behind the following solution and provide code in Erlang: Given the `root` of a binary tree, determine if it is a _complete binary tree_. In a **[complete binary tree](http://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_trees)**, every level, except possibly the last, is completely fi...
dolphin
port this code to Scala: ```typescript function isCovered(ranges: number[][], left: number, right: number): boolean { const covered: number[] = new Array(51).fill(0); for (const _range of ranges) { for (let i = _range[0]; i <= _range[1]; i++) { covered[i] = 1; } } for (let i ...
dolphin
convert this code to C#: ```fortran subroutine largestNumber(cost, target, result) integer, dimension(9), intent(in) :: cost integer, intent(in) :: target character(100), intent(out) :: result character(100), dimension(target + 1) :: dp integer :: i, j, k dp(1:target + 1) = " " dp(1) = "" ...
dolphin
Please explain the reasoning behind the following solution and provide code in Mojo: Given an integer `n`, return _an array_ `ans` _of length_ `n + 1` _such that for each_ `i` (`0 <= i <= n`)_,_ `ans[i]` _is the **number of**_ `1`_**'s** in the binary representation of_ `i`. **Example 1:** **Input:** n = 2 **Output:*...
dolphin
Please explain the reasoning behind the following solution and provide code in Scheme: There is an **undirected** graph consisting of `n` nodes numbered from `1` to `n`. You are given the integer `n` and a **2D** array `edges` where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi`. The ...
dolphin
port this code to Perl: ```dart int numTuples(List<int> arr, int target) { int count = 0; int n = arr.length; arr.sort(); int mod = 1000000007; for (int i = 0; i < n-2; i++) { int j = i+1, k = n-1; while (j < k) { int total = arr[i] + arr[j] + arr[k]; if (total == target) { int ...
dolphin
translate this code from F# to Visual Basic .NET: ```fsharp let rec candyCrush (board:int[][]) = let rows = Array.length board let cols = Array.length board.[0] let mutable toDo = false for r in 0 .. rows - 1 do for c in 0 .. cols - 3 do let v = abs board.[r].[c] if ...
dolphin
Please explain the reasoning behind the following solution and provide code in Clojure: Design a Todo List Where users can add **tasks**, mark them as **complete**, or get a list of pending tasks. Users can also add **tags** to tasks and can filter the tasks by certain tags. Implement the `TodoList` class: * `TodoL...
dolphin
Please explain the reasoning behind the following solution and provide code in Erlang: Given an array of strings `words` (**without duplicates**), return _all the **concatenated words** in the given list of_ `words`. A **concatenated word** is defined as a string that is comprised entirely of at least two shorter word...
dolphin
Please explain the reasoning behind the following solution and provide code in java: You are given a binary string `s` and a positive integer `k`. Return _the length of the **longest** subsequence of_ `s` _that makes up a **binary** number less than or equal to_ `k`. Note: * The subsequence can contain **leading z...
dolphin
convert this code to F#: ```python MOD = 10**9 + 7 def mul(a, b): return (a * b) % MOD def ways(n, k, mem): if n == 1: return k if (n_tuple := (n, k)) in mem: return mem[n_tuple] if k == 1: mem[n_tuple] = 1 return 1 if n > k: mem[n_tuple] = 0 return ...
dolphin
Please focus on the algorithm of this problem and provide code in PHP: You are given the `root` of a binary tree and a positive integer `k`. The **level sum** in the tree is the sum of the values of the nodes that are on the **same** level. Return _the_ `kth` _**largest** level sum in the tree (not necessarily distin...
dolphin
translate this code from C# to Clojure: ```csharp public class Solution { public int LargestMagicSquare(int[][] grid) { int m = grid.Length, n = grid[0].Length; int[][] row = new int[m][], col = new int[m + 1][]; for(int i = 0; i < m; i++){ row[i] = new int[n + 1]; fo...
dolphin
Please write the following solution using Visual Basic .NET: Given a **1-indexed** array of integers `numbers` that is already **_sorted in non-decreasing order_**, find two numbers such that they add up to a specific `target` number. Let these two numbers be `numbers[index1]` and `numbers[index2]` where `1 <= index1 <...
dolphin
translate this code from ANSI C to javascript: ```c #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #define MAX_N 100 struct Queue { int front, rear; int arr[MAX_N * MAX_N][2]; }; struct Queue* createQueue() { struct Queue* q = (struct Queue*) malloc(sizeof(struct Queue)); q->front = -1; ...
dolphin
Please explain the following problem in detail and provide code in python: Given a string `s` which represents an expression, _evaluate this expression and return its value_. The integer division should truncate toward zero. You may assume that the given expression is always valid. All intermediate results will be in...
dolphin
convert this code from Swift to python: ```swift class Solution { func findShortestWay(_ maze: [[Int]], _ ball: [Int], _ hole: [Int]) -> String { let m = maze.count, n = maze[0].count var dist = Array(repeating: Array(repeating: Int.max, count: n), count: m) let dirs = ["d", "l", "r", "u"] ...
dolphin
Please explain the following problem in detail and provide code in Ruby: A **confusing number** is a number that when rotated `180` degrees becomes a different number with **each digit valid**. We can rotate digits of a number by `180` degrees to form new digits. * When `0`, `1`, `6`, `8`, and `9` are rotated `180`...
dolphin
translate this code to Lua: ```pascal program Solution; const MAXSIZE = 1000000; type Edge = record fromi: integer; toi: integer; weighti: integer; end; AdjList = array of array of record v: integer; w: integer; end; function dijkstra(src: integer; adj: Adj...
dolphin
Please explain the following problem in detail and provide code in Visual Basic .NET: There is a long table with a line of plates and candles arranged on top of it. You are given a **0-indexed** string `s` consisting of characters `'*'` and `'|'` only, where a `'*'` represents a **plate** and a `'|'` represents a **can...
dolphin
Please write the following solution using Ruby: Given a non-negative integer `x`, return _the square root of_ `x` _rounded down to the nearest integer_. The returned integer should be **non-negative** as well. You **must not use** any built-in exponent function or operator. * For example, do not use `pow(x, 0.5)` i...
dolphin
convert this code from Visual Basic .NET to Lisp: ```vb.net Public Class Employee Public Property id As Integer Public Property importance As Integer Public Property subordinates As List(Of Integer) End Class Public Function getTotalImportance(employees As List(Of Employee), id As Integer) As Integer D...
dolphin
Please explain the following problem in detail and provide code in TypeScript: Given an array of integers `citations` where `citations[i]` is the number of citations a researcher received for their `ith` paper and `citations` is sorted in **ascending order**, return _the researcher's h-index_. According to the [defini...
dolphin
Please explain the reasoning behind the following solution and provide code in Go: 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 ...
dolphin
Please focus on the efficiency of this problem and provide code in Groovy: Given an `m x n` `matrix`, return _all elements of the_ `matrix` _in spiral order_. **Example 1:** **Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\] **Output:** \[1,2,3,6,9,8,7,4,5\] **Example 2:** **Input:** matrix = \[\[1,2,3,4\],\[5,6...
dolphin
port this code to Go: ```php function sumConsecutiveIntegers($num) { $result = array(); for ($i = 1; $i <= $num; $i++) { $sum = 0; for ($j = $i; $j <= $num; $j++) { $sum += $j; if ($sum == $num && $j - $i == 2) { $result = array($i, $i+1, $i+2); ...
dolphin
Please explain the reasoning behind the following solution and provide code in Clojure: You are given a string `sentence` containing words separated by spaces, and an integer `k`. Your task is to separate `sentence` into **rows** where the number of characters in each row is **at most** `k`. You may assume that `senten...
dolphin
convert this code from Go to Lisp: ```go type Video struct { videoId int video string views int likes int dislikes int } type VideoSharingPlatform struct { videoMap map[int]*Video availableIds []int } func Constructor() VideoSharingPlatform { return VideoSharingPlatform...
dolphin
Please explain the following problem in detail and provide code in R: Given an array of integers `citations` where `citations[i]` is the number of citations a researcher received for their `ith` paper and `citations` is sorted in **ascending order**, return _the researcher's h-index_. According to the [definition of h...
dolphin
Please explain the following problem in detail and provide code in python: You are given an `m x n` binary matrix `grid`. A **move** consists of choosing any row or column and toggling each value in that row or column (i.e., changing all `0`'s to `1`'s, and all `1`'s to `0`'s). Every row of the matrix is interpreted ...
dolphin
Please focus on the efficiency of this problem and provide code in Perl: A **wiggle sequence** is a sequence where the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with one element and a seque...
dolphin
Please focus on the functionality of this problem and provide code in Perl: You are given two positive integer arrays `nums` and `numsDivide`. You can delete any number of elements from `nums`. Return _the **minimum** number of deletions such that the **smallest** element in_ `nums` _**divides** all the elements of_ `...
dolphin
translate this code from Fortran to F#: ```fortran PROGRAM Max_XOR_Subtree IMPLICIT NONE INTEGER :: n, i, j INTEGER, DIMENSION(:,:), ALLOCATABLE :: edges INTEGER, DIMENSION(:), ALLOCATABLE :: values INTEGER :: root_sum, first_max INTEGER, DIMENSION(:), ALLOCATABLE :: tree READ(*,*) n A...
dolphin
Please explain the following problem in detail and provide code in PHP: You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in **adjacent** plots. Given an integer array `flowerbed` containing `0`'s and `1`'s, where `0` means empty and `1` means not em...
dolphin
Please explain the following problem in detail and provide code in Groovy: You are given a **0-indexed**, **strictly increasing** integer array `nums` and a positive integer `diff`. A triplet `(i, j, k)` is an **arithmetic triplet** if the following conditions are met: * `i < j < k`, * `nums[j] - nums[i] == diff`,...
dolphin
convert this code from Elixir to Scala: ```elixir defmodule Solution do def count_pairs(nums, k) do mod_count = Enum.reduce(nums, fn num, acc -> acc |> Enum.with_index() |> Enum.map(fn {count, i} -> if i == rem(num, k) do count + 1 else count end end) end, Enum.replicate(k, 0)) count ...
dolphin
convert this code from Mojo to Visual Basic .NET: ``` sub min_time_to_repair(ranks, cars) { ranks.sort() my $low = 0 my $high = 100 * $cars * $cars while ($low < $high) { my $mid = $low + ($high - $low) div 2 my $total_cars_repaired = 0 for my $rank (@$ranks) { ...
dolphin
Please focus on the functionality of this problem and provide code in R: Given a string `s` of lower and upper case English letters. A good string is a string which doesn't have **two adjacent characters** `s[i]` and `s[i + 1]` where: * `0 <= i <= s.length - 2` * `s[i]` is a lower-case letter and `s[i + 1]` is th...
dolphin
Please explain the reasoning behind the following solution and provide code in Swift: You are given a **0-indexed** 2D integer array `tires` where `tires[i] = [fi, ri]` indicates that the `ith` tire can finish its `xth` successive lap in `fi * ri(x-1)` seconds. * For example, if `fi = 3` and `ri = 2`, then the tire ...
dolphin
Please explain the following problem in detail and provide code in ANSI C: Given an `m x n` binary `matrix` filled with `0`'s and `1`'s, _find the largest square containing only_ `1`'s _and return its area_. **Example 1:** **Input:** matrix = \[\[ "1 ", "0 ", "1 ", "0 ", "0 "\],\[ "1 ", "0 ", "1 ", "1 ", "1 "\],\[ "1...
dolphin
Please explain the following problem in detail and provide code in Objective-C: Given the `root` of a binary tree, return _the length of the **diameter** of the tree_. The **diameter** of a binary tree is the **length** of the longest path between any two nodes in a tree. This path may or may not pass through the `roo...
dolphin
translate this code to Object Pascal: ````mojo sub dfs($node, $parent, $xor_values, @tree) { my $xor_value = $xor_values[$node]; for my $child (@{$tree[$node]}) { if ($child != $parent) { $xor_value ^= dfs($child, $node, $xor_values, @tree); } } return $xor_value; } sub mini...
dolphin
Please explain the following problem in detail and provide code in Kotlin: Given an integer array `nums` that may contain duplicates, return _all possible_ _subsets_ _(the power set)_. The solution set **must not** contain duplicate subsets. Return the solution in **any order**. **Example 1:** **Input:** nums = \[1,...
dolphin
convert this code from PHP to javascript: ```php function longestLine($mat) { $rows = count($mat); $cols = count($mat[0]); $max_length = 0; $dp = array_fill(0, $rows, array_fill(0, $cols, array_fill(0, 4, 0))); for ($r = 0; $r < $rows; $r++) { for ($c = 0; $c < $cols; $c++) { if...
dolphin
convert this code from Groovy to Ruby: ```groovy def maxPalindromesSubstrings(String s, int k) { int n = s.length() if (n < k) { return 0 } int count = 0 boolean[][] dp = new boolean[n][n] for (int i = n - 1; i >= 0; i--) { for (int j = i; j < n; j++) { if (i == j) { dp[i][j] = true ...
dolphin
port this code to Visual Basic .NET: ```elixir defmodule Solution do def large_groups(s) do n = String.length(s) result = [] start = 0 for i <- 1..n do if String.at(s, i) != String.at(s, i-1) do if i-1 - start >= 2 do result = [result|[start, i-1]] end start = i...
dolphin
Please focus on the algorithm of this problem and provide code in Elixir: You are given a **0-indexed** array of **distinct** integers `nums`. There is an element in `nums` that has the **lowest** value and an element that has the **highest** value. We call them the **minimum** and **maximum** respectively. Your goal ...
dolphin
Please explain the following problem in detail and provide code in c++: You are given an array of integers `nums`. Perform the following steps: 1. Find **any** two **adjacent** numbers in `nums` that are **non-coprime**. 2. If no such numbers are found, **stop** the process. 3. Otherwise, delete the two numbers and...
dolphin
Please explain the following problem in detail and provide code in F#: There are `n` dominoes in a line, and we place each domino vertically upright. In the beginning, we simultaneously push some of the dominoes either to the left or to the right. After each second, each domino that is falling to the left pushes the a...
dolphin
translate this code to python: ```dart int paintGrid(int n) { int mod = 1000000007; int redCount = 6; int yellowCount = 6; int greenCount = 6; for (int i = 2; i <= n; i++) { int newRedCount = ((2 * redCount) % mod + (2 * yellowCount) % mod) % mod; int newYellowCount = ((2 * redCount) % mod + (2 * yell...
dolphin
Please explain the reasoning behind the following solution and provide code in Objective-C: 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, ...
dolphin
Please explain the reasoning behind the following solution and provide code in Visual Basic .NET: Given an integer array `nums` of length `n`, return `true` if there is a triplet `(i, j, k)` which satisfies the following conditions: * `0 < i, i + 1 < j, j + 1 < k < n - 1` * The sum of subarrays `(0, i - 1)`, `(i +...
dolphin
Please explain the following problem in detail and provide code in Fortran: You are given an integer `n`. Each number from `1` to `n` is grouped according to the sum of its digits. Return _the number of groups that have the largest size_. **Example 1:** **Input:** n = 13 **Output:** 4 **Explanation:** There are 9 g...
dolphin
convert this code from PHP to c++: ```php class Solution { function closestValue($root, $target) { $closest = $root->val; while ($root) { if (abs($target - $closest) > abs($target - $root->val)) { $closest = $root->val; } $root = ($target < $root->...
dolphin
Please focus on the algorithm of this problem and provide code in C#: You are given two strings `s1` and `s2` of equal length. A **string swap** is an operation where you choose two indices in a string (not necessarily different) and swap the characters at these indices. Return `true` _if it is possible to make both s...
dolphin
port this code to Scheme: ```go func countWays(s string) int { n := len(s) count := 0 for i := 0; i <= n-3; i++ { if s[i] != s[i+1] && s[i+1] != s[i+2] && s[i] != s[i+2] { count++ } } return count } ```
dolphin
Please write the following solution using Haskell: You are given a **0-indexed** integer array `nums` and a target element `target`. A **target index** is an index `i` such that `nums[i] == target`. Return _a list of the target indices of_ `nums` after _sorting_ `nums` _in **non-decreasing** order_. If there are no t...
dolphin
translate this code to Visual Basic .NET: ```fortran function simplifyExpression(expression, evalvars, evalints) result(res) character(*), intent(in) :: expression character(*), dimension(:), intent(in) :: evalvars integer, dimension(:), intent(in) :: evalints character(20) :: var integer :: i, j, k...
dolphin
port this code to java: ```pascal function longestPalindromeSubseq(word1, word2: string): integer; var n, m, i, j: integer; dp: array of array of integer; begin n := Length(word1); m := Length(word2); SetLength(dp, n + 1, m + 1); for i := 0 to n do dp[i][0] := 0; for j := 0 to m do dp[0][j] := 0;...
dolphin
Please focus on the efficiency of this problem and provide code in Go: You start at the cell `(rStart, cStart)` of an `rows x cols` grid facing east. The northwest corner is at the first row and column in the grid, and the southeast corner is at the last row and column. You will walk in a clockwise spiral shape to vis...
dolphin
convert this code to Go: ```lua function total_ways_to_split_ranges(ranges) local MOD = 10^9 + 7 table.sort(ranges, function(a, b) return a[2] < b[2] end) local overlapping, non_overlapping, prev_end = 0, 1, -1 for _, range in ipairs(ranges) do local start, e = range[1], range[2] if sta...
dolphin
convert this code from Ruby to Kotlin: ```ruby def min_flips(s) n = s.length s = s + s count = 0 for i in 0...n if s[i] == s[i+1] count += 1 end end return [count, n-count].min end ```
dolphin
port this code from Groovy to c++: ```groovy def countSteppingNumbers(low, high) { def results = [] for (int i = low; i <= high; i++) { int prev = -1 int j = i boolean is_stepping = true while (j > 0) { int digit = j % 10 if (prev != -1 && Math.abs(prev - ...
dolphin
translate this code to Perl: ```rust use std::collections::HashMap; fn delete_duplicate_folder(paths: Vec<Vec<String>>) -> Vec<Vec<String>> { let mut folder_counts: HashMap<String, i32> = HashMap::new(); for path in &paths { let path_string = format!("/{}", path.join("/")); *folder_counts.entr...
dolphin
translate this code from python to Lisp: ```python import heapq class KthLargest: def __init__(self, k: int, nums: List[int]): self.k = k self.min_heap = nums heapq.heapify(self.min_heap) while len(self.min_heap) > k: heapq.heappop(self.min_heap) def add(s...
dolphin
translate this code from java to Rust: ```java public int numPrimeArrangements(int n) { boolean[] isPrime = new boolean[n + 1]; Arrays.fill(isPrime, true); isPrime[0] = false; isPrime[1] = false; for (int i = 2; i * i <= n; i++) { if (isPrime[i]) { for (int j = i * i; j <= n; j +...
dolphin
Please explain the following problem in detail and provide code in Ruby: An axis-aligned rectangle is represented as a list `[x1, y1, x2, y2]`, where `(x1, y1)` is the coordinate of its bottom-left corner, and `(x2, y2)` is the coordinate of its top-right corner. Its top and bottom edges are parallel to the X-axis, and...
dolphin
Please explain the following problem in detail and provide code in Object Pascal: We are given a list `nums` of integers representing a list compressed with run-length encoding. Consider each adjacent pair of elements `[freq, val] = [nums[2*i], nums[2*i+1]]` (with `i >= 0`). For each such pair, there are `freq` elemen...
dolphin
Please explain the following problem in detail and provide code in Lua: Given an array of **distinct** integers `candidates` and a target integer `target`, return _a list of all **unique combinations** of_ `candidates` _where the chosen numbers sum to_ `target`_._ You may return the combinations in **any order**. The ...
dolphin
Please focus on the efficiency of this problem and provide code in TypeScript: You are given four integers, `m`, `n`, `introvertsCount`, and `extrovertsCount`. You have an `m x n` grid, and there are two types of people: introverts and extroverts. There are `introvertsCount` introverts and `extrovertsCount` extroverts....
dolphin
Please write the following solution using Scheme: 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 enclosed**. Return _the coor...
dolphin
Please explain the reasoning behind the following solution and provide code in Objective-C: Roman numerals are represented by seven different symbols: `I`, `V`, `X`, `L`, `C`, `D` and `M`. **Symbol** **Value** I 1 V 5 X 10 L 50 C 100 D 500 M...
dolphin
Please write the following solution using Elixir: You are given an integer array `nums` of length `n` where `nums` is a permutation of the integers in the range `[1, n]`. You are also given a 2D integer array `sequences` where `sequences[i]` is a subsequence of `nums`. Check if `nums` is the shortest possible and the ...
dolphin
Please explain the reasoning behind the following solution and provide code in Scala: You are given an integer array `nums`. You have an integer array `arr` of the same length with all values set to `0` initially. You also have the following `modify` function: You want to use the modify function to covert `arr` to `nu...
dolphin
Please focus on the efficiency of this problem and provide code in Erlang: Let `f(x)` be the number of zeroes at the end of `x!`. Recall that `x! = 1 * 2 * 3 * ... * x` and by convention, `0! = 1`. * For example, `f(3) = 0` because `3! = 6` has no zeroes at the end, while `f(11) = 2` because `11! = 39916800` has two...
dolphin
convert this code to Scala: ```pascal function maximize_sum(matrix: array of array of integer): integer; var n, negatives, curr_val, absolute_val, min_val, i, j: integer; sum: integer = 0; begin n := Length(matrix); negatives := 0; min_val := MaxInt; for i := 0 to n - 1 do begin for j := 0 to n - 1 do...
dolphin
Please focus on the functionality of this problem and provide code in Mojo: In MATLAB, there is a handy function called `reshape` which can reshape an `m x n` matrix into a new one with a different size `r x c` keeping its original data. You are given an `m x n` matrix `mat` and two integers `r` and `c` representing t...
dolphin
Please write the following solution using Haskell: You are given an integer array `jobs`, where `jobs[i]` is the amount of time it takes to complete the `ith` job. There are `k` workers that you can assign jobs to. Each job should be assigned to **exactly** one worker. The **working time** of a worker is the sum of th...
dolphin
convert this code to Julia: ```go func shiftGrid(grid [][]int, k int) [][]int { m, n := len(grid), len(grid[0]) k = k % (m * n) if k == 0 { return grid } flat := flatten(grid) shifted := shiftArray(flat, k) shiftedGrid := reshape(shifted, m, n) return shiftedGrid } func flatte...
dolphin
port this code from Lua to java: ```lua function RLEIterator(encoded) local encoding = encoded local curr_idx = 1 function next(n) while n > 0 and curr_idx <= #encoding do if encoding[curr_idx] >= n then encoding[curr_idx] = encoding[curr_idx] - n ret...
dolphin
Please write the following solution using Swift: You are given two strings `current` and `correct` representing two **24-hour times**. 24-hour times are formatted as `"HH:MM "`, where `HH` is between `00` and `23`, and `MM` is between `00` and `59`. The earliest 24-hour time is `00:00`, and the latest is `23:59`. In ...
dolphin
Please write the following solution using Julia: Given an **empty** set of intervals, implement a data structure that can: * **Add** an interval to the set of intervals. * **Count** the number of integers that are present in **at least one** interval. Implement the `CountIntervals` class: * `CountIntervals()` ...
dolphin
Please focus on the efficiency of this problem and provide code in Mojo: Given an integer array `nums` and an integer `val`, remove all occurrences of `val` in `nums` [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm). The order of the elements may be changed. Then return _the number of elements in_ `nums...
dolphin
port this code to Scala: ```vb.net Public Function DigitSum(n As Long) As Integer Dim sum As Integer = 0 While n > 0 sum += n Mod 10 n \= 10 End While Return sum End Function Public Function MinimumBeautiful(n As Long, target As Integer) As Long Dim x As Long = 0 While DigitSum(...
dolphin
Please write the following solution using Ruby: A website domain `"discuss.leetcode.com "` consists of various subdomains. At the top level, we have `"com "`, at the next level, we have `"leetcode.com "` and at the lowest level, `"discuss.leetcode.com "`. When we visit a domain like `"discuss.leetcode.com "`, we will a...
dolphin
Please explain the reasoning behind the following solution and provide code in c++: You have a graph of `n` nodes. You are given an integer `n` and an array `edges` where `edges[i] = [ai, bi]` indicates that there is an edge between `ai` and `bi` in the graph. Return _the number of connected components in the graph_. ...
dolphin
port this code to Elixir: ```swift func numberOfArithmeticSlices(_ nums: [Int]) -> Int { var res = 0 let n = nums.count var dp = [Dictionary<Int, Int>](repeating: Dictionary<Int, Int>(), count: n) for i in 0..<n { for j in 0..<i { let diff = nums[i] - nums[j] if diff <= ...
dolphin
Please explain the reasoning behind the following solution and provide code in java: You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. Return _the single element that appears only once_. Your solution must run in `O(l...
dolphin
convert this code from Visual Basic .NET to Clojure: ```vb.net Function MaxDistance(commands As Integer(), obstacles As Integer()()) As Integer Dim x As Integer = 0 Dim y As Integer = 0 Dim direction As Integer = 0 Dim dx As Integer() = {0, 1, 0, -1} Dim dy As Integer() = {1, 0, -1, 0} Dim obsta...
dolphin
Please focus on the algorithm of this problem and provide code in Lua: Design a logger system that receives a stream of messages along with their timestamps. Each **unique** message should only be printed **at most every 10 seconds** (i.e. a message printed at timestamp `t` will prevent other identical messages from be...
dolphin
Please explain the following problem in detail and provide code in Fortran: You are given **two identical** eggs and you have access to a building with `n` floors labeled from `1` to `n`. You know that there exists a floor `f` where `0 <= f <= n` such that any egg dropped at a floor **higher** than `f` will **break**,...
dolphin
Please write the following solution using Rust: Given two non-negative integers, `num1` and `num2` represented as string, return _the sum of_ `num1` _and_ `num2` _as a string_. You must solve the problem without using any built-in library for handling large integers (such as `BigInteger`). You must also not convert th...
dolphin
convert this code to java: ```R sum_base <- function(n, k) { s <- 0 while (n > 0) { s <- s + (n %% k) n <- floor(n / k) } return(s) } ```
dolphin
translate this code from C# to Clojure: ```csharp using System.Collections.Generic; public class Solution { public int MinOperations(int[] coins, int[][] edges) { var adj = new Dictionary<int, List<int>>(); for (int i = 0; i < coins.Length; i++) { adj[i] = new List<int>(); } ...
dolphin
Please explain the following problem in detail and provide code in c++: You are given `n` tables represented with two arrays `names` and `columns`, where `names[i]` is the name of the `ith` table and `columns[i]` is the number of columns of the `ith` table. You should be able to perform the following **operations**: ...
dolphin
convert this code from Scheme to Clojure: ```scheme (define (lenLongestFibSubseq arr) (define index (let loop ((lst arr) (acc '()) (count 0)) (if (null? lst) acc (loop (cdr lst) (cons (cons (car lst) count) acc) (+ count 1))))) (define longest (make-hash)) (define ans 0)...
dolphin
Please explain the following problem in detail and provide code in Erlang: Given the **API** `rand7()` that generates a uniform random integer in the range `[1, 7]`, write a function `rand10()` that generates a uniform random integer in the range `[1, 10]`. You can only call the API `rand7()`, and you shouldn't call an...
dolphin
Please focus on the functionality of this problem and provide code in python: Given the `root` of a Binary Search Tree (BST), return _the minimum absolute difference between the values of any two different nodes in the tree_. **Example 1:** **Input:** root = \[4,2,6,1,3\] **Output:** 1 **Example 2:** **Input:** roo...
dolphin
Please write the following solution using Groovy: You are given a **0-indexed** integer array `nums`. Rearrange the values of `nums` according to the following rules: 1. Sort the values at **odd indices** of `nums` in **non-increasing** order. * For example, if `nums = [4,**1**,2,**3**]` before this step, it be...
dolphin
Please explain the reasoning behind the following solution and provide code in C#: You are given a **0-indexed** array of strings `garbage` where `garbage[i]` represents the assortment of garbage at the `ith` house. `garbage[i]` consists only of the characters `'M'`, `'P'` and `'G'` representing one unit of metal, pape...
dolphin