instruction_seed
stringlengths
29
40.5k
source
stringclasses
6 values
Please focus on the efficiency of this problem and provide code in c++: Given an integer array `nums` and an integer `k`, return _the number of pairs_ `(i, j)` _where_ `i < j` _such that_ `|nums[i] - nums[j]| == k`. The value of `|x|` is defined as: * `x` if `x >= 0`. * `-x` if `x < 0`. **Example 1:** **Input:*...
dolphin
Please explain the following problem in detail and provide code in Groovy: 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 alte...
dolphin
Please explain the following problem in detail and provide code in Elixir: You are given a **0-indexed** integer array `nums`. You are also given an integer `key`, which is present in `nums`. For every unique integer `target` in `nums`, **count** the number of times `target` immediately follows an occurrence of `key` ...
dolphin
convert this code to Perl: ```vb.net Function MaximumSwap(num As Integer) As Integer Dim num_str As String = num.ToString() Dim last As New Dictionary(Of Integer, Integer) For i As Integer = 0 To num_str.Length - 1 last(Integer.Parse(num_str(i).ToString())) = i Next For i As Integer...
dolphin
Please explain the following problem in detail and provide code in Clojure: A **Fibonacci** tree is a binary tree created using the order function `order(n)`: * `order(0)` is the empty tree. * `order(1)` is a binary tree with only **one node**. * `order(n)` is a binary tree that consists of a root node with the ...
dolphin
convert this code to Lisp: ```c /** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode* merge(struct ListNode* left, struct ListNode* right){ if(left == NULL) return right; if(right == NULL) return left; if(left...
dolphin
Please write the following solution using Lisp: Given an array of strings `nums` containing `n` **unique** binary strings each of length `n`, return _a binary string of length_ `n` _that **does not appear** in_ `nums`_. If there are multiple answers, you may return **any** of them_. **Example 1:** **Input:** nums = \...
dolphin
Please explain the reasoning behind the following solution and provide code in Perl: You are given two **0-indexed** integer arrays `nums1` and `nums2`, each of size `n`, and an integer `diff`. Find the number of **pairs** `(i, j)` such that: * `0 <= i < j <= n - 1` **and** * `nums1[i] - nums1[j] <= nums2[i] - num...
dolphin
Please focus on the algorithm of this problem and provide code in Perl: There are `n` houses in a village. We want to supply water for all the houses by building wells and laying pipes. For each house `i`, we can either build a well inside it directly with cost `wells[i - 1]` (note the `-1` due to **0-indexing**), or ...
dolphin
translate this code from python to PHP: ```python class TreeNode: def __init__(self, isLeaf, val, topLeft=None, topRight=None, bottomLeft=None, bottomRight=None): self.isLeaf = isLeaf self.val = val self.topLeft = topLeft self.topRight = topRight self.bottomLeft = bottomLeft ...
dolphin
Please explain the reasoning behind the following solution and provide code in javascript: You are given a binary string `binary`. A **subsequence** of `binary` is considered **good** if it is **not empty** and has **no leading zeros** (with the exception of `"0 "`). Find the number of **unique good subsequences** of ...
dolphin
Please explain the following problem in detail and provide code in Ruby: 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 as...
dolphin
Please explain the following problem in detail and provide code in Julia: Given a string `s`, you can transform every letter individually to be lowercase or uppercase to create another string. Return _a list of all possible strings we could create_. Return the output in **any order**. **Example 1:** **Input:** s = ...
dolphin
Please focus on the algorithm of this problem and provide code in Mojo: You are currently designing a dynamic array. You are given a **0-indexed** integer array `nums`, where `nums[i]` is the number of elements that will be in the array at time `i`. In addition, you are given an integer `k`, the **maximum** number of t...
dolphin
translate this code to c++: ```mojo sub well_spaced_string($s as Str, @distance as Int) { my %first; for my $i (0..$s.chars-1) { my $c = $s.substr($i, 1); if (!%first{$c}) { %first{$c} = $i; } else { if (@distance[ord($c) - ord('a')] != $i - %first{$c} - 1) { ...
dolphin
Please explain the following problem in detail and provide code in Haskell: You are given a 0-indexed integer array `nums`. You are allowed to permute `nums` into a new array `perm` of your choosing. We define the **greatness** of `nums` be the number of indices `0 <= i < nums.length` for which `perm[i] > nums[i]`. R...
dolphin
Please focus on the algorithm of this problem and provide code in Haskell: You are given a string `s` consisting of lowercase English letters. A **duplicate removal** consists of choosing two **adjacent** and **equal** letters and removing them. We repeatedly make **duplicate removals** on `s` until we no longer can. ...
dolphin
Please focus on the algorithm of this problem and provide code in Swift: Given an `n x n` array of integers `matrix`, return _the **minimum sum** of any **falling path** through_ `matrix`. A **falling path** starts at any element in the first row and chooses the element in the next row that is either directly below or...
dolphin
translate this code from Scala to javascript: ```scala def minOperations(nums: Array[Int]): Int = { val n = nums.length var inc = 0 var dec = 0 for (i <- 1 until n) { if (nums(i) < nums(i-1)) dec += nums(i-1) - nums(i) else if (nums(i) > nums(i-1)) inc += nums(i) - nums(i-1) } math.min(i...
dolphin
Please explain the following problem in detail and provide code in Haskell: You are given an array of `n` integers, `nums`, where there are at most `50` unique values in the array. You are also given an array of `m` customer order quantities, `quantity`, where `quantity[i]` is the amount of integers the `ith` customer ...
dolphin
port this code to Lua: ```clojure (defn last-remaining [n] (let [direction? true head 1 remaining n step 1] (loop [direction? direction? head head remaining remaining step step] (if (> remaining 1) (let [head (if (or direction? (odd? remaining...
dolphin
Please focus on the efficiency of this problem and provide code in Swift: Given two arrays of **unique** digits `nums1` and `nums2`, return _the **smallest** number that contains **at least** one digit from each array_. **Example 1:** **Input:** nums1 = \[4,1,3\], nums2 = \[5,7\] **Output:** 15 **Explanation:** The n...
dolphin
Please explain the following problem in detail and provide code in Kotlin: You are given a **0-indexed** array of strings `words` and a 2D array of integers `queries`. Each query `queries[i] = [li, ri]` asks us to find the number of strings present in the range `li` to `ri` (both **inclusive**) of `words` that start a...
dolphin
port this code to Erlang: ```fsharp type CombinationIterator(characters: string, combinationLength: int) = let combinations = List.ofSeq [for i in 0 .. characters.Length - 1 do for j in (i+1) .. characters.Length - 1 do if (j - i + 1) = com...
dolphin
Please write the following solution using Rust: Given two integers `dividend` and `divisor`, divide two integers **without** using multiplication, division, and mod operator. The integer division should truncate toward zero, which means losing its fractional part. For example, `8.345` would be truncated to `8`, and `-...
dolphin
Please write the following solution using R: Given the `root` of an n-ary tree, return _the postorder traversal of its nodes' values_. Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples) **Example 1:** **Input:** root = \[1...
dolphin
convert this code to java: ```rust struct Node { val: i32, children: Vec<Node>, } impl Node { fn new(val: i32) -> Self { Node { val, children: Vec::new(), } } } fn helper(root: Option<&Node>, result: &mut Vec<i32>) { if let Some(node) = root { result...
dolphin
Please write the following solution using C#: You are given an integer array `nums` and an integer `k`. In one operation, you can pick two numbers from the array whose sum equals `k` and remove them from the array. Return _the maximum number of operations you can perform on the array_. **Example 1:** **Input:** num...
dolphin
Please write the following solution using PHP: In a row of dominoes, `tops[i]` and `bottoms[i]` represent the top and bottom halves of the `ith` domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.) We may rotate the `ith` domino, so that `tops[i]` and `bottoms[i]` swap values. Ret...
dolphin
convert this code to Objective-C: ```swift func maxProductPath(_ grid: [[Int]]) -> Int { let m = grid.count, n = grid[0].count, mod = Int(1e9) + 7 var dp = Array(repeating: Array(repeating: [0, 0], count: n), count: m) dp[0][0] = [grid[0][0], grid[0][0]] for i in 1..<m { dp[i][0] = [grid[i][0] *...
dolphin
Please explain the following problem in detail and provide code in Mojo: Given an array of strings `strs`, return _the length of the **longest uncommon subsequence** between them_. If the longest uncommon subsequence does not exist, return `-1`. An **uncommon subsequence** between an array of strings is a string that ...
dolphin
Please focus on the algorithm of this problem and provide code in javascript: 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 `root`...
dolphin
Please explain the reasoning behind the following solution and provide code in ANSI C: You are given a binary array `nums` and an integer `k`. A **k-bit flip** is choosing a **subarray** of length `k` from `nums` and simultaneously changing every `0` in the subarray to `1`, and every `1` in the subarray to `0`. Retur...
dolphin
Please write the following solution using TypeScript: Given two integer arrays `pushed` and `popped` each with distinct values, return `true` _if this could have been the result of a sequence of push and pop operations on an initially empty stack, or_ `false` _otherwise._ **Example 1:** **Input:** pushed = \[1,2,3,4,...
dolphin
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 least common multiple of the subarray's elements is_ `k`. A **subarray** is a contiguous non-empty sequence of elements within an array....
dolphin
Please write the following solution using C#: There is an infrastructure of `n` cities with some number of `roads` connecting these cities. Each `roads[i] = [ai, bi]` indicates that there is a bidirectional road between cities `ai` and `bi`. The **network rank** of **two different cities** is defined as the total numb...
dolphin
Please explain the reasoning behind the following solution and provide code in Visual Basic .NET: You are given an integer array `nums`. You are initially positioned at the array's **first index**, and each element in the array represents your maximum jump length at that position. Return `true` _if you can reach the l...
dolphin
Please explain the following problem in detail and provide code in Dart: You are given a **0-indexed** binary string `target` of length `n`. You have another binary string `s` of length `n` that is initially set to all zeros. You want to make `s` equal to `target`. In one operation, you can pick an index `i` where `0 ...
dolphin
convert this code to Julia: ```cpp #include <vector> #include <unordered_map> int numberOfArithmeticSlices(std::vector<int>& nums) { int res = 0; int n = nums.size(); std::vector<std::unordered_map<int, int>> dp(n); for (int i = 0; i < n; ++i) { for (int j = 0; j < i; ++j) { long d...
dolphin
Please focus on the algorithm of this problem and provide code in Elixir: You are given a **0-indexed** `m x n` binary matrix `land` where a `0` represents a hectare of forested land and a `1` represents a hectare of farmland. To keep the land organized, there are designated rectangular areas of hectares that consist ...
dolphin
translate this code from PHP to Scheme: ```php function countSmaller($nums) { $counts = array_fill(0, count($nums), 0); function merge_sort($indices) use (&$nums, &$counts) { if (count($indices) <= 1) { return $indices; } $mid = intval(count($indices) / 2); ...
dolphin
Please write the following solution using Swift: You are given a 2D integer array `intervals` where `intervals[i] = [starti, endi]` represents all the integers from `starti` to `endi` inclusively. A **containing set** is an array `nums` where each interval from `intervals` has **at least two** integers in `nums`. * ...
dolphin
Please explain the reasoning behind the following solution and provide code in Perl: A web developer needs to know how to design a web page's size. So, given a specific rectangular web page's area, your job by now is to design a rectangular web page, whose length L and width W satisfy the following requirements: 1. T...
dolphin
Please write the following solution using PHP: Given an integer array `nums`, return _the largest integer that only occurs once_. If no integer occurs once, return `-1`. **Example 1:** **Input:** nums = \[5,7,3,9,4,9,8,3,1\] **Output:** 8 **Explanation:** The maximum integer in the array is 9 but it is repeated. The ...
dolphin
convert this code from C# to ANSI C: ```csharp public class Solution { public ListNode ReverseGroup(ListNode head, int k) { if (head == null || k == 1) { return head; } ListNode prev = null; ListNode cur = head; for (int i = 1; i <= k; i++) { ListNode ...
dolphin
Please explain the reasoning behind the following solution and provide code in Object Pascal: Given the heads of two singly linked-lists `headA` and `headB`, return _the node at which the two lists intersect_. If the two linked lists have no intersection at all, return `null`. For example, the following two linked lis...
dolphin
convert this code to Swift: ```cpp int smallestRepunitDivByK(int k) { if (k % 2 == 0 || k % 5 == 0) return -1; int n = 0; for (int i = 1; i <= k; i++) { n = (n * 10 + 1) % k; if (n == 0) return i; } return -1; } ```
dolphin
Please explain the reasoning behind the following solution and provide code in ANSI C: Design a time-based key-value data structure that can store multiple values for the same key at different time stamps and retrieve the key's value at a certain timestamp. Implement the `TimeMap` class: * `TimeMap()` Initializes t...
dolphin
translate this code from TypeScript to Fortran: ```typescript function wellSpacedString(s: string, distance: number[]): boolean { const first: Record<string, number> = {}; for (let i = 0; i < s.length; i++) { const c = s[i]; if (!(c in first)) { first[c] = i; } else if (dista...
dolphin
Please explain the reasoning behind the following solution and provide code in Groovy: A `k`\-booking happens when `k` events have some non-empty intersection (i.e., there is some time that is common to all `k` events.) You are given some events `[startTime, endTime)`, after each given event, return an integer `k` rep...
dolphin
Please write the following solution using Lisp: Given a binary string `s`, return `true` _if the **longest** contiguous segment of_ `1`'_s is **strictly longer** than the **longest** contiguous segment of_ `0`'_s in_ `s`, or return `false` _otherwise_. * For example, in `s = "110100010 "` the longest continuous segm...
dolphin
Please explain the following problem in detail and provide code in ANSI C: A **wonderful** string is a string where **at most one** letter appears an **odd** number of times. * For example, `"ccjjc "` and `"abab "` are wonderful, but `"ab "` is not. Given a string `word` that consists of the first ten lowercase Eng...
dolphin
Please write the following solution using c++: You are given a **0-indexed** `m x n` integer matrix `grid` and an integer `k`. You are currently at position `(0, 0)` and you want to reach position `(m - 1, n - 1)` moving only **down** or **right**. Return _the number of paths where the sum of the elements on the path ...
dolphin
convert this code to Erlang: ```groovy def sumWeights(items1, items2) { def weightSums = [:] def result = [] items1.each { value, weight -> weightSums[value] = weightSums.getOrDefault(value, 0) + weight } items2.each { value, weight -> weightSums[value] = weightSums.getOrDefault(val...
dolphin
Please explain the following problem in detail and provide code in Dart: You are given an integer array `nums` where the `ith` bag contains `nums[i]` balls. You are also given an integer `maxOperations`. You can perform the following operation at most `maxOperations` times: * Take any bag of balls and divide it int...
dolphin
Please write the following solution using python: You are given an integer array `nums` consisting of `n` elements, and an integer `k`. Find a contiguous subarray whose **length is equal to** `k` that has the maximum average value and return _this value_. Any answer with a calculation error less than `10-5` will be ac...
dolphin
Please focus on the efficiency of this problem and provide code in Julia: You are given a string `s` and an array of strings `words`. You should add a closed pair of bold tag **and** to wrap the substrings in `s` that exist in `words`. * If two such substrings overlap, you should wrap them together with only one pa...
dolphin
Please explain the reasoning behind the following solution and provide code in Elixir: Given a rectangle of size `n` x `m`, return _the minimum number of integer-sided squares that tile the rectangle_. **Example 1:** **Input:** n = 2, m = 3 **Output:** 3 **Explanation:** `3` squares are necessary to cover the rectang...
dolphin
Please write the following solution using Mojo: Given the `root` of a binary tree, return _the number of nodes where the value of the node is equal to the **sum** of the values of its descendants_. A **descendant** of a node `x` is any node that is on the path from node `x` to some leaf node. The sum is considered to ...
dolphin
translate this code to TypeScript: ```java import java.util.Arrays; public int bagOfTokensScore(int[] tokens, int power) { Arrays.sort(tokens); int score = 0, maxScore = 0; int left = 0, right = tokens.length - 1; while (left <= right) { if (power >= tokens[left]) { power -= tokens...
dolphin
Please explain the reasoning behind the following solution and provide code in Lua: Given a valid (IPv4) IP `address`, return a defanged version of that IP address. A _defanged IP address_ replaces every period `". "` with `"[.] "`. **Example 1:** **Input:** address = "1.1.1.1" **Output:** "1\[.\]1\[.\]1\[.\]1" **E...
dolphin
Please write the following solution using Perl: You are given an empty 2D binary grid `grid` of size `m x n`. The grid represents a map where `0`'s represent water and `1`'s represent land. Initially, all the cells of `grid` are water cells (i.e., all the cells are `0`'s). We may perform an add land operation which tu...
dolphin
convert this code to c++: ```lua function wiggleSort(nums) table.sort(nums) for i = 1, #nums - 1, 2 do nums[i], nums[i + 1] = nums[i + 1], nums[i] end end ```
dolphin
port this code from Fortran to python: ```fortran function max_building(n, restrictions) integer, intent(in) :: n integer, intent(inout), dimension(:,:) :: restrictions integer :: i, height, maxHeight restrictions = reshape([/ [1, 0], [n, n - 1] /], [2, 2]) call sort(restrictions, dim=1) do i...
dolphin
Please focus on the efficiency of this problem and provide code in python: Given an integer `num`, return _three consecutive integers (as a sorted array)_ _that **sum** to_ `num`. If `num` cannot be expressed as the sum of three consecutive integers, return _an **empty** array._ **Example 1:** **Input:** num = 33 **O...
dolphin
Please explain the reasoning behind the following solution and provide code in Scala: You are asked to cut off all the trees in a forest for a golf event. The forest is represented as an `m x n` matrix. In this matrix: * `0` means the cell cannot be walked through. * `1` represents an empty cell that can be walked...
dolphin
convert this code from Groovy to Go: ``` def min_operations(target) { def n = target.size() def s = new int[n] def operations = 0 for (int i = n - 1; i >= 0; i--) { if (s[i] != target[i] ) { if (i > 0 && s[i - 1] != target[i - 1]) { s[i - 1] = target[i - 1] as int ...
dolphin
Please explain the reasoning behind the following solution and provide code in Lisp: There is a rooted tree consisting of `n` nodes numbered `0` to `n - 1`. Each node's number denotes its **unique genetic value** (i.e. the genetic value of node `x` is `x`). The **genetic difference** between two genetic values is defin...
dolphin
Please write the following solution using Objective-C: An image is represented by an `m x n` integer grid `image` where `image[i][j]` represents the pixel value of the image. You are also given three integers `sr`, `sc`, and `color`. You should perform a **flood fill** on the image starting from the pixel `image[sr][s...
dolphin
Please explain the following problem in detail and provide code in Julia: You are given an `m x n` integer matrix `grid` where each cell is either `0` (empty) or `1` (obstacle). You can move up, down, left, or right from and to an empty cell in **one step**. Return _the minimum number of **steps** to walk from the upp...
dolphin
Please explain the following problem in detail and provide code in javascript: Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has exactly `two` or `zero` sub-node. If the node has two sub-nodes, then this node's value is the smaller value among its tw...
dolphin
Please explain the reasoning behind the following solution and provide code in Rust: In the world of Dota2, there are two parties: the Radiant and the Dire. The Dota2 senate consists of senators coming from two parties. Now the Senate wants to decide on a change in the Dota2 game. The voting for this change is a round...
dolphin
Please explain the following problem in detail and provide code in TypeScript: Alice is throwing `n` darts on a very large wall. You are given an array `darts` where `darts[i] = [xi, yi]` is the position of the `ith` dart that Alice threw on the wall. Bob knows the positions of the `n` darts on the wall. He wants to p...
dolphin
Please write the following solution using Swift: Given a `date` string in the form `Day Month Year`, where: * `Day` is in the set `{ "1st ", "2nd ", "3rd ", "4th ", ..., "30th ", "31st "}`. * `Month` is in the set `{ "Jan ", "Feb ", "Mar ", "Apr ", "May ", "Jun ", "Jul ", "Aug ", "Sep ", "Oct ", "Nov ", "Dec "}`. ...
dolphin
port this code from Ruby to TypeScript: ```ruby class LRUCache def initialize(capacity) @cache = {} @capacity = capacity end def get(key) value = @cache.delete(key) { return -1 } @cache[key] = value value end def put(key, value) @cache.delete(key) @cache.shift if @cache.size == @...
dolphin
port this code to Julia: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> int calculate_min_elements_to_change(int* nums, int numsSize, int k) { if (k == 1) { return numsSize; } int freq[210] = {0}; int count = 0; for (int i = 0; i < numsSize; i++) { if (i >= k) ...
dolphin
Please focus on the functionality of this problem and provide code in Scheme: 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]` ...
dolphin
port this code from ANSI C to Scala: ```c int get_next(int n){ int sum = 0; while(n > 0){ int digit = n % 10; sum += digit * digit; n /= 10; } return sum; } bool is_happy(int n){ int slow = n, fast = get_next(n); while(fast != 1 && slow != fast){ slow = get_next(...
dolphin
Please explain the reasoning behind the following solution and provide code in Scheme: Given a **0-indexed** integer array `nums`, find a **0-indexed** integer array `answer` where: * `answer.length == nums.length`. * `answer[i] = |leftSum[i] - rightSum[i]|`. Where: * `leftSum[i]` is the sum of elements to the...
dolphin
Please focus on the algorithm of this problem and provide code in Go: Given the `head` of a linked list and an integer `val`, remove all the nodes of the linked list that has `Node.val == val`, and return _the new head_. **Example 1:** **Input:** head = \[1,2,6,3,4,5,6\], val = 6 **Output:** \[1,2,3,4,5\] **Example ...
dolphin
translate this code to Perl: ```scheme (define (get-coordinates k n) (let ((x (ceiling (/ k n))) (y (if (= (modulo k n) 0) n (modulo k n)))) (list x y))) (define (get-neighbors x y m n introverts extroverts) (let ((neighbors '())) (when (> x 1) (let ((neighbor (if (<= (+ (* (- x 2) n) y) int...
dolphin
port this code to Julia: ```c #include <stdio.h> #include <string.h> #include <limits.h> #define MAX_KEY_LENGTH 10 typedef struct node { char key[MAX_KEY_LENGTH + 1]; int count; struct node *next; struct node *prev; } Node; typedef struct { Node *head; Node *tail; Node **buckets; int ...
dolphin
Please explain the following problem in detail and provide code in Dart: Two strings `word1` and `word2` are considered **almost equivalent** if the differences between the frequencies of each letter from `'a'` to `'z'` between `word1` and `word2` is **at most** `3`. Given two strings `word1` and `word2`, each of leng...
dolphin
convert this code from R to Scala: ```R minimumScore <- function(n, roads) { adj <- vector("list", n) for (i in 1:length(roads)) { road <- roads[i] adj[[road[1]]] <- append(adj[[road[1]]], list(c(road[2], road[3]))) adj[[road[2]]] <- append(adj[[road[2]]], list(c(road[1], road[3]))) } INF <- 10^9...
dolphin
translate this code to Haskell: ``` function MAX_CANDIES(status, candies, keys, containedBoxes, initialBoxes) local visited_boxes = {} local total_candies = 0 local queue = initialBoxes while next(queue) ~= nil do local box = table.remove(queue, 1) if not visited_boxes[box] then ...
dolphin
Please write the following solution using C#: Given two integer arrays `preorder` and `inorder` where `preorder` is the preorder traversal of a binary tree and `inorder` is the inorder traversal of the same tree, construct and return _the binary tree_. **Example 1:** **Input:** preorder = \[3,9,20,15,7\], inorder = \...
dolphin
port this code from Mojo to Groovy: ``` function deleteNode(root, key) if root == null return null if key < root.val root.left = deleteNode(root.left, key) else if key > root.val root.right = deleteNode(root.right, key) else if root.left == null return root.ri...
dolphin
Please focus on the functionality of this problem and provide code in TypeScript: You are given the `head` of a linked list, which contains a series of integers **separated** by `0`'s. The **beginning** and **end** of the linked list will have `Node.val == 0`. For **every** two consecutive `0`'s, **merge** all the nod...
dolphin
Please explain the following problem in detail and provide code in F#: You are given an array `nums` consisting of non-negative integers. You are also given a `queries` array, where `queries[i] = [xi, mi]`. The answer to the `ith` query is the maximum bitwise `XOR` value of `xi` and any element of `nums` that does not...
dolphin
convert this code from R to Haskell: ```R findMedian <- function(grid) { m <- nrow(grid) n <- ncol(grid) low <- 1 high <- 1000000 while (low < high) { mid <- low + floor((high - low) / 2) count <- sum(sapply(grid, function(row) sum(row <= mid))) if (count < (m * n) / 2 + 1) { low <- ...
dolphin
Please explain the reasoning behind the following solution and provide code in F#: There is a **directed graph** of `n` colored nodes and `m` edges. The nodes are numbered from `0` to `n - 1`. You are given a string `colors` where `colors[i]` is a lowercase English letter representing the **color** of the `ith` node i...
dolphin
Please explain the following problem in detail and provide code in Clojure: There is a class with `m` students and `n` exams. You are given a **0-indexed** `m x n` integer matrix `score`, where each row represents one student and `score[i][j]` denotes the score the `ith` student got in the `jth` exam. The matrix `score...
dolphin
convert this code to java: ```pascal function nice_divisors(primeFactors: integer): integer; const MOD: integer = 1000000007; var n, p_count, divisor_count, p, power: integer; prime_list: array[0..9] of integer = (2, 3, 5, 7, 11, 13, 17, 19, 23, 29); begin n := 200; p_count := 0; divisor_count := 1; wh...
dolphin
translate this code from Lua to ANSI C: ```lua function checkMove(board, rMove, cMove, color) local directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}, {-1, -1}, {-1, 1}, {1, -1}, {1, 1}} local opposite_color = color == 'W' and 'B' or 'W' for _, d in ipairs(directions) do local x, y = rMove + d[1], cMove + ...
dolphin
Please write the following solution using R: Anti-theft security devices are activated inside a bank. You are given a **0-indexed** binary string array `bank` representing the floor plan of the bank, which is an `m x n` 2D matrix. `bank[i]` represents the `ith` row, consisting of `'0'`s and `'1'`s. `'0'` means the cell...
dolphin
Please explain the reasoning behind the following solution and provide code in Scheme: **No-Zero integer** is a positive integer that **does not contain any `0`** in its decimal representation. Given an integer `n`, return _a list of two integers_ `[a, b]` _where_: * `a` and `b` are **No-Zero integers**. * `a + b...
dolphin
Please explain the reasoning behind the following solution and provide code in Go: There is an undirected tree with `n` nodes labeled from `0` to `n - 1`. You are given a **0-indexed** integer array `nums` of length `n` where `nums[i]` represents the value of the `ith` node. You are also given a 2D integer array `edge...
dolphin
Please focus on the efficiency of this problem and provide code in java: Given a string `s`, reverse only all the vowels in the string and return it. The vowels are `'a'`, `'e'`, `'i'`, `'o'`, and `'u'`, and they can appear in both lower and upper cases, more than once. **Example 1:** **Input:** s = "hello" **Output...
dolphin
Please explain the reasoning behind the following solution and provide code in C#: Winter is coming! During the contest, your first job is to design a standard heater with a fixed warm radius to warm all the houses. Every house can be warmed, as long as the house is within the heater's warm radius range. Given the po...
dolphin
Please explain the following problem in detail and provide code in Dart: Design a Leaderboard class, which has 3 functions: 1. `addScore(playerId, score)`: Update the leaderboard by adding `score` to the given player's score. If there is no player with such id in the leaderboard, add him to the leaderboard with the g...
dolphin