instruction_seed
stringlengths
29
40.5k
source
stringclasses
6 values
Please explain the following problem in detail and provide code in Visual Basic .NET: Given an integer `n`, return _the **decimal value** of the binary string formed by concatenating the binary representations of_ `1` _to_ `n` _in order, **modulo**_ `109 + 7`. **Example 1:** **Input:** n = 1 **Output:** 1 **Explanati...
dolphin
Please write the following solution using c++: You are given a 2D integer array `logs` where each `logs[i] = [birthi, deathi]` indicates the birth and death years of the `ith` person. The **population** of some year `x` is the number of people alive during that year. The `ith` person is counted in year `x`'s populatio...
dolphin
translate this code to java: ```elixir defmodule Solution do def min_score(nums, k) do n = length(nums) if n == 1 do 0 else if n == 2 do abs(nums |> Enum.at(1) - nums |> Enum.at(0)) else nums = Enum.sort(nums) ans = nums |> Enum.at(n-1) - nums |> Enum.at(0) small = nums ...
dolphin
Please focus on the functionality of this problem and provide code in Fortran: There are `n` computers numbered from `0` to `n - 1` connected by ethernet cables `connections` forming a network where `connections[i] = [ai, bi]` represents a connection between computers `ai` and `bi`. Any computer can reach any other com...
dolphin
Please write the following solution using Fortran: A set of real numbers can be represented as the union of several disjoint intervals, where each interval is in the form `[a, b)`. A real number `x` is in the set if one of its intervals `[a, b)` contains `x` (i.e. `a <= x < b`). You are given a **sorted** list of disj...
dolphin
translate this code to Ruby: ```haskell floodFill :: [[Int]] -> Int -> Int -> Int -> [[Int]] floodFill image sr sc newColor = let startColor = image !! sr !! sc fill r c | r < 0 || r >= length image || c < 0 || c >= length (head image) = () | image !! r !! c /= startColor || image ...
dolphin
Please write the following solution using Kotlin: You are given an integer array `gifts` denoting the number of gifts in various piles. Every second, you do the following: * Choose the pile with the maximum number of gifts. * If there is more than one pile with the maximum number of gifts, choose any. * Leave be...
dolphin
Please focus on the functionality of this problem and provide code in Scala: You are given an **even** number of people `numPeople` that stand around a circle and each person shakes hands with someone else so that there are `numPeople / 2` handshakes total. Return _the number of ways these handshakes could occur such ...
dolphin
Please explain the following problem in detail and provide code in Rust: A password is considered strong if the below conditions are all met: * It has at least `6` characters and at most `20` characters. * It contains at least **one lowercase** letter, at least **one uppercase** letter, and at least **one digit**....
dolphin
Please write the following solution using R: Given an input string `s`, reverse the order of the **words**. A **word** is defined as a sequence of non-space characters. The **words** in `s` will be separated by at least one space. Return _a string of the words in reverse order concatenated by a single space._ **Note...
dolphin
translate this code from Julia to Scheme: ```julia function numberOfBalancedRanges(nums1::Array{Int64, 1}, nums2::Array{Int64, 1}) MOD = 10^9 + 7 dp = Array{Int64}(undef, 101, 101, 101) dp[1, 1, 1] = 2 sums1, sums2 = zeros(Int64, length(nums1) + 1), zeros(Int64, length(nums1) + 1) for i in 1:length...
dolphin
convert this code from ANSI C to Perl: ``` #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #define MAX_FORBIDDEN 1000 int forbidden[MAX_FORBIDDEN]; struct Node { int pos, steps, backward; }; int minimumJumps(int* forbidden, int forbiddenSize, int a, int b, int x) { bool visited[6001][2] = {false...
dolphin
Please explain the following problem in detail and provide code in Lua: Given an integer array `nums` and an integer `k`, return _the length of the shortest non-empty **subarray** of_ `nums` _with a sum of at least_ `k`. If there is no such **subarray**, return `-1`. A **subarray** is a **contiguous** part of an array...
dolphin
Please focus on the efficiency of this problem and provide code in Julia: You are given an integer array `power` where `power[i]` is the power of the `ith` monster. You start with `0` mana points, and each day you increase your mana points by `gain` where `gain` initially is equal to `1`. Each day, after gaining `gai...
dolphin
translate this code from PHP to C#: ```php function PRIMITIVE_DECOMPOSITION($s) { $n = strlen($s); $i = 0; $res = ""; while ($i < $n) { $open_count = 0; $j = $i; while ($j < $n) { if ($s[$j] == "(") { $open_count++; } else { ...
dolphin
Please explain the reasoning behind the following solution and provide code in Swift: _(This problem is an **interactive problem**.)_ You may recall that an array `arr` is a **mountain array** if and only if: * `arr.length >= 3` * There exists some `i` with `0 < i < arr.length - 1` such that: * `arr[0] < ar...
dolphin
Please focus on the algorithm of this problem and provide code in python: A **stepping number** is an integer such that all of its adjacent digits have an absolute difference of exactly `1`. * For example, `321` is a **stepping number** while `421` is not. Given two integers `low` and `high`, return _a sorted list ...
dolphin
port this code from Groovy to R: ```groovy def is_ugly(n) { if (n <= 0) { return false } for (factor in [2, 3, 5]) { while (n % factor == 0) { n /= factor } } return n == 1 } ```
dolphin
Please write the following solution using F#: You are given two strings `firstString` and `secondString` that are **0-indexed** and consist only of lowercase English letters. Count the number of index quadruples `(i,j,a,b)` that satisfy the following conditions: * `0 <= i <= j < firstString.length` * `0 <= a <= b ...
dolphin
translate this code from Haskell to PHP: ```haskell longestConsecutive :: [Int] -> Int longestConsecutive nums = let elements = Set.fromList nums checkConsecutive currentNum currentSeq = if Set.member (currentNum + 1) elements then checkConsecutive (currentNum + 1) (currentSeq ...
dolphin
Please explain the reasoning behind the following solution and provide code in PHP: You are given an integer `n`. There is an **undirected** graph with `n` nodes, numbered from `0` to `n - 1`. You are given a 2D integer array `edges` where `edges[i] = [ai, bi]` denotes that there exists an **undirected** edge connectin...
dolphin
Please explain the reasoning behind the following solution and provide code in Objective-C: There are several stones **arranged in a row**, and each stone has an associated value which is an integer given in the array `stoneValue`. In each round of the game, Alice divides the row into **two non-empty rows** (i.e. left...
dolphin
convert this code from Object Pascal to PHP: ```pascal uses Generics.Collections; function smallestChair(times: TArray<TArray<Integer>>; targetFriend: Integer): Integer; var events: TSortedDictionary<Integer, Integer>; availableChairs: TSortedSet<Integer>; assignedChair: TArray<Integer>; time, idx, chair: In...
dolphin
port this code from Julia to Object Pascal: ```julia function can_destroy_all(mass::Int64, asteroids::Array{Int64})::Bool sort!(asteroids) for asteroid in asteroids if mass >= asteroid mass += asteroid else return false end end return true end ```
dolphin
port this code to Erlang: ```php function getMaxScore($nums, $k) { $n = count($nums); $dp = array_fill(0, $n, 0); $dp[0] = $nums[0]; $deque = [0]; for ($i = 1; $i < $n; $i++) { while (!empty($deque) && $deque[0] < $i - $k) array_shift($deque); $dp[$i] = $nums[$i] + $dp[$d...
dolphin
Please focus on the algorithm of this problem and provide code in Mojo: You are given a string array `features` where `features[i]` is a single word that represents the name of a feature of the latest product you are working on. You have made a survey where users have reported which features they like. You are given a ...
dolphin
translate this code from c++ to Swift: ```cpp int maxAbsoluteSum(vector<int>& nums) { int max_sum = 0, min_sum = 0, max_so_far = 0, min_so_far = 0; for (int num : nums) { max_so_far = max(num, max_so_far + num); max_sum = max(max_sum, max_so_far); min_so_far = min(num,min_so_far + num);...
dolphin
Please explain the following problem in detail and provide code in Julia: You are given a 2D array of axis-aligned `rectangles`. Each `rectangle[i] = [xi1, yi1, xi2, yi2]` denotes the `ith` rectangle where `(xi1, yi1)` are the coordinates of the **bottom-left corner**, and `(xi2, yi2)` are the coordinates of the **top-...
dolphin
Please explain the reasoning behind the following solution and provide code in Elixir: An undirected graph of `n` nodes is defined by `edgeList`, where `edgeList[i] = [ui, vi, disi]` denotes an edge between nodes `ui` and `vi` with distance `disi`. Note that there may be **multiple** edges between two nodes. Given an ...
dolphin
port this code from Clojure to Elixir: ```clojure (defn encode [strs] (let [encoded-string (reduce #(str %1 (str (count %2) "#" %2)) "" strs)] encoded-string)) (defn decode [s] (let [strs [] len (count s) i 0] (loop [i i] (when (< i len) (let [delimiter-pos (.indexOf s "#" i) ...
dolphin
Please write the following solution using python: A social media company is trying to monitor activity on their site by analyzing the number of tweets that occur in select periods of time. These periods can be partitioned into smaller **time chunks** based on a certain frequency (every **minute**, **hour**, or **day**)...
dolphin
Please write the following solution using Perl: You have `n` buckets each containing some gallons of water in it, represented by a **0-indexed** integer array `buckets`, where the `ith` bucket contains `buckets[i]` gallons of water. You are also given an integer `loss`. You want to make the amount of water in each buc...
dolphin
translate this code from Haskell to ANSI C: ```haskell canConstruct :: String -> String -> Bool canConstruct ransomNote magazine = let letterCount = foldr (\c counts -> Map.insertWith (+) c 1 counts) Map.empty magazine in all (\c -> Map.lookup c letterCount /= Nothing && letterCount Map.! c > 0) ransomNote...
dolphin
port this code from C# to Object Pascal: ```csharp public string DecodeString(string s) { Stack<int> counts = new Stack<int>(); Stack<string> results = new Stack<string>(); string current = ""; int ptr = 0; while (ptr < s.Length) { if (Char.IsDigit(s[ptr])) { int count = 0; ...
dolphin
port this code to python: ```java public int[][] floodFill(int[][] image, int sr, int sc, int newColor) { int startColor = image[sr][sc]; fill(image, sr, sc, newColor, startColor); return image; } private void fill(int[][] image, int sr, int sc, int newColor, int startColor) { if (sr < 0 || sc < 0 || s...
dolphin
Please focus on the algorithm of this problem and provide code in Object Pascal: You are given two arrays of integers `nums1` and `nums2`, possibly of different lengths. The values in the arrays are between `1` and `6`, inclusive. In one operation, you can change any integer's value in **any** of the arrays to **any**...
dolphin
Please explain the reasoning behind the following solution and provide code in Visual Basic .NET: Given two arrays of integers `nums1` and `nums2`, return the number of triplets formed (type 1 and type 2) under the following rules: * Type 1: Triplet (i, j, k) if `nums1[i]2 == nums2[j] * nums2[k]` where `0 <= i < num...
dolphin
Please write the following solution using Clojure: You are given a **0-indexed** integer array `nums`. Rearrange the values of `nums` according to the following rules: 1. Sort the values at **odd indices** of `nums` in **non-increasing** order. * For example, if `nums = [4,**1**,2,**3**]` before this step, it b...
dolphin
translate this code to Kotlin: ```swift func countElements(_ nums: [Int]) -> Int { var count = 0 let sortedNums = nums.sorted() for i in 1..<nums.count - 1 { if sortedNums[i] > sortedNums[0] && sortedNums[i] < sortedNums[nums.count - 1] { count += 1 } } return count } ```
dolphin
Please explain the reasoning behind the following solution and provide code in Objective-C: You are given an integer array `arr`. You can choose a set of integers and remove all the occurrences of these integers in the array. Return _the minimum size of the set so that **at least** half of the integers of the array ar...
dolphin
Please explain the following problem in detail and provide code in C#: Given two arrays of integers `nums1` and `nums2`, return the number of triplets formed (type 1 and type 2) under the following rules: * Type 1: Triplet (i, j, k) if `nums1[i]2 == nums2[j] * nums2[k]` where `0 <= i < nums1.length` and `0 <= j < k ...
dolphin
port this code from c++ to Scheme: ```cpp int minimumMountainRemovals(vector<int>& nums) { int n = nums.size(); vector<int> left(n), right(n); for (int i = 1; i < n; ++i) { left[i] = left[i - 1] + (nums[i] > nums[i - 1]); right[n - i - 1] = right[n - i] + (nums[n - i - 1] > nums[n - i]); ...
dolphin
port this code to Visual Basic .NET: ```C# using System; using System.Collections.Generic; public class Solution { public bool AreSentencesSimilar(string[] sentence1, string[] sentence2, IList<IList<string>> similarPairs) { if (sentence1.Length != sentence2.Length) return false; var similarityMap =...
dolphin
Please focus on the functionality of this problem and provide code in c++: Given a string `s` which consists of lowercase or uppercase letters, return _the length of the **longest palindrome**_ that can be built with those letters. Letters are **case sensitive**, for example, `"Aa "` is not considered a palindrome her...
dolphin
convert this code to TypeScript: ```scala def minSubstrs(s: String): Int = { var seen = Set[Char]() var count = 0 for (c <- s) { if (seen.contains(c)) { count += 1 seen = Set[Char]() } seen += c } count + (if (seen.nonEmpty) 1 else 0) } ```
dolphin
convert this code from Julia to python: ```julia function apply_queries(n::Int, queries::Array{Array{Int,1},1}) mat = zeros(Int, n, n) for query in queries for i in query[1]:query[3] for j in query[2]:query[4] mat[i+1, j+1] += 1 end end end for i...
dolphin
Please focus on the functionality of this problem and provide code in javascript: You are given a string `s`. We want to partition the string into as many parts as possible so that each letter appears in at most one part. Note that the partition is done so that after concatenating all the parts in order, the resultant...
dolphin
Please focus on the functionality of this problem and provide code in java: Given three integers `x`, `y`, and `bound`, return _a list of all the **powerful integers** that have a value less than or equal to_ `bound`. An integer is **powerful** if it can be represented as `xi + yj` for some integers `i >= 0` and `j >=...
dolphin
Please explain the reasoning behind the following solution and provide code in Erlang: You are given a square `board` of characters. You can move on the board starting at the bottom right square marked with the character `'S'`. You need to reach the top left square marked with the character `'E'`. The rest of the squa...
dolphin
Please explain the reasoning behind the following solution and provide code in Object Pascal: You are given an integer array `nums` and an integer `k`. Find the maximum subarray sum of all the subarrays of `nums` that meet the following conditions: * The length of the subarray is `k`, and * All the elements of the...
dolphin
translate this code from Perl to Rust: ``` sub GOOD_DAYS_TO_ROB_BANK { my ($security, $time) = @_; my $n = scalar @$security; my @good_days; for my $i (0..$n-1) { next if ($i - $time < 0 or $i + $time >= $n); my @left = @$security[$i-$time..$i-1]; my @right = @$security[$i+1..$i+...
dolphin
translate this code to Clojure: ```haskell minNonExpressibleInteger :: [Int] -> Int minNonExpressibleInteger nums = go 1 (sort nums) where go result [] = result go result (x:xs) | x > result = result | otherwise = go (result + x) xs ```
dolphin
Please write the following solution using Rust: Given an binary array `nums` and an integer `k`, return `true` _if all_ `1`_'s are at least_ `k` _places away from each other, otherwise return_ `false`. **Example 1:** **Input:** nums = \[1,0,0,0,1,0,0,1\], k = 2 **Output:** true **Explanation:** Each of the 1s are at ...
dolphin
Please explain the following problem in detail and provide code in Swift: We will use a file-sharing system to share a very large file which consists of `m` small **chunks** with IDs from `1` to `m`. When users join the system, the system should assign **a unique** ID to them. The unique ID should be used **once** for...
dolphin
Please explain the reasoning behind the following solution and provide code in Objective-C: Given a string `s` of zeros and ones, _return the maximum score after splitting the string into two **non-empty** substrings_ (i.e. **left** substring and **right** substring). The score after splitting a string is the number o...
dolphin
convert this code from Julia to Mojo: ```julia struct Robot width::Int64 height::Int64 x::Int64 y::Int64 dir::Int64 # 0 for East, 1 for North, 2 for West, and 3 for South dx::Vector{Int64} # change in x for each direction dy::Vector{Int64} # change in y for each direction end function Robot...
dolphin
translate this code to Rust: ```haskell data Node = Node { val :: Int, left :: Maybe Node, right :: Maybe Node, parent :: Maybe Node } lowestCommonAncestor :: Node -> Node -> Node lowestCommonAncestor p q = let a = p b = q in while (a /= b) do a = if a.parent /= Nothing then a....
dolphin
translate this code to Visual Basic .NET: ``` -module(num_matrix). -export([new/1, sum_region/5]). new(Matrix) -> M = length(Matrix), N = length(lists:nth(1, Matrix)), DP = [[0 || _ <- lists:seq(1, N + 1)] || _ <- lists:seq(1, M + 1)], lists:foldl(fun(I, Acc) -> lists:foldl(fun(J, A...
dolphin
Please write the following solution using Visual Basic .NET: Let's define a function `countUniqueChars(s)` that returns the number of unique characters on `s`. * For example, calling `countUniqueChars(s)` if `s = "LEETCODE "` then `"L "`, `"T "`, `"C "`, `"O "`, `"D "` are the unique characters since they appear onl...
dolphin
convert this code to Swift: ```clojure (defn erase-overlap-intervals [intervals] (if (empty? intervals) 0 (let [intervals (sort-by second intervals) count 0 prev-end (second (first intervals))] (loop [i 1] (if (< (first (nth intervals i)) prev-end) (recur (inc i) (i...
dolphin
Please explain the following problem in detail and provide code in R: Given a 2D integer array `nums`, return _all elements of_ `nums` _in diagonal order as shown in the below images_. **Example 1:** **Input:** nums = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\] **Output:** \[1,4,2,7,5,3,8,6,9\] **Example 2:** **Input:** nums...
dolphin
Please explain the following problem in detail and provide code in Object Pascal: Design a simplified version of Twitter where users can post tweets, follow/unfollow another user, and is able to see the `10` most recent tweets in the user's news feed. Implement the `Twitter` class: * `Twitter()` Initializes your tw...
dolphin
Please write the following solution using Clojure: There is a hotel with `n` rooms. The rooms are represented by a 2D integer array `rooms` where `rooms[i] = [roomIdi, sizei]` denotes that there is a room with room number `roomIdi` and size equal to `sizei`. Each `roomIdi` is guaranteed to be **unique**. You are also ...
dolphin
Please explain the following problem in detail and provide code in Mojo: You are given an integer array `ranks` and a character array `suits`. You have `5` cards where the `ith` card has a rank of `ranks[i]` and a suit of `suits[i]`. The following are the types of **poker hands** you can make from best to worst: 1. ...
dolphin
Please explain the following problem in detail and provide code in Rust: 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 ...
dolphin
translate this code from Lua to Lisp: ```lua function time_crossing_the_door(arrival, state) local n = #arrival local answer = {} local door_seen_time = {-1, -1} local i, t = 1, 0 while i <= n do while t < arrival[i] do t = t + 1 end local direction = 1 if...
dolphin
Please write the following solution using python: There is a ball in a `maze` with empty spaces (represented as `0`) and walls (represented as `1`). The ball can go through the empty spaces by rolling **up, down, left or right**, but it won't stop rolling until hitting a wall. When the ball stops, it could choose the n...
dolphin
Please focus on the algorithm of this problem and provide code in Rust: You are given a string `s` of length `n` where `s[i]` is either: * `'D'` means decreasing, or * `'I'` means increasing. A permutation `perm` of `n + 1` integers of all the integers in the range `[0, n]` is called a **valid permutation** if fo...
dolphin
Please explain the reasoning behind the following solution and provide code in Fortran: You are given a **0-indexed** integer array `nums` containing **distinct** numbers, an integer `start`, and an integer `goal`. There is an integer `x` that is initially set to `start`, and you want to perform operations on `x` such ...
dolphin
Please explain the following problem in detail and provide code in Julia: You are assigned to put some amount of boxes onto **one truck**. You are given a 2D array `boxTypes`, where `boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]`: * `numberOfBoxesi` is the number of boxes of type `i`. * `numberOfUnitsPerBox...
dolphin
Please explain the following problem in detail and provide code in Julia: Serialization is converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environm...
dolphin
Please explain the reasoning behind the following solution and provide code in Dart: You are given an integer `n`, which indicates that there are `n` courses labeled from `1` to `n`. You are also given a 2D integer array `relations` where `relations[j] = [prevCoursej, nextCoursej]` denotes that course `prevCoursej` has...
dolphin
Please explain the reasoning behind the following solution and provide code in Objective-C: You want to schedule a list of jobs in `d` days. Jobs are dependent (i.e To work on the `ith` job, you have to finish all the jobs `j` where `0 <= j < i`). You have to finish **at least** one task every day. The difficulty of a...
dolphin
Please write the following solution using Perl: Given an integer `n`, return all the **strobogrammatic numbers** that are of length `n`. You may return the answer in **any order**. A **strobogrammatic number** is a number that looks the same when rotated `180` degrees (looked at upside down). **Example 1:** **Input:...
dolphin
convert this code from Rust to PHP: ```rust pub fn permute_unique(nums: &mut Vec<i32>) -> Vec<Vec<i32>> { fn backtrack(start: usize, nums: &mut Vec<i32>, result: &mut Vec<Vec<i32>>) { if start == nums.len() { result.push(nums.clone()); } else { for i in start..nums.len() { ...
dolphin
port this code from Kotlin to ANSI C: ```kotlin fun largestDividingString(str1: String, str2: String): String { val n1 = str1.length val n2 = str2.length val gcdLen = n1.gcd(n2) val substring = str1.substring(0, gcdLen) return if (substring.repeat(n1 / gcdLen) == str1 && substring.repeat(n2 / gcdLen...
dolphin
Please explain the reasoning behind the following solution and provide code in Mojo: **Reversing** an integer means to reverse all its digits. * For example, reversing `2021` gives `1202`. Reversing `12300` gives `321` as the **leading zeros are not retained**. Given an integer `num`, **reverse** `num` to get `reve...
dolphin
Please focus on the algorithm of this problem and provide code in Visual Basic .NET: You are given an integer `n`, the number of teams in a tournament that has strange rules: * If the current number of teams is **even**, each team gets paired with another team. A total of `n / 2` matches are played, and `n / 2` team...
dolphin
translate this code to Julia: ```pascal type ListNode = class val: Integer; next: ListNode; constructor Create(x: Integer); end; constructor ListNode.Create(x: Integer); begin val := x; next := nil; end; function deleteDuplicates(head: ListNode): ListNode; var dummy, prev, ...
dolphin
Please focus on the efficiency of this problem and provide code in TypeScript: Design a max stack data structure that supports the stack operations and supports finding the stack's maximum element. Implement the `MaxStack` class: * `MaxStack()` Initializes the stack object. * `void push(int x)` Pushes element `x`...
dolphin
Please explain the reasoning behind the following solution and provide code in Dart: Given a list of the scores of different students, `items`, where `items[i] = [IDi, scorei]` represents one score from a student with `IDi`, calculate each student's **top five average**. Return _the answer as an array of pairs_ `resul...
dolphin
translate this code to TypeScript: ```objc - (NSInteger)countStarsExceptBetweenPair:(NSString *)s { NSInteger count = 0; NSInteger pipeCount = 0; for (NSInteger i = 0; i < s.length; i++) { unichar c = [s characterAtIndex:i]; if (c == '|') { pipeCount++; } else if (c ...
dolphin
port this code from TypeScript to Visual Basic .NET: ```typescript function paintGrid(n: number): number { let redCount = 6; let yellowCount = 6; let greenCount = 6; const MOD = 1e9 + 7; for (let i = 2; i <= n; i++) { const newRedCount = (2 * redCount + 2 * yellowCount) % MOD; const newYellowCount = ...
dolphin
Please explain the reasoning behind the following solution and provide code in Haskell: You are given an integer array `nums` and an integer `k`. You can partition the array into **at most** `k` non-empty adjacent subarrays. The **score** of a partition is the sum of the averages of each subarray. Note that the partit...
dolphin
Please explain the following problem in detail and provide code in Scala: Alice has `n` candies, where the `ith` candy is of type `candyType[i]`. Alice noticed that she started to gain weight, so she visited a doctor. The doctor advised Alice to only eat `n / 2` of the candies she has (`n` is always even). Alice likes...
dolphin
Please write the following solution using ANSI C: Given a string `licensePlate` and an array of strings `words`, find the **shortest completing** word in `words`. A **completing** word is a word that **contains all the letters** in `licensePlate`. **Ignore numbers and spaces** in `licensePlate`, and treat letters as *...
dolphin
Please explain the reasoning behind the following solution and provide code in Swift: You are given integers `height` and `width` which specify the dimensions of a brick wall you are building. You are also given a **0-indexed** array of **unique** integers `bricks`, where the `ith` brick has a height of `1` and a width...
dolphin
Please explain the reasoning behind the following solution and provide code in Erlang: You are given an array of **unique** integers `salary` where `salary[i]` is the salary of the `ith` employee. Return _the average salary of employees excluding the minimum and maximum salary_. Answers within `10-5` of the actual ans...
dolphin
Please focus on the functionality of this problem and provide code in Kotlin: A binary tree is given such that each node contains an additional random pointer which could point to any node in the tree or null. Return a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) of the tree. The tree is re...
dolphin
Please focus on the functionality of this problem and provide code in javascript: Given a year `year` and a month `month`, return _the number of days of that month_. **Example 1:** **Input:** year = 1992, month = 7 **Output:** 31 **Example 2:** **Input:** year = 2000, month = 2 **Output:** 29 **Example 3:** **Inp...
dolphin
Please explain the following problem in detail and provide code in Lua: You are given an integer array `nums`. The **range** of a subarray of `nums` is the difference between the largest and smallest element in the subarray. Return _the **sum of all** subarray ranges of_ `nums`_._ A subarray is a contiguous **non-emp...
dolphin
Please explain the reasoning behind the following solution and provide code in c++: _(This problem is an **interactive problem**.)_ You may recall that an array `arr` is a **mountain array** if and only if: * `arr.length >= 3` * There exists some `i` with `0 < i < arr.length - 1` such that: * `arr[0] < arr[...
dolphin
Please write the following solution using Rust: Given an integer array `nums` and an integer `k`, split `nums` into `k` non-empty subarrays such that the largest sum of any subarray is **minimized**. Return _the minimized largest sum of the split_. A **subarray** is a contiguous part of the array. **Example 1:** **...
dolphin
Please explain the reasoning behind the following solution and provide code in Scala: A set of real numbers can be represented as the union of several disjoint intervals, where each interval is in the form `[a, b)`. A real number `x` is in the set if one of its intervals `[a, b)` contains `x` (i.e. `a <= x < b`). You ...
dolphin
port this code from java to Rust: ```java import java.util.*; public int numBusesToDestination(int[][] routes, int source, int target) { if (source == target) return 0; Map<Integer, Set<Integer>> stopRouteMap = new HashMap<>(); for (int i = 0; i < routes.length; i++) { for (int stop : routes[i]) {...
dolphin
translate this code to Dart: ```elixir defmodule Solution do def three_equal_parts(arr) do n = length(arr) ones_count = Enum.count(arr, &(&1 == 1)) if rem(ones_count, 3) != 0 do return [-1,-1] end if ones_count == 0 do return [0, n-1] end ones_in_each_part = ones_count / 3 ...
dolphin
translate this code from Visual Basic .NET to Go: ```vb.net Module Module1 Public Function findClosestDivisors(ByVal num As Integer) As Integer() Dim i As Integer For i = CInt(Math.Floor(Math.Sqrt(num + 2))) To 1 Step -1 If (num + 1) Mod i = 0 Then Return {i, (num + 1) \ ...
dolphin
translate this code from Lua to PHP: ```lua -- Definition for singly-linked list: -- local ListNode = {} -- function ListNode:new (val) -- local obj = { val = val, next = nil } -- setmetatable(obj, self) -- self.__index = self -- return obj -- end -- @param {ListNode[]} lists -- @return {ListNode} fun...
dolphin
translate this code from Visual Basic .NET to Haskell: ```vb.net Function PowerOfString(ByVal s As String) As Integer Dim n As Integer = s.Length Dim max_power As Integer = 1 Dim power As Integer = 1 For i As Integer = 1 To n - 1 If s(i) = s(i - 1) Then power += 1 Else ...
dolphin
Please explain the reasoning behind the following solution and provide code in Ruby: Given an array `nums` that represents a permutation of integers from `1` to `n`. We are going to construct a binary search tree (BST) by inserting the elements of `nums` in order into an initially empty BST. Find the number of differen...
dolphin