instruction_seed
stringlengths
29
40.5k
source
stringclasses
6 values
Please write the following solution using R: Given the root of a binary tree and two integers `p` and `q`, return _the **distance** between the nodes of value_ `p` _and value_ `q` _in the tree_. The **distance** between two nodes is the number of edges on the path from one to the other. **Example 1:** **Input:** roo...
dolphin
Please write the following solution using C#: Given the `root` of a binary search tree (BST) with duplicates, return _all the [mode(s)](https://en.wikipedia.org/wiki/Mode_(statistics)) (i.e., the most frequently occurred element) in it_. If the tree has more than one mode, return them in **any order**. Assume a BST i...
dolphin
Please focus on the efficiency of this problem and provide code in Swift: Given an array `nums` of integers, a _move_ consists of choosing any element and **decreasing it by 1**. An array `A` is a _zigzag array_ if either: * Every even-indexed element is greater than adjacent elements, ie. `A[0] > A[1] < A[2] > A[3...
dolphin
Please explain the following problem in detail and provide code in F#: An **IP address** is a formatted 32-bit unsigned integer where each group of 8 bits is printed as a decimal number and the dot character `'.'` splits the groups. * For example, the binary number `00001111 10001000 11111111 01101011` (spaces added...
dolphin
translate this code from Fortran to C#: ```fortran recursive function minRemovals(i, j, arr, dp) result(ans) integer, intent(in) :: i, j, arr(:,:) integer, intent(inout) :: dp(:,:) integer :: k, ans if (i > j) then ans = 0 elseif (i == j) then ans = 1 elseif (dp(i,j) /= -1) then...
dolphin
Please write the following solution using TypeScript: Given an expression such as `expression = "e + 8 - a + 5 "` and an evaluation map such as `{ "e ": 1}` (given in terms of `evalvars = [ "e "]` and `evalints = [1]`), return a list of tokens representing the simplified expression, such as `[ "-1*a ", "14 "]` * An ...
dolphin
Please explain the following problem in detail and provide code in Erlang: Given an integer array `nums` and two integers `k` and `p`, return _the number of **distinct subarrays** which have **at most**_ `k` _elements divisible by_ `p`. Two arrays `nums1` and `nums2` are said to be **distinct** if: * They are of **...
dolphin
Please explain the following problem in detail and provide code in Objective-C: You are given an `m x n` integer matrix `grid`, where you can move from a cell to any adjacent cell in all `4` directions. Return _the number of **strictly** **increasing** paths in the grid such that you can start from **any** cell and en...
dolphin
Please explain the reasoning behind the following solution and provide code in ANSI C: 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
port this code to Go: ```lua function matrix_block_sum(mat, k) local m, n = #mat, #mat[1] local answer = {} for i=1,m do answer[i] = {} for j=1,n do answer[i][j] = 0 local top = math.max(i-k, 1) local left = math.max(j-k, 1) local bottom = math...
dolphin
Please write the following solution using Erlang: You are given a **0-indexed** integer array `nums` and two integers `key` and `k`. A **k-distant index** is an index `i` of `nums` for which there exists at least one index `j` such that `|i - j| <= k` and `nums[j] == key`. Return _a list of all k-distant indices sorte...
dolphin
Please explain the reasoning behind the following solution and provide code in Elixir: There is an **undirected** connected tree with `n` nodes labeled from `1` to `n` and `n - 1` edges. You are given the integer `n`. The parent node of a node with a label `v` is the node with the label `floor (v / 2)`. The root of the...
dolphin
convert this code to Julia: ```lua function count_homogenous(s) MOD = 1000000007 count, total = 1, 0 for i = 2, #s do count = s:sub(i, i) == s:sub(i-1, i-1) and count+1 or 1 total = (total + count) % MOD end return (total + count) % MOD end ```
dolphin
convert this code to Clojure: ```lisp (defun max-sum-of-three-subarrays (nums k) (let* ((n (length nums)) (sums (make-array (- n k 1) :initial-element 0)) (left (make-array n :initial-element 0)) (right (make-array n :initial-element 0))) (let ((acc-sum 0)) (dotimes (i n) ...
dolphin
Please explain the following problem in detail and provide code in Scheme: We are given a list `schedule` of employees, which represents the working time for each employee. Each employee has a list of non-overlapping `Intervals`, and these intervals are in sorted order. Return the list of finite intervals representin...
dolphin
Please explain the reasoning behind the following solution and provide code in Haskell: You are given an `m x n` integer matrix `grid`​​​. A **rhombus sum** is the sum of the elements that form **the** **border** of a regular rhombus shape in `grid`​​​. The rhombus must have the shape of a square rotated 45 degrees wi...
dolphin
port this code to Julia: ```go func visiblePeople(heights [][]int) [][]int { m, n := len(heights), len(heights[0]) answer := make([][]int, m) for i := range answer { answer[i] = make([]int, n) } for i := 0; i < m; i++ { for j := 0; j < n; j++ { var rightCount int ...
dolphin
Please write the following solution using python: Given the `root` of a binary tree, the level of its root is `1`, the level of its children is `2`, and so on. Return the **smallest** level `x` such that the sum of all the values of nodes at level `x` is **maximal**. **Example 1:** **Input:** root = \[1,7,0,7,-8,nul...
dolphin
Please focus on the efficiency of this problem and provide code in PHP: You are given a **directed** graph of `n` nodes numbered from `0` to `n - 1`, where each node has **at most one** outgoing edge. The graph is represented with a given **0-indexed** array `edges` of size `n`, indicating that there is a directed edg...
dolphin
Please explain the following problem in detail and provide code in ANSI C: Given two arrays of strings `list1` and `list2`, find the **common strings with the least index sum**. A **common string** is a string that appeared in both `list1` and `list2`. A **common string with the least index sum** is a common string s...
dolphin
Please focus on the functionality of this problem and provide code in Object Pascal: Given a list of non-negative integers `nums`, arrange them such that they form the largest number and return it. Since the result may be very large, so you need to return a string instead of an integer. **Example 1:** **Input:** num...
dolphin
Please write the following solution using Julia: 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 use each sticker more than...
dolphin
Please focus on the algorithm of this problem and provide code in TypeScript: You are given two **0-indexed** integer arrays `nums1` and `nums2` of length `n`. A range `[l, r]` (**inclusive**) where `0 <= l <= r < n` is **balanced** if: * For every `i` in the range `[l, r]`, you pick either `nums1[i]` or `nums2[i]`...
dolphin
convert this code from Mojo to Dart: ```mojo sub minimum_distance(word) { sub dp(first, second, pos) { if pos == length(word) { return 0; } my $ans = Inf; for my $i in [$first, $second] { if $i != -1 { my $dx = abs(ord(word[$pos]) - ord(word[$i])) % 6; ...
dolphin
translate this code to Clojure: ```erlang -module(three_equal_parts). -export([three_equal_parts/1]). three_equal_parts(Arr) -> N = length(Arr), OnesCount = lists:sum(Arr), case OnesCount rem 3 of 0 -> OnesInEachPart = OnesCount div 3, ZerosCount = 0, FoundFirst ...
dolphin
convert this code to Scala: ``` (define (total-area ax1 ay1 ax2 ay2 bx1 by1 bx2 by2) (let ((area1 (* (- ax2 ax1) (- ay2 ay1))) (area2 (* (- bx2 bx1) (- by2 by1))) (overlap-width (max 0 (- (min ax2 bx2) (max ax1 bx1)))) (overlap-height (max 0 (- (min ay2 by2) (max ay1 by1))))) (- (+ area1 a...
dolphin
Please explain the reasoning behind the following solution and provide code in Scala: You are given an integer array `coins` representing coins of different denominations and an integer `amount` representing a total amount of money. Return _the number of combinations that make up that amount_. If that amount of money ...
dolphin
port this code from Visual Basic .NET to Go: ```vb.net Function IsCovered(ranges As List(Of List(Of Integer)), left As Integer, right As Integer) As Boolean Dim covered(50) As Integer For Each _range In ranges For i = _range(0) To _range(1) covered(i) = 1 Next Next For i = le...
dolphin
port this code to R: ```go func sequentialDigits(low int, high int) []int { result := []int{} for i := 1; i < 10; i++ { number := i for j := i + 1; j < 10; j++ { number = number * 10 + j if low <= number && number <= high { result = append(result, number) ...
dolphin
convert this code from Ruby to Groovy: ```ruby def exist(board, word) m, n = board.length, board[0].length def dfs(i, j, k) return false if i < 0 || i >= m || j < 0 || j >= n || board[i][j] != word[k] return true if k == word.length - 1 temp, board[i][j] = board[i][j], '-' ...
dolphin
Please explain the reasoning behind the following solution and provide code in Object Pascal: Given an integer array `arr`, remove a subarray (can be empty) from `arr` such that the remaining elements in `arr` are **non-decreasing**. Return _the length of the shortest subarray to remove_. A **subarray** is a contiguo...
dolphin
Please focus on the efficiency of this problem and provide code in ANSI C: An integer `x` is **numerically balanced** if for every digit `d` in the number `x`, there are **exactly** `d` occurrences of that digit in `x`. Given an integer `n`, return _the **smallest numerically balanced** number **strictly greater** tha...
dolphin
convert this code to Objective-C: ```typescript function greatestNumberOfCandies(candies: number[], extraCandies: number): boolean[] { const n = candies.length; const maxCandies = Math.max(...candies); const result = new Array(n); for (let i = 0; i < n; i++) { result[i] = candies[i] + extraCandi...
dolphin
Please focus on the functionality of this problem and provide code in F#: 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 m...
dolphin
Please explain the following problem in detail and provide code in Haskell: Given an array of integers `nums`, sort the array in ascending order and return it. You must solve the problem **without using any built-in** functions in `O(nlog(n))` time complexity and with the smallest space complexity possible. **Example...
dolphin
translate this code from Perl to Rust: ```perl sub minimum_moves_to_make_unique { my ($nums) = @_; my $n = scalar @$nums; my @freq = (0) x (max(@$nums) + 1); foreach my $i (0..$n-1) { $freq[$nums->[$i]] += 1; } my $moves = 0; foreach my $i (0..$n-1) { if ($freq[$nums->[$i]] >...
dolphin
Please explain the reasoning behind the following solution and provide code in Dart: The **Fibonacci numbers**, commonly denoted `F(n)` form a sequence, called the **Fibonacci sequence**, such that each number is the sum of the two preceding ones, starting from `0` and `1`. That is, F(0) = 0, F(1) = 1 F(n) = F(n - 1) ...
dolphin
Please write the following solution using c++: **Run-length encoding** is a compression algorithm that allows for an integer array `nums` with many segments of **consecutive repeated** numbers to be represented by a (generally smaller) 2D array `encoded`. Each `encoded[i] = [vali, freqi]` describes the `ith` segment of...
dolphin
Please write the following solution using Fortran: There are `buckets` buckets of liquid, where **exactly one** of the buckets is poisonous. To figure out which one is poisonous, you feed some number of (poor) pigs the liquid to see whether they will die or not. Unfortunately, you only have `minutesToTest` minutes to d...
dolphin
convert this code from Ruby to Lisp: ```ruby def remove_stones(stones) row_groups = Hash.new(0) col_groups = Hash.new(0) group_count = 0 groups = Hash.new { |h, k| h[k] = [] } stones.each do |x, y| if row_groups[x].zero? row_groups[x] = group_count group_cou...
dolphin
Please explain the following problem in detail and provide code in Lua: An array is **monotonic** if it is either monotone increasing or monotone decreasing. An array `nums` is monotone increasing if for all `i <= j`, `nums[i] <= nums[j]`. An array `nums` is monotone decreasing if for all `i <= j`, `nums[i] >= nums[j]...
dolphin
Please write the following solution using c++: You are given an integer array `nums`. We call a subset of `nums` **good** if its product can be represented as a product of one or more **distinct prime** numbers. * For example, if `nums = [1, 2, 3, 4]`: * `[2, 3]`, `[1, 2, 3]`, and `[1, 3]` are **good** subsets...
dolphin
Please write the following solution using Dart: Given an integer array nums and an integer k, return `true` _if_ `nums` _has a **good subarray** or_ `false` _otherwise_. A **good subarray** is a subarray where: * its length is **at least two**, and * the sum of the elements of the subarray is a multiple of `k`. ...
dolphin
Please focus on the functionality of this problem and provide code in Fortran: We distribute some number of `candies`, to a row of **`n = num_people`** people in the following way: We then give 1 candy to the first person, 2 candies to the second person, and so on until we give `n` candies to the last person. Then, w...
dolphin
Please explain the reasoning behind the following solution and provide code in Ruby: Given a string `s` and a character `letter`, return _the **percentage** of characters in_ `s` _that equal_ `letter` _**rounded down** to the nearest whole percent._ **Example 1:** **Input:** s = "foobar ", letter = "o " **Output:**...
dolphin
port this code from Fortran to C#: ```fortran function isInterleave(s1, s2, s3) result(ans) character(*), intent(in) :: s1, s2, s3 logical :: ans integer :: m, n, i, j logical, dimension(:,:), allocatable :: dp m = len(s1) n = len(s2) if (m + n) /= len(s3) then ans = .false. ...
dolphin
Please focus on the algorithm of this problem and provide code in Groovy: There are `n` persons numbered from `0` to `n - 1` and a door. Each person can enter or exit through the door once, taking one second. You are given a **non-decreasing** integer array `arrival` of size `n`, where `arrival[i]` is the arrival time...
dolphin
Please focus on the efficiency of this problem and provide code in Perl: Given a string `s` and an integer `k`, rearrange `s` such that the same characters are **at least** distance `k` from each other. If it is not possible to rearrange the string, return an empty string `" "`. **Example 1:** **Input:** s = "aabbcc...
dolphin
Please write the following solution using java: You are given a **perfect binary tree** where all leaves are on the same level, and every parent has two children. The binary tree has the following definition: struct Node { int val; Node \*left; Node \*right; Node \*next; } Populate each next pointer to point ...
dolphin
Please write the following solution using java: You are given two **0-indexed** integer arrays `nums` and `multipliers` of size `n` and `m` respectively, where `n >= m`. You begin with a score of `0`. You want to perform **exactly** `m` operations. On the `ith` operation (**0-indexed**) you will: * Choose one integ...
dolphin
Please explain the reasoning behind the following solution and provide code in c++: Given `n` points on a 1-D plane, where the `ith` point (from `0` to `n-1`) is at `x = i`, find the number of ways we can draw **exactly** `k` **non-overlapping** line segments such that each segment covers two or more points. The endpoi...
dolphin
Please explain the reasoning behind the following solution and provide code in Go: You are given an array of variable pairs `equations` and an array of real numbers `values`, where `equations[i] = [Ai, Bi]` and `values[i]` represent the equation `Ai / Bi = values[i]`. Each `Ai` or `Bi` is a string that represents a sin...
dolphin
Please explain the reasoning behind the following solution and provide code in Elixir: There is a forest with an unknown number of rabbits. We asked n rabbits **"How many rabbits have the same color as you? "** and collected the answers in an integer array `answers` where `answers[i]` is the answer of the `ith` rabbit....
dolphin
Please explain the following problem in detail and provide code in java: You have `n` computers. You are given the integer `n` and a **0-indexed** integer array `batteries` where the `ith` battery can **run** a computer for `batteries[i]` minutes. You are interested in running **all** `n` computers **simultaneously** u...
dolphin
Please explain the reasoning behind the following solution and provide code in Rust: There is a **family tree** rooted at `0` consisting of `n` nodes numbered `0` to `n - 1`. You are given a **0-indexed** integer array `parents`, where `parents[i]` is the parent for node `i`. Since node `0` is the **root**, `parents[0]...
dolphin
convert this code to Ruby: ```csharp public class Solution { public int[][] SplitPainting(int[][] segments) { Dictionary<int, int> line = new Dictionary<int, int>(); foreach (int[] s in segments) { int start = s[0]; int end = s[1]; int color = s[2]; if...
dolphin
Please write the following solution using Ruby: Given an array of integers `nums` and an integer `threshold`, we will choose a positive integer `divisor`, divide all the array by it, and sum the division's result. Find the **smallest** `divisor` such that the result mentioned above is less than or equal to `threshold`....
dolphin
Please explain the reasoning behind the following solution and provide code in Dart: You are given an integer array `cookies`, where `cookies[i]` denotes the number of cookies in the `ith` bag. You are also given an integer `k` that denotes the number of children to distribute **all** the bags of cookies to. All the co...
dolphin
Please write the following solution using PHP: You are given an integer array `nums` of size `n`. You are asked to solve `n` queries for each integer `i` in the range `0 <= i < n`. To solve the `ith` query: 1. Find the **minimum value** in each possible subarray of size `i + 1` of the array `nums`. 2. Find the **ma...
dolphin
Please explain the following problem in detail and provide code in C#: Given `2n` balls of `k` distinct colors. You will be given an integer array `balls` of size `k` where `balls[i]` is the number of balls of color `i`. All the balls will be **shuffled uniformly at random**, then we will distribute the first `n` ball...
dolphin
Please explain the reasoning behind the following solution and provide code in Rust: 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 **mini...
dolphin
port this code to R: ```lua function findMedianSortedArrays(nums1, nums2) if #nums1 > #nums2 then return findMedianSortedArrays(nums2, nums1) end local x, y = #nums1, #nums2 local low, high = 0, x while low <= high do local partition_x = math.floor((low + high) / 2) ...
dolphin
port this code from Lua to Julia: ```lua function findClosestElements(arr, k, x) local left = 1 local right = #arr - k + 1 while left < right do local mid = left + math.floor((right - left) / 2) if x - arr[mid] > arr[mid + k - 1] - x then left = mid + 1 else right = mid end end ...
dolphin
Please write the following solution using c++: Given a binary string `s` and a positive integer `n`, return `true` _if the binary representation of all the integers in the range_ `[1, n]` _are **substrings** of_ `s`_, or_ `false` _otherwise_. A **substring** is a contiguous sequence of characters within a string. **E...
dolphin
Please explain the reasoning behind the following solution and provide code in PHP: Given the `root` of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST. As a reminder, a _binary...
dolphin
convert this code from Julia to Lua: ```julia function is_perfect_square(num::Int)::Bool if num < 2 return true end left, right = 2, div(num, 2) while left <= right mid = left + div(right - left, 2) square = mid * mid if square == num return true elsei...
dolphin
Please explain the following problem in detail and provide code in Go: You are given a string `s` consisting of only lowercase English letters. In one operation, you can: * Delete **the entire string** `s`, or * Delete the **first** `i` letters of `s` if the first `i` letters of `s` are **equal** to the following ...
dolphin
Please explain the reasoning behind the following solution and provide code in Julia: Given an integer array `nums`, return _the number of all the **arithmetic subsequences** of_ `nums`. A sequence of numbers is called arithmetic if it consists of **at least three elements** and if the difference between any two conse...
dolphin
Please explain the following problem in detail and provide code in java: You are given a **0-indexed** 2D integer array `grid` of size `m x n` which represents a field. Each cell has one of three values: * `0` represents grass, * `1` represents fire, * `2` represents a wall that you and fire cannot pass through....
dolphin
Please explain the following problem in detail and provide code in Lua: 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,2,2...
dolphin
Please explain the reasoning behind the following solution and provide code in Kotlin: Given two strings `s` and `t`, return _the number of distinct_ **_subsequences_** _of_ `s` _which equals_ `t`. The test cases are generated so that the answer fits on a 32-bit signed integer. **Example 1:** **Input:** s = "rabbbi...
dolphin
Please explain the reasoning behind the following solution and provide code in Object Pascal: You are given an array `nums` that consists of non-negative integers. Let us define `rev(x)` as the reverse of the non-negative integer `x`. For example, `rev(123) = 321`, and `rev(120) = 21`. A pair of indices `(i, j)` is **n...
dolphin
Please focus on the efficiency of this problem and provide code in Clojure: Given an `m x n` matrix `mat`, return _an array of all the elements of the array in a diagonal order_. **Example 1:** **Input:** mat = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\] **Output:** \[1,2,4,7,5,3,6,8,9\] **Example 2:** **Input:** mat = \[\[1...
dolphin
Please focus on the efficiency of this problem and provide code in Kotlin: Given a string `s` of lowercase letters, you need to find the maximum number of **non-empty** substrings of `s` that meet the following conditions: 1. The substrings do not overlap, that is for any two substrings `s[i..j]` and `s[x..y]`, eithe...
dolphin
Please write the following solution using Perl: Given a binary array `nums`, you should delete one element from it. Return _the size of the longest non-empty subarray containing only_ `1`_'s in the resulting array_. Return `0` if there is no such subarray. **Example 1:** **Input:** nums = \[1,1,0,1\] **Output:** 3 *...
dolphin
Please explain the reasoning behind the following solution and provide code in Rust: You are given a **0-indexed** integer array `nums` of length `n`. `nums` contains a **valid split** at index `i` if the following are true: * The sum of the first `i + 1` elements is **greater than or equal to** the sum of the last...
dolphin
Please explain the following problem in detail and provide code in Dart: Let's say a positive integer is a **super-palindrome** if it is a palindrome, and it is also the square of a palindrome. Given two positive integers `left` and `right` represented as strings, return _the number of **super-palindromes** integers i...
dolphin
convert this code from PHP to R: ```php class TreeNode { public $val; public $left; public $right; function __construct($val = 0, $left = null, $right = null) { $this->val = $val; $this->left = $left; $this->right = $right; } } function all_possible_FBT($n) { if ($n % 2...
dolphin
Please explain the following problem in detail and provide code in Object Pascal: You are given the `head` of a linked list with `n` nodes. For each node in the list, find the value of the **next greater node**. That is, for each node, find the value of the first node that is next to it and has a **strictly larger** v...
dolphin
Please explain the following problem in detail and provide code in Clojure: A **fancy string** is a string where no **three** **consecutive** characters are equal. Given a string `s`, delete the **minimum** possible number of characters from `s` to make it **fancy**. Return _the final string after the deletion_. It c...
dolphin
Please write the following solution using C#: In a string composed of `'L'`, `'R'`, and `'X'` characters, like `"RXXLRXRXL "`, a move consists of either replacing one occurrence of `"XL "` with `"LX "`, or replacing one occurrence of `"RX "` with `"XR "`. Given the starting string `start` and the ending string `end`, r...
dolphin
Please explain the reasoning behind the following solution and provide code in Julia: You are given an integer array `deck` where `deck[i]` represents the number written on the `ith` card. Partition the cards into **one or more groups** such that: * Each group has **exactly** `x` cards where `x > 1`, and * All th...
dolphin
convert this code to Rust: ```fsharp let climbStairs n = if n <= 2 then n else let mutable a = 1 let mutable b = 2 for i in 3..n do let temp = b b <- a + b a <- temp b ```
dolphin
Please explain the following problem in detail and provide code in Scheme: The **variance** of a string is defined as the largest difference between the number of occurrences of **any** `2` characters present in the string. Note the two characters may or may not be the same. Given a string `s` consisting of lowercase ...
dolphin
Please focus on the functionality of this problem and provide code in C#: You are given two string arrays, `queries` and `dictionary`. All words in each array comprise of lowercase English letters and have the same length. In one **edit** you can take a word from `queries`, and change any letter in it to any other let...
dolphin
Please explain the following problem in detail and provide code in Scheme: You are given two strings `a` and `b` of the same length. Choose an index and split both strings **at the same index**, splitting `a` into two strings: `aprefix` and `asuffix` where `a = aprefix + asuffix`, and splitting `b` into two strings: `b...
dolphin
convert this code to ANSI C: ```vb.net Function IsAlienSorted(words As String(), order As String) As Boolean Dim alienOrder As New Dictionary(Of Char, Integer) For i As Integer = 0 To order.Length - 1 alienOrder.Add(order(i), i) Next For i As Integer = 1 To words.Length - 1 For j As Int...
dolphin
port this code to Haskell: ```csharp using System; using System.Collections.Generic; public class TreeNode { public int val; public TreeNode left; public TreeNode right; public TreeNode(int x) { val = x; } } public class Solution { public string ShortestPath(TreeNode root, int startValue, int dest...
dolphin
Please explain the following problem in detail and provide code in Ruby: 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 following problem in detail and provide code in Object Pascal: Given a string `queryIP`, return `"IPv4 "` if IP is a valid IPv4 address, `"IPv6 "` if IP is a valid IPv6 address or `"Neither "` if IP is not a correct IP of any type. **A valid IPv4** address is an IP in the form `"x1.x2.x3.x4 "` where...
dolphin
port this code from Lisp to python: ```lisp (defun num-decodings (s) (let* ((MOD (expt 10 9) 7) (n (length s)) (dp (make-array (1+ n) :initial-element 0))) (setf (aref dp 0) 1) (setf (aref dp 1) (if (char-equal (aref s 0) #\*) 9 (if (char-equal (aref s 0...
dolphin
Please explain the reasoning behind the following solution and provide code in Swift: You are given a **directed** graph of `n` nodes numbered from `0` to `n - 1`, where each node has **at most one** outgoing edge. The graph is represented with a given **0-indexed** array `edges` of size `n`, indicating that there is ...
dolphin
Please explain the reasoning behind the following solution and provide code in Swift: You are given a **0-indexed** string `s` that has lowercase English letters in its **even** indices and digits in its **odd** indices. There is a function `shift(c, x)`, where `c` is a character and `x` is a digit, that returns the `...
dolphin
Please write the following solution using Haskell: You are given a 2D integer array `groups` of length `n`. You are also given an integer array `nums`. You are asked if you can choose `n` **disjoint** subarrays from the array `nums` such that the `ith` subarray is equal to `groups[i]` (**0-indexed**), and if `i > 0`, ...
dolphin
translate this code from Groovy to Clojure: ```groovy def matching_cards(cards) { def n = cards.size() def last_occurrence = [:] def result = -1 for (int i = 0; i < n; i++) { if (last_occurrence.containsKey(cards[i])) { result = (i - last_occurrence[cards[i]]) break ...
dolphin
Please explain the reasoning behind the following solution and provide code in python: You are given a circle represented as `(radius, xCenter, yCenter)` and an axis-aligned rectangle represented as `(x1, y1, x2, y2)`, where `(x1, y1)` are the coordinates of the bottom-left corner, and `(x2, y2)` are the coordinates of...
dolphin
Please explain the following problem in detail and provide code in Haskell: The **boundary** of a binary tree is the concatenation of the **root**, the **left boundary**, the **leaves** ordered from left-to-right, and the **reverse order** of the **right boundary**. The **left boundary** is the set of nodes defined by...
dolphin
Please explain the reasoning behind the following solution and provide code in Julia: You are given an array of characters `letters` that is sorted in **non-decreasing order**, and a character `target`. There are **at least two different** characters in `letters`. Return _the smallest character in_ `letters` _that is ...
dolphin
Please explain the following problem in detail and provide code in Groovy: You are given an integer `n`, the number of nodes in a directed graph where the nodes are labeled from `0` to `n - 1`. Each edge is red or blue in this graph, and there could be self-edges and parallel edges. You are given two arrays `redEdges`...
dolphin
Please write the following solution using java: You are given a string `s` consisting of digits from `1` to `9` and an integer `k`. A partition of a string `s` is called **good** if: * Each digit of `s` is part of **exactly** one substring. * The value of each substring is less than or equal to `k`. Return _the ...
dolphin