instruction_seed
stringlengths
29
40.5k
source
stringclasses
6 values
Please focus on the functionality of this problem and provide code in c++: Given an integer array `nums` and an integer `k`, return _the number of **subarrays** of_ `nums` _where the greatest common divisor of the subarray's elements is_ `k`. A **subarray** is a contiguous non-empty sequence of elements within an arra...
dolphin
Please explain the following problem in detail and provide code in Elixir: The **bitwise AND** of an array `nums` is the bitwise AND of all integers in `nums`. * For example, for `nums = [1, 5, 3]`, the bitwise AND is equal to `1 & 5 & 3 = 1`. * Also, for `nums = [7]`, the bitwise AND is `7`. You are given an arr...
dolphin
Please focus on the efficiency of this problem and provide code in java: Given a signed 32-bit integer `x`, return `x` _with its digits reversed_. If reversing `x` causes the value to go outside the signed 32-bit integer range `[-231, 231 - 1]`, then return `0`. **Assume the environment does not allow you to store 64-...
dolphin
Please explain the following problem in detail and provide code in Perl: 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...
dolphin
Please explain the following problem in detail and provide code in Go: You are given an array of strings `words` and a string `chars`. A string is **good** if it can be formed by characters from chars (each character can only be used once). Return _the sum of lengths of all good strings in words_. **Example 1:** **...
dolphin
Please focus on the efficiency of this problem and provide code in TypeScript: You are given an **integer** array `pref` of size `n`. Find and return _the array_ `arr` _of size_ `n` _that satisfies_: * `pref[i] = arr[0] ^ arr[1] ^ ... ^ arr[i]`. Note that `^` denotes the **bitwise-xor** operation. It can be proven...
dolphin
Please focus on the functionality of this problem and provide code in PHP: Given an integer array `arr` of **distinct** integers and an integer `k`. A game will be played between the first two elements of the array (i.e. `arr[0]` and `arr[1]`). In each round of the game, we compare `arr[0]` with `arr[1]`, the larger i...
dolphin
convert this code to F#: ```javascript function numTilePossibilities(tiles) { const freq = new Array(26).fill(0); for (const c of tiles) { freq[c.charCodeAt(0) - 'A'.charCodeAt(0)]++; } function dfs(freq) { let result = 0; for (let i = 0; i < 26; i++) { if (freq[i] >...
dolphin
Please focus on the functionality of this problem and provide code in java: 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 of the elements tha...
dolphin
Please explain the reasoning behind the following solution and provide code in Clojure: Given a positive integer `k`, you need to find the **length** of the **smallest** positive integer `n` such that `n` is divisible by `k`, and `n` only contains the digit `1`. Return _the **length** of_ `n`. If there is no such `n`,...
dolphin
Please explain the following problem in detail and provide code in F#: You are given an integer array `nums` of length `n` where `nums` is a permutation of the numbers in the range `[0, n - 1]`. You should build a set `s[k] = {nums[k], nums[nums[k]], nums[nums[nums[k]]], ... }` subjected to the following rule: * Th...
dolphin
Please focus on the functionality of this problem and provide code in Rust: Given an integer `k`, _return the minimum number of Fibonacci numbers whose sum is equal to_ `k`. The same Fibonacci number can be used multiple times. The Fibonacci numbers are defined as: * `F1 = 1` * `F2 = 1` * `Fn = Fn-1 + Fn-2` for...
dolphin
Please write the following solution using java: There is a programming language with only **four** operations and **one** variable `X`: * `++X` and `X++` **increments** the value of the variable `X` by `1`. * `--X` and `X--` **decrements** the value of the variable `X` by `1`. Initially, the value of `X` is `0`. ...
dolphin
port this code from Dart to TypeScript: ```dart import 'dart:convert'; import 'dart:math'; int superPalindromeCount(String left, String right) { int L = int.parse(left); int R = int.parse(right); int count = 0; for (int i = 1; i <= sqrt(R); i++) { if (isPalindrome(i) && isPalindrome(i * i)) { int squ...
dolphin
convert this code from Groovy to F#: ```groovy def num_splits(String s) { int mod = 1000000007 int ones = 0 for (char c : s.toCharArray()) { if (c == '1') ones++ } if (ones % 3 != 0) return 0 if (ones == 0) return (s.length() - 1) * (s.length() - 2) / 2 % mod int each = ones / 3 ...
dolphin
Please write the following solution using java: Given an integer array `nums` sorted in **non-decreasing order**, remove some duplicates [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm) such that each unique element appears **at most twice**. The **relative order** of the elements should be kept the **s...
dolphin
Please write the following solution using Scala: Given a **binary tree** `root`, return _the maximum sum of all keys of **any** sub-tree which is also a Binary Search Tree (BST)_. Assume a BST is defined as follows: * The left subtree of a node contains only nodes with keys **less than** the node's key. * The rig...
dolphin
Please focus on the functionality of this problem and provide code in TypeScript: Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values. **Example 1:** **Input:** n = 5 **Output:** true **Explanation:** The binary representation of 5 is: 101 *...
dolphin
translate this code to Rust: ```F# let minMoves (grid: int[][]) = let n = grid.Length if grid.[0].[2] = 1 then -1 else let mutable q = [(0, 0, 0, 1)] let mutable visited = Set(q) let mutable moves = 0 while q.Length > 0 do for i in 0..q.Length-1 do ...
dolphin
Please focus on the functionality of this problem and provide code in java: 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 representi...
dolphin
Please write the following solution using PHP: Given an integer array `nums`, return _the length of the longest **strictly increasing**_ _**subsequence**_. **Example 1:** **Input:** nums = \[10,9,2,5,3,7,101,18\] **Output:** 4 **Explanation:** The longest increasing subsequence is \[2,3,7,101\], therefore the length ...
dolphin
port this code to Go: ```c #include <stdio.h> #include <stdbool.h> #define MAX_SIZE 205 #define OFFSET 10001 int row_groups[MAX_SIZE]; int col_groups[MAX_SIZE]; int groups[MAX_SIZE][MAX_SIZE]; int group_count = 0; bool visited[MAX_SIZE]; void dfs(int groupId) { if (visited[groupId]) { return; } v...
dolphin
translate this code from Swift to Perl: ```swift func minSeededValue(_ nums: [Int], _ space: Int) -> Int { var count = [Int: Int]() for num in nums { count[num % space, default: 0] += 1 } return count.max(by: { if $0.value == $1.value { return $0.key > $1.key } ...
dolphin
port this code from PHP to Julia: ```php function minAbsoluteDiff($nums, $queries) { $n = count($nums); $res = array(); for ($i = 0; $i < count($queries); $i++) { $li = $queries[$i][0]; $ri = $queries[$i][1]; $subarray = array_slice($nums, $li, $ri - $li + 1); if (count(...
dolphin
Please explain the reasoning behind the following solution and provide code in Go: The **minimum absolute difference** of an array `a` is defined as the **minimum value** of `|a[i] - a[j]|`, where `0 <= i < j < a.length` and `a[i] != a[j]`. If all elements of `a` are the **same**, the minimum absolute difference is `-1...
dolphin
Please write the following solution using python: You are given a map of a server center, represented as a `m * n` integer matrix `grid`, where 1 means that on that cell there is a server and 0 means that it is no server. Two servers are said to communicate if they are on the same row or on the same column. Return...
dolphin
Please explain the reasoning behind the following solution and provide code in Go: There is a tree (i.e. a connected, undirected graph with no cycles) consisting of `n` nodes numbered from `0` to `n - 1` and exactly `n - 1` edges. You are given a **0-indexed** integer array `vals` of length `n` where `vals[i]` denotes...
dolphin
port this code to Haskell: ```vb.net Function InterpretCommand(command As String) As String Dim result As String = "" Dim i As Integer = 0 While i < command.Length If command(i) = "G"c Then result &= "G" i += 1 ElseIf command(i) = "("c And command(i+1) = ")"c The...
dolphin
Please explain the following problem in detail and provide code in Go: You are given a 2D integer array `descriptions` where `descriptions[i] = [parenti, childi, isLefti]` indicates that `parenti` is the **parent** of `childi` in a **binary** tree of **unique** values. Furthermore, * If `isLefti == 1`, then `childi`...
dolphin
Please write the following solution using Objective-C: You are given a nested list of integers `nestedList`. Each element is either an integer or a list whose elements may also be integers or other lists. Implement an iterator to flatten it. Implement the `NestedIterator` class: * `NestedIterator(List nestedList)` ...
dolphin
port this code from Mojo to Visual Basic .NET: ```mojo fn minNonZeroProduct(p: int) -> int { let mod = 10 ** 9 + 7; let x = (1 << p) - 1; let y = (1 << p) - 2; let z = modPow(y, x-1, mod); return (x * z) % mod; } fn modPow(base: int, exponent: int, modulo: int) -> int { if exponent == 0 { ...
dolphin
convert this code to Perl: ```swift func maxSubstringOccurrences(_ s: String, _ k: Int) -> Int { var freq = [Character: Int]() var res = 0 for c in s { freq[c, default: 0] += 1 if freq.keys.count <= k { res = max(res, freq[c]!) } } return freq.keys.count > k ? 0 :...
dolphin
Please explain the reasoning behind the following solution and provide code in COBOL: Given an integer array `nums`, return `true` if any value appears **at least twice** in the array, and return `false` if every element is distinct. **Example 1:** **Input:** nums = \[1,2,3,1\] **Output:** true **Example 2:** **Inp...
dolphin
Please focus on the functionality of this problem and provide code in Visual Basic .NET: There are a total of `numCourses` courses you have to take, labeled from `0` to `numCourses - 1`. You are given an array `prerequisites` where `prerequisites[i] = [ai, bi]` indicates that you **must** take course `bi` first if you ...
dolphin
Please focus on the functionality of this problem and provide code in PHP: On a campus represented as a 2D grid, there are `n` workers and `m` bikes, with `n <= m`. Each worker and bike is a 2D coordinate on this grid. We assign one unique bike to each worker so that the sum of the **Manhattan distances** between each...
dolphin
Please explain the following problem in detail and provide code in Swift: There are a total of `numCourses` courses you have to take, labeled from `0` to `numCourses - 1`. You are given an array `prerequisites` where `prerequisites[i] = [ai, bi]` indicates that you **must** take course `ai` first if you want to take co...
dolphin
convert this code from ANSI C to C#: ```c #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #define MAXN 100005 int n, seats, distance[MAXN]; bool visited[MAXN]; int head[MAXN], nxt[MAXN * 2], to[MAXN * 2], edges; void add_edge(int u, int v) { nxt[++edges] = head[u]; to[edges] = v; head[u] = ed...
dolphin
Please explain the reasoning behind the following solution and provide code in Mojo: You have a convex `n`\-sided polygon where each vertex has an integer value. You are given an integer array `values` where `values[i]` is the value of the `ith` vertex (i.e., **clockwise order**). You will **triangulate** the polygon ...
dolphin
Please write the following solution using Objective-C: You are given a positive integer `n` representing the number of nodes in a tree, numbered from `0` to `n - 1` (**inclusive**). You are also given a 2D integer array `edges` of length `n - 1`, where `edges[i] = [node1i, node2i]` denotes that there is a **bidirection...
dolphin
Please explain the reasoning behind the following solution and provide code in Rust: You are given a **0-indexed** integer array `nums` and a positive integer `k`. We call an index `i` **k-big** if the following conditions are satisfied: * There exist at least `k` different indices `idx1` such that `idx1 < i` and `...
dolphin
Please explain the following problem in detail and provide code in TypeScript: Given two arrays `nums1` and `nums2`. Return the maximum dot product between **non-empty** subsequences of nums1 and nums2 with the same length. A subsequence of a array is a new array which is formed from the original array by deleting so...
dolphin
Please focus on the efficiency of this problem and provide code in Fortran: There are `n` buildings in a line. You are given an integer array `heights` of size `n` that represents the heights of the buildings in the line. The ocean is to the right of the buildings. A building has an ocean view if the building can see ...
dolphin
Please explain the reasoning behind the following solution and provide code in Rust: There are `n` rings and each ring is either red, green, or blue. The rings are distributed **across ten rods** labeled from `0` to `9`. You are given a string `rings` of length `2n` that describes the `n` rings that are placed onto th...
dolphin
Please write the following solution using Objective-C: In a garden represented as an infinite 2D grid, there is an apple tree planted at **every** integer coordinate. The apple tree planted at an integer coordinate `(i, j)` has `|i| + |j|` apples growing on it. You will buy an axis-aligned **square plot** of land that...
dolphin
convert this code to Dart: ```elixir def max_number_of_candies(candy_type) do unique_candies = :lists.foldl(candy_type, %{}, fn x, acc -> Map.put(acc, x, true) end) [length(candy_type), length(unique_candies)] |> Enum.min() |> div(2) end ```
dolphin
convert this code from ANSI C to R: ```c #include <stdio.h> #include <stdlib.h> int cmpfunc(const void *a, const void *b) { return (*(int *)a - *(int *)b); } int minimum_operations(int **grid, int grid_size, int *grid_col_size, int x) { int n = grid_size; int m = grid_col_size[0]; int *sorted_grid = m...
dolphin
port this code to Objective-C: ```julia function is_similar(a::String, b::String)::Bool diff_count = 0 for (char_a, char_b) in zip(a, b) if char_a != char_b diff_count += 1 if diff_count > 2 return false end end end return true end fun...
dolphin
Please write the following solution using Dart: Given an array `nums` of **distinct** positive integers, return _the number of tuples_ `(a, b, c, d)` _such that_ `a * b = c * d` _where_ `a`_,_ `b`_,_ `c`_, and_ `d` _are elements of_ `nums`_, and_ `a != b != c != d`_._ **Example 1:** **Input:** nums = \[2,3,4,6\] **Ou...
dolphin
Please write the following solution using Visual Basic .NET: Given a string `s`, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. **Example 1:** **Input:** s = "abab " **Output:** true **Explanation:** It is the substring "ab " twice. **Example 2:*...
dolphin
Please write the following solution using Julia: 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 have the same color and are next...
dolphin
translate this code to R: ```scala def countAvgNodes(root: TreeNode): Int = { var totalNodes = 0 def dfs(node: TreeNode): (Int, Int) = { if (node == null) return (0, 0) val (leftSum, leftCount) = dfs(node.left) val (rightSum, rightCount) = dfs(node.right) val nodeSum = leftSum + ...
dolphin
port this code to Object Pascal: ```lua function balanceBST(root) local sortedNodes = {} inorderTraversal(root, sortedNodes) return sortedArrayToBST(sortedNodes, 1, #sortedNodes) end function inorderTraversal(node, sortedNodes) if node == nil then return end inorderTraversal(node.left, sortedNodes)...
dolphin
Please write the following solution using Lua: You are given an integer array `nums`. The adjacent integers in `nums` will perform the float division. * For example, for `nums = [2,3,4]`, we will evaluate the expression `"2/3/4 "`. However, you can add any number of parenthesis at any position to change the priorit...
dolphin
convert this code from ANSI C to PHP: ```c #include <stdio.h> #include <stdlib.h> int cmpfunc(const void* a, const void* b) { return (*(int*)b - *(int*)a); } int maxCoins(int** piles, int pilesSize, int* pilesColSize, int k){ int* pq = malloc(sizeof(int) * 2000); int pqSize = 0; for (int i = 0; i < pi...
dolphin
convert this code from javascript to Julia: ```javascript function stringSumScores(s) { let score = 0; let prefix_length = 0; for (let i = s.length - 1; i >= 0; i--) { if (s[i] === s[s.length - 1]) { prefix_length++; } else { prefix_length = 0; } scor...
dolphin
convert this code to Elixir: ```python def minimum_energy(tasks): tasks.sort(key=lambda task: task[1] - task[0], reverse=True) energy = 0 for task in tasks: energy = max(energy + task[0], task[1]) return energy ```
dolphin
Please focus on the algorithm of this problem and provide code in Ruby: Given an array of unique integers, `arr`, where each integer `arr[i]` is strictly greater than `1`. We make a binary tree using these integers, and each number may be used for any number of times. Each non-leaf node's value should be equal to the ...
dolphin
Please write the following solution using Swift: You are given an `m x n` binary matrix `grid`. An island is a group of `1`'s (representing land) connected **4-directionally** (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water. An island is considered to be the same as another ...
dolphin
Please explain the following problem in detail and provide code in Scala: There are `n` people standing in a queue, and they numbered from `0` to `n - 1` in **left to right** order. You are given an array `heights` of **distinct** integers where `heights[i]` represents the height of the `ith` person. A person can **se...
dolphin
convert this code to java: ```dart int totalAppeal(String s) { int n = s.length; int total = 0; for (int i = 0; i < n; i++) { List<int> freq = List.filled(26, 0); for (int j = i; j < n; j++) { freq[s.codeUnitAt(j) - 'a'.codeUnitAt(0)]++; int distinct = 0; for (int k = 0; k < 26; k++) { ...
dolphin
Please write the following solution using Visual Basic .NET: Given the `root` of a binary tree, construct a string consisting of parenthesis and integers from a binary tree with the preorder traversal way, and return it. Omit all the empty parenthesis pairs that do not affect the one-to-one mapping relationship betwee...
dolphin
Please explain the following problem in detail and provide code in Dart: You are given an `n x n` integer matrix `board` where the cells are labeled from `1` to `n2` in a [**Boustrophedon style**](https://en.wikipedia.org/wiki/Boustrophedon) starting from the bottom left of the board (i.e. `board[n - 1][0]`) and altern...
dolphin
convert this code from Visual Basic .NET to Go: ```vb.net Function isPalindrome(ByVal num As Integer) As Boolean Return num.ToString().Equals(StrReverse(num.ToString())) End Function Function superpalindromesInRange(ByVal left As String, ByVal right As String) As Integer Dim l As Integer = Integer.Parse(left) ...
dolphin
translate this code from Groovy to R: ```groovy def maxBeauty(flowers, newFlowers, target, full, partial) { def beauty = flowers.sum { f -> f >= target ? full : partial * f } flowers.sort() for (int i = 0; i < flowers.size(); i++) { def needed = target - flowers[i] if (needed <= newFlow...
dolphin
port this code to ANSI C: ```javascript function numWays(n, k) { if (n === 0) return 0; if (n === 1) return k; let same = k; let different = k * (k - 1); for (let i = 2; i < n; ++i) { const temp = different; different = (same + different) * (k - 1); same = temp; } re...
dolphin
Please focus on the functionality of this problem and provide code in Clojure: You are given a **0-indexed** array of strings `words`. Each string consists of **lowercase English letters** only. No letter occurs more than once in any string of `words`. Two strings `s1` and `s2` are said to be **connected** if the set ...
dolphin
Please explain the reasoning behind the following solution and provide code in Perl: You are given a **sorted unique** integer array `nums`. A **range** `[a,b]` is the set of all integers from `a` to `b` (inclusive). Return _the **smallest sorted** list of ranges that **cover all the numbers in the array exactly**_. ...
dolphin
port this code to Julia: ```R convertDate <- function(date) { days <- c("1st", "2nd", "3rd", "4th", "5th", "6th", "7th", "8th", "9th", "10th", "11th", "12th", "13th", "14th", "15th", "16th", "17th", "18th", "19th", "20th", "21st", "22nd", "23rd", "24th", "25th", "26th", "27th", "28th", "29th", "30th", "31st") month...
dolphin
Please explain the following problem in detail and provide code in Dart: You are given a sorted integer array `arr` containing `1` and **prime** numbers, where all the integers of `arr` are unique. You are also given an integer `k`. For every `i` and `j` where `0 <= i < j < arr.length`, we consider the fraction `arr[i...
dolphin
translate this code from Clojure to Kotlin: ```clojure (defn generate-palindromes [s] (let [char-count (frequencies s) mid-char (atom "") half-str (atom []) num-occurrences (atom 0)] (doseq [[char count] char-count] (if (odd? count) (do (swap! num-occurrences inc) ...
dolphin
Please explain the following problem in detail and provide code in Lisp: Given an array of positive integers `arr`, find a pattern of length `m` that is repeated `k` or more times. A **pattern** is a subarray (consecutive sub-sequence) that consists of one or more values, repeated multiple times **consecutively** with...
dolphin
Please focus on the functionality of this problem and provide code in Dart: In English, we have a concept called **root**, which can be followed by some other word to form another longer word - let's call this word **successor**. For example, when the **root** `"an "` is followed by the **successor** word `"other "`, w...
dolphin
translate this code to Ruby: ```kotlin fun validPartition(nums: IntArray): Boolean { val count = mutableMapOf<Int, Int>() for (num in nums) { count[num] = count.getOrDefault(num, 0) + 1 } for ((num, cnt) in count) { if (cnt == 2 || cnt == 3 || (count.containsKey(num - 1) && count.contain...
dolphin
Please explain the following problem in detail and provide code in Haskell: Given an integer array `nums` of length `n` where all the integers of `nums` are in the range `[1, n]` and each integer appears **once** or **twice**, return _an array of all the integers that appears **twice**_. You must write an algorithm th...
dolphin
Please explain the following problem in detail and provide code in python: You are given an array of `n` strings `strs`, all of the same length. We may choose any deletion indices, and we delete all the characters in those indices for each string. For example, if we have `strs = [ "abcdef ", "uvwxyz "]` and deletion ...
dolphin
Please explain the reasoning behind the following solution and provide code in SmallTalk: Given the `root` of a binary tree, _check whether it is a mirror of itself_ (i.e., symmetric around its center). **Example 1:** **Input:** root = \[1,2,2,3,4,4,3\] **Output:** true **Example 2:** **Input:** root = \[1,2,2,null...
dolphin
Please write the following solution using TypeScript: You are given an `m x n` integer array `grid`. There is a robot initially located at the **top-left corner** (i.e., `grid[0][0]`). The robot tries to move to the **bottom-right corner** (i.e., `grid[m - 1][n - 1]`). The robot can only move either down or right at an...
dolphin
Please explain the reasoning behind the following solution and provide code in PHP: You are given an integer matrix `isWater` of size `m x n` that represents a map of **land** and **water** cells. * If `isWater[i][j] == 0`, cell `(i, j)` is a **land** cell. * If `isWater[i][j] == 1`, cell `(i, j)` is a **water** c...
dolphin
Please write the following solution using javascript: Given an integer array `nums`, return _the number of longest increasing subsequences._ **Notice** that the sequence has to be **strictly** increasing. **Example 1:** **Input:** nums = \[1,3,5,4,7\] **Output:** 2 **Explanation:** The two longest increasing subsequ...
dolphin
translate this code from Julia to javascript: ```julia struct TreeNode val::Int left::Union{Nothing, TreeNode} right::Union{Nothing, TreeNode} end function is_sum_equal_to_children(root::TreeNode) return root.val == (root.left?.val ?? 0) + (root.right?.val ?? 0) end # Example usage: root = TreeNode(10...
dolphin
convert this code to Erlang: ```dart int getMaxRepetitions(String s1, int n1, String s2, int n2) { int count1 = 0, count2 = 0, i = 0, j = 0; while (count1 < n1) { if (s1[i] == s2[j]) { j++; if (j == s2.length) { j = 0; count2++; } } i++; if (i == s1.length) { ...
dolphin
Please explain the following problem in detail and provide code in Scheme: You are given an `m x n` **0-indexed** 2D array of positive integers `heights` where `heights[i][j]` is the height of the person standing at position `(i, j)`. A person standing at position `(row1, col1)` can see a person standing at position `...
dolphin
Please write the following solution using F#: Given an integer array `nums` sorted in **non-decreasing** order, return _an array of **the squares of each number** sorted in non-decreasing order_. **Example 1:** **Input:** nums = \[-4,-1,0,3,10\] **Output:** \[0,1,9,16,100\] **Explanation:** After squaring, the array ...
dolphin
Please focus on the efficiency of this problem and provide code in Scheme: There are `n` buildings in a line. You are given an integer array `heights` of size `n` that represents the heights of the buildings in the line. The ocean is to the right of the buildings. A building has an ocean view if the building can see t...
dolphin
Please explain the following problem in detail and provide code in Groovy: You are given a **0-indexed** integer array `nums` and an integer `value`. In one operation, you can add or subtract `value` from any element of `nums`. * For example, if `nums = [1,2,3]` and `value = 2`, you can choose to subtract `value` f...
dolphin
Please write the following solution using Julia: You are given a string s of length `n` containing only four kinds of characters: `'Q'`, `'W'`, `'E'`, and `'R'`. A string is said to be **balanced** if each of its characters appears `n / 4` times where `n` is the length of the string. Return _the minimum length of the...
dolphin
Please explain the following problem in detail and provide code in Fortran: Given the `head` of a linked list, we repeatedly delete consecutive sequences of nodes that sum to `0` until there are no such sequences. After doing so, return the head of the final linked list. You may return any such answer. (Note that in ...
dolphin
translate this code to Groovy: ```typescript class MovingAverage { private queue: number[]; private maxSize: number; private sum: number; constructor(size: number) { this.queue = []; this.maxSize = size; this.sum = 0; } next(val: number): number { if (this.queue.length === this.maxSize) { ...
dolphin
port this code from Julia to javascript: ```julia function count_good_pairs(root::TreeNode, distance::Int) count = 0 function dfs(node::Union{Nothing, TreeNode})::Array nonlocal count if node == nothing return [] end if node.left == nothing && node.right == nothing ...
dolphin
Please explain the reasoning behind the following solution and provide code in Objective-C: Given strings `s1`, `s2`, and `s3`, find whether `s3` is formed by an **interleaving** of `s1` and `s2`. An **interleaving** of two strings `s` and `t` is a configuration where `s` and `t` are divided into `n` and `m` substring...
dolphin
Please explain the following problem in detail and provide code in Visual Basic .NET: You have `k` lists of sorted integers in **non-decreasing order**. Find the **smallest** range that includes at least one number from each of the `k` lists. We define the range `[a, b]` is smaller than range `[c, d]` if `b - a < d - ...
dolphin
Please explain the following problem in detail and provide code in c++: You are given an array of integers `stones` where `stones[i]` is the weight of the `ith` stone. We are playing a game with the stones. On each turn, we choose any two stones and smash them together. Suppose the stones have weights `x` and `y` with...
dolphin
convert this code to Go: ```mojo sub title_to_number($column_title) { my $result = 0; for my $c (split //, $column_title) { $result = $result * 26 + (ord($c) - ord("A") + 1); } return $result; } ```
dolphin
translate this code from Julia to Groovy: ```julia function substring_words(words::Array{String,1})::Array{String,1} substrings = [] for i = 1:length(words) for j = 1:length(words) if i != j && contains(words[j], words[i]) push!(substrings, words[i]) break ...
dolphin
Please explain the following problem in detail and provide code in Lisp: Given the `root` of a binary search tree (BST) and an integer `target`, split the tree into two subtrees where one subtree has nodes that are all smaller or equal to the target value, while the other subtree has all nodes that are greater than the...
dolphin
convert this code from Go to Scheme: ```go func rotateGrid(grid [][]int, k int) [][]int { if len(grid) == 0 { return grid } m, n := len(grid), len(grid[0]) numLayers := min(m, n) / 2 for layer := 0; layer < numLayers; layer++ { numToRotate := (m - 2*layer)*2 + (n - 2*layer ...
dolphin
Please write the following solution using Clojure: Our hero Teemo is attacking an enemy Ashe with poison attacks! When Teemo attacks Ashe, Ashe gets poisoned for a exactly `duration` seconds. More formally, an attack at second `t` will mean Ashe is poisoned during the **inclusive** time interval `[t, t + duration - 1]`...
dolphin
Please explain the reasoning behind the following solution and provide code in Scala: A series of highways connect `n` cities numbered from `0` to `n - 1`. You are given a 2D integer array `highways` where `highways[i] = [city1i, city2i, tolli]` indicates that there is a highway that connects `city1i` and `city2i`, all...
dolphin
Please explain the reasoning behind the following solution and provide code in Mojo: **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, ...
dolphin
convert this code to TypeScript: ```pascal function maximumTime(time: string): string; var time_list: array[0..4] of char; begin time_list := time.ToCharArray; if time_list[0] = '?' then if (time_list[1] <= '3') or (time_list[1] = '?') then time_list[0] := '2' else time_list[0] := '1'; if ti...
dolphin