instruction_seed
stringlengths
29
40.5k
source
stringclasses
6 values
Please explain the following problem in detail and provide code in Perl: There is an integer array `nums` sorted in non-decreasing order (not necessarily with **distinct** values). Before being passed to your function, `nums` is **rotated** at an unknown pivot index `k` (`0 <= k < nums.length`) such that the resulting...
dolphin
Please explain the following problem in detail and provide code in c++: Given an array `nums` of integers, a _move_ consists of choosing any element and **decreasing it by 1**. An array `A` is a _zigzag array_ if either: * Every even-indexed element is greater than adjacent elements, ie. `A[0] > A[1] < A[2] > A[3] ...
dolphin
Please explain the following problem in detail and provide code in Rust: You are given an array of `events` where `events[i] = [startDayi, endDayi, valuei]`. The `ith` event starts at `startDayi` and ends at `endDayi`, and if you attend this event, you will receive a value of `valuei`. You are also given an integer `k`...
dolphin
port this code to Ruby: ```fortran function maximumElementAfterDecrementingAndRearranging(arr) result(maxVal) integer, intent(in) :: arr(:) integer :: i, n, maxVal integer :: temp n = size(arr) call sort(arr) arr(1) = 1 do i = 2, n temp = min(arr(i), arr(i-1)+1) arr(i) = temp end do maxVal = a...
dolphin
Please explain the following problem in detail and provide code in R: Given a string `s`, sort it in **decreasing order** based on the **frequency** of the characters. The **frequency** of a character is the number of times it appears in the string. Return _the sorted string_. If there are multiple answers, return _an...
dolphin
Please explain the reasoning behind the following solution and provide code in Object Pascal: Given a positive integer `n`, return the number of the integers in the range `[0, n]` whose binary representations **do not** contain consecutive ones. **Example 1:** **Input:** n = 5 **Output:** 5 **Explanation:** Here are ...
dolphin
translate this code from Groovy to Clojure: ```groovy def racecar(int target) { def memo = [:] def dp = { int position, int speed -> if (Math.abs(position) > 2 * target) return target + 1 if (position == target) return speed == 1 ? 0 : 1 if ([position, speed] in memo) return memo[[positi...
dolphin
convert this code from Visual Basic .NET to PHP: ```vb.net Function CountTriplets(nums as Integer()) as Integer Dim count As Integer = 0 Dim n As Integer = nums.Length Dim sorted_nums = nums.OrderBy(Function(x) x).ToArray() For i As Integer = 0 To n - 3 Dim j As Integer = i + 1 Dim ...
dolphin
Please explain the reasoning behind the following solution and provide code in Julia: 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 th...
dolphin
Please focus on the efficiency of this problem and provide code in R: You have `n` boxes labeled from `0` to `n - 1`. You are given four arrays: `status`, `candies`, `keys`, and `containedBoxes` where: * `status[i]` is `1` if the `ith` box is open and `0` if the `ith` box is closed, * `candies[i]` is the number of...
dolphin
Please explain the following problem in detail and provide code in Lisp: You are given a **0-indexed** string `s` consisting of only lowercase English letters. In one operation, you can change **any** character of `s` to any **other** character. Return `true` _if you can make_ `s` _a palindrome after performing **exac...
dolphin
Please write the following solution using Lua: Given string num representing a non-negative integer `num`, and an integer `k`, return _the smallest possible integer after removing_ `k` _digits from_ `num`. **Example 1:** **Input:** num = "1432219 ", k = 3 **Output:** "1219 " **Explanation:** Remove the three digits...
dolphin
Please write the following solution using Lisp: Given an unsorted array of integers `nums`, return _the length of the longest consecutive elements sequence._ You must write an algorithm that runs in `O(n)` time. **Example 1:** **Input:** nums = \[100,4,200,1,3,2\] **Output:** 4 **Explanation:** The longest consecuti...
dolphin
Please focus on the algorithm of this problem and provide code in Scala: You are given an `n x n` binary matrix `grid`. You are allowed to change **at most one** `0` to be `1`. Return _the size of the largest **island** in_ `grid` _after applying this operation_. An **island** is a 4-directionally connected group of ...
dolphin
convert this code from Visual Basic .NET to Julia: ```vb.net Public Function PalindromeSubsequence(s As String) As Integer Dim n As Integer = s.Length Dim modVal As Integer = 1000000007 Dim dp(9, n - 1) As Integer For i As Integer = 0 To n - 1 dp(Integer.Parse(s(i)), i) = 1 Next ...
dolphin
Please explain the following problem in detail and provide code in Clojure: Given a binary tree `root`, a node _X_ in the tree is named **good** if in the path from root to _X_ there are no nodes with a value _greater than_ X. Return the number of **good** nodes in the binary tree. **Example 1:** **Input:** root = \...
dolphin
Please focus on the functionality of this problem and provide code in Rust: There are `n` cars on an infinitely long road. The cars are numbered from `0` to `n - 1` from left to right and each car is present at a **unique** point. You are given a **0-indexed** string `directions` of length `n`. `directions[i]` can be ...
dolphin
Please focus on the functionality of this problem and provide code in java: Given a string containing just the characters `'('` and `')'`, return _the length of the longest valid (well-formed) parentheses_ _substring_. **Example 1:** **Input:** s = "(() " **Output:** 2 **Explanation:** The longest valid parentheses ...
dolphin
Please focus on the functionality of this problem and provide code in java: Suppose LeetCode will start its **IPO** soon. In order to sell a good price of its shares to Venture Capital, LeetCode would like to work on some projects to increase its capital before the **IPO**. Since it has limited resources, it can only f...
dolphin
translate this code to java: ```vb.net Function CoinTossProbability(n As Integer, prob() As Double, target As Integer) As Double Dim dp(n, target) As Double dp(0, 0) = 1 For i As Integer = 1 To n dp(i, 0) = dp(i - 1, 0) * (1 - prob(i - 1)) For j As Integer = 1 To target dp(i, j) ...
dolphin
Please focus on the functionality of this problem and provide code in Ruby: You are given a network of `n` nodes represented as an `n x n` adjacency matrix `graph`, where the `ith` node is directly connected to the `jth` node if `graph[i][j] == 1`. Some nodes `initial` are initially infected by malware. Whenever two n...
dolphin
convert this code from Object Pascal to Scheme: ``` function k_beauty(num: integer; k: integer): integer; var beauties, i, substr: integer; str_num: string; begin beauties := 0; str_num := IntToStr(num); for i := 1 to Length(str_num) - k + 1 do begin substr := StrToInt(Copy(str_num, i, k)); if (subs...
dolphin
Please write the following solution using Scheme: Given an array of integers `arr` and an integer `d`. In one step you can jump from index `i` to index: * `i + x` where: `i + x < arr.length` and `0 < x <= d`. * `i - x` where: `i - x >= 0` and `0 < x <= d`. In addition, you can only jump from index `i` to index `j...
dolphin
convert this code to Lua: ```erlang create_target_array(Nums, Index) -> Target = [], create_target_array(Nums, Index, Target). create_target_array([], [], Target) -> Target; create_target_array([Num|RestNums], [Index|RestIndex], Target) -> Target1 = lists:insert(Index, Num, Target), create_target_a...
dolphin
Please explain the reasoning behind the following solution and provide code in TypeScript: Given an integer array `nums` and two integers `k` and `p`, return _the number of **distinct subarrays** which have **at most**_ `k` _elements divisible by_ `p`. Two arrays `nums1` and `nums2` are said to be **distinct** if: * ...
dolphin
Please explain the following problem in detail and provide code in Julia: Given a positive integer `n`, find and return _the **longest distance** between any two **adjacent**_ `1`_'s in the binary representation of_ `n`_. If there are no two adjacent_ `1`_'s, return_ `0`_._ Two `1`'s are **adjacent** if there are only...
dolphin
Please explain the reasoning behind the following solution and provide code in Haskell: On an infinite plane, a robot initially stands at `(0, 0)` and faces north. Note that: * The **north direction** is the positive direction of the y-axis. * The **south direction** is the negative direction of the y-axis. * Th...
dolphin
Please focus on the functionality of this problem and provide code in Mojo: We define the string `base` to be the infinite wraparound string of `"abcdefghijklmnopqrstuvwxyz "`, so `base` will look like this: * `"...zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd.... "`. Given a string `s`, return _the num...
dolphin
Please explain the following problem in detail and provide code in Dart: You are given an array `nums` of size `n` consisting of **distinct** integers from `1` to `n` and a positive integer `k`. Return _the number of non-empty subarrays in_ `nums` _that have a **median** equal to_ `k`. **Note**: * The median of an...
dolphin
translate this code to TypeScript: ```lua function check_ways(pairs) local candidates = {} for i = 1, #pairs do local x, y = pairs[i][1], pairs[i][2] candidates[x] = (candidates[x] or 0) + 1 candidates[y] = (candidates[y] or 0) + 1 end local root_count = 0 for _, v in pairs(...
dolphin
translate this code from c++ to Objective-C: ```cpp int pathSumHelper(TreeNode* node, int targetSum, int currentSum) { if (node == nullptr) { return 0; } currentSum += node->val; int totalPaths = currentSum == targetSum; totalPaths += pathSumHelper(node->left, targetSum, currentSum); ...
dolphin
Please write the following solution using F#: Given an array of integers `nums`, find the maximum length of a subarray where the product of all its elements is positive. A subarray of an array is a consecutive sequence of zero or more values taken out of that array. Return _the maximum length of a subarray with posit...
dolphin
Please focus on the efficiency of this problem and provide code in Object Pascal: You are given an integer array `nums` of length `n` and an integer `numSlots` such that `2 * numSlots >= n`. There are `numSlots` slots numbered from `1` to `numSlots`. You have to place all `n` integers into the slots such that each slo...
dolphin
Please explain the reasoning behind the following solution and provide code in Erlang: You are given a 2D array of integers `envelopes` where `envelopes[i] = [wi, hi]` represents the width and the height of an envelope. One envelope can fit into another if and only if both the width and height of one envelope are grea...
dolphin
Please explain the following problem in detail and provide code in Swift: Given an `m x n` integers `matrix`, return _the length of the longest increasing path in_ `matrix`. From each cell, you can either move in four directions: left, right, up, or down. You **may not** move **diagonally** or move **outside the bound...
dolphin
Please explain the reasoning behind the following solution and provide code in Scheme: Given two non-negative integers `low` and `high`. Return the _count of odd numbers between_ `low` _and_ `high` _(inclusive)_. **Example 1:** **Input:** low = 3, high = 7 **Output:** 3 **Explanation:** The odd numbers between 3 and ...
dolphin
Please focus on the efficiency of this problem and provide code in Object Pascal: There exists an infinitely large two-dimensional grid of uncolored unit cells. You are given a positive integer `n`, indicating that you must do the following routine for `n` minutes: * At the first minute, color **any** arbitrary unit...
dolphin
translate this code to Clojure: ```javascript function letterCasePermutation(s) { const result = []; function backtrack(index) { if (index === s.length) { result.push(s.join('')); return; } backtrack(index + 1); if (s[index] !== s[index].toUpperCase() || s...
dolphin
Please explain the following problem in detail and provide code in Julia: You are given two strings `s` and `sub`. You are also given a 2D character array `mappings` where `mappings[i] = [oldi, newi]` indicates that you may perform the following operation **any** number of times: * **Replace** a character `oldi` of ...
dolphin
Please write the following solution using PHP: Given the `head` of a linked list, return _the node where the cycle begins. If there is no cycle, return_ `null`. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the `next` pointer. Internally, `pos` ...
dolphin
convert this code from F# to ANSI C: ```fsharp let least_lexicographically_small_string (s: string) (k: int) = let n = s.Length let mutable result = s for i in 0..n-1 do if i >= k then break let candidate = s.[i..n-1] + s.[0..i-1] if candidate < result then re...
dolphin
translate this code from Haskell to python: ```haskell import Data.List (sort) widestVerticalArea :: [[Int]] -> Int widestVerticalArea points = maximum widths - 1 where sortedPoints = sort points widths = [sortedPoints !! i !! 0 - sortedPoints !! (i-1) !! 0 | i <- [1..length sortedPoints - 1]] ```
dolphin
convert this code to Kotlin: ```R minSwapsCouples <- function(row) { n <- length(row) position <- rep(0, n) for (i in 1:n) { position[row[i] + 1] <- i } swaps <- 0 for (i in seq(1, n, by = 2)) { partner <- ifelse(row[i] %% 2 == 0, row[i] + 1, row[i] - 1) if (row[i + 1] !=...
dolphin
port this code to Lua: ```python def cross_product(p, q, r): return (q[1] - p[1]) * (r[0] - q[0]) - (q[0] - p[0]) * (r[1] - q[1]) def fence(trees): trees.sort(key=lambda p: (p[0], p[1])) hull = [] for p in trees: while len(hull) >= 2 and cross_product(hull[-2], hull[-1], p) > 0: hul...
dolphin
translate this code from Perl to java: ```perl sub firstMissingPositive { my ($nums) = @_; my $n = scalar(@$nums); for (my $i = 0; $i < $n; $i++) { while (1 <= $nums->[$i] && $nums->[$i] <= $n && $nums->[$nums->[$i] - 1] != $nums->[$i]) { my $temp = $nums->[$nums->[$i] - 1]; ...
dolphin
translate this code to R: ```javascript function minimumMovesToConvert(s) { let count = 0; for (let i = 0; i < s.length - 2; i++) { if (s[i] === 'X' && s[i + 1] === 'X' && s[i + 2] === 'X') { count++; i += 2; // move by 3 } } return count; } ```
dolphin
convert this code from TypeScript to Lisp: ```typescript function sortNamesByHeight(names: string[], heights: number[]): string[] { const nameHeightPairs: [number, string][] = []; for (let i = 0; i < names.length; i++) { nameHeightPairs.push([heights[i], names[i]]); } const sortedPairs = nameHeightPairs.sor...
dolphin
translate this code to Scheme: ```go func countSmallerFrequencies(words []string, queries []string) []int { freqWords := make([]int, len(words)) for i, word := range words { minChar := word[0] for _, c := range word { if c < minChar { minChar = c } ...
dolphin
Please explain the following problem in detail and provide code in Rust: Given a string `s` and an integer `k`, return _the maximum number of vowel letters in any substring of_ `s` _with length_ `k`. **Vowel letters** in English are `'a'`, `'e'`, `'i'`, `'o'`, and `'u'`. **Example 1:** **Input:** s = "abciiidef ", ...
dolphin
Please focus on the algorithm of this problem and provide code in PHP: You are given an array `points` where `points[i] = [xi, yi]` represents a point on an **X-Y** plane. **Straight lines** are going to be added to the **X-Y** plane, such that every point is covered by at **least** one line. Return _the **minimum** ...
dolphin
Please explain the reasoning behind the following solution and provide code in Kotlin: A **sentence** is a list of words that are separated by a **single** space with no leading or trailing spaces. * For example, `"Hello World "`, `"HELLO "`, `"hello world hello world "` are all sentences. Words consist of **only**...
dolphin
Please focus on the functionality of this problem and provide code in PHP: You are given an array of strings `nums` and an integer `k`. Each string in `nums` represents an integer without leading zeros. Return _the string that represents the_ `kth` _**largest integer** in_ `nums`. **Note**: Duplicate numbers should b...
dolphin
Please write the following solution using Objective-C: 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 subseq...
dolphin
Please write the following solution using Lisp: Given a string `s`, return _the length of the longest substring between two equal characters, excluding the two characters._ If there is no such substring return `-1`. A **substring** is a contiguous sequence of characters within a string. **Example 1:** **Input:** s =...
dolphin
Please write the following solution using Clojure: Given a `file` and assume that you can only read the file using a given method `read4`, implement a method to read `n` characters. **Method read4:** The API `read4` reads **four consecutive characters** from `file`, then writes those characters into the buffer array ...
dolphin
Please focus on the algorithm of this problem and provide code in Elixir: Given an integer `n`, return _the number of prime numbers that are strictly less than_ `n`. **Example 1:** **Input:** n = 10 **Output:** 4 **Explanation:** There are 4 prime numbers less than 10, they are 2, 3, 5, 7. **Example 2:** **Input:**...
dolphin
Please explain the reasoning behind the following solution and provide code in Haskell: Given an array of `prices` `[p1,p2...,pn]` and a `target`, round each price `pi` to `Roundi(pi)` so that the rounded array `[Round1(p1),Round2(p2)...,Roundn(pn)]` sums to the given `target`. Each operation `Roundi(pi)` could be eith...
dolphin
port this code to Scheme: ```Fortran recursive function dfs(x, n, targetGrid, top, bottom, left, right, vis) result(res) integer, intent(in) :: x, n, top(:), bottom(:), left(:), right(:) integer, dimension(:,:), intent(in) :: targetGrid logical, dimension(:,:), intent(inout) :: vis logical :: res in...
dolphin
translate this code to Fortran: ```groovy import java.util.* def parse(formula, i) { def counts = [:].withDefault { 0 } while (i[0] < formula.length()) { if (formula[i[0]] == '(') { i[0]++ def temp = parse(formula, i) def count = 0 while (i[0] < formula.l...
dolphin
convert this code from ANSI C to Julia: ```c int cmpfunc (const void * a, const void * b) { return (*(int*)a - *(int*)b); } int maxScore(int* nums, int numsSize){ qsort(nums, numsSize, sizeof(int), cmpfunc); int result = 0; int prefixSum = 0; for(int i = 0; i < numsSize; i++){ if(prefixSum +...
dolphin
Please explain the reasoning behind the following solution and provide code in Lua: Implement a SnapshotArray that supports the following interface: * `SnapshotArray(int length)` initializes an array-like data structure with the given length. **Initially, each element equals 0**. * `void set(index, val)` sets the ...
dolphin
port this code to Lisp: ```cpp #include <vector> int merge(std::vector<int>& nums, std::vector<int>& temp, int left, int mid, int right) { int count = 0; int j = mid; for (int i = left; i < mid; i++) { while (j <= right && (long long)nums[i] > 2LL * nums[j]) { j++; } cou...
dolphin
Please explain the following problem in detail and provide code in python: You are given an array of binary strings `strs` and two integers `m` and `n`. Return _the size of the largest subset of `strs` such that there are **at most**_ `m` `0`_'s and_ `n` `1`_'s in the subset_. A set `x` is a **subset** of a set `y` i...
dolphin
Please explain the reasoning behind the following solution and provide code in Perl: A digit string is **good** if the digits **(0-indexed)** at **even** indices are **even** and the digits at **odd** indices are **prime** (`2`, `3`, `5`, or `7`). * For example, `"2582 "` is good because the digits (`2` and `8`) at ...
dolphin
Please focus on the algorithm of this problem and provide code in Clojure: Given an `m x n` binary matrix `mat`, _return the number of **submatrices** that have all ones_. **Example 1:** **Input:** mat = \[\[1,0,1\],\[1,1,0\],\[1,1,0\]\] **Output:** 13 **Explanation:** There are 6 rectangles of side 1x1. There are 2...
dolphin
Please write the following solution using TypeScript: Given the `root` of a binary tree, return _the sum of values of its deepest leaves_. **Example 1:** **Input:** root = \[1,2,3,4,5,null,6,7,null,null,null,null,8\] **Output:** 15 **Example 2:** **Input:** root = \[6,7,8,2,7,1,3,9,null,1,4,null,null,null,5\] **Out...
dolphin
port this code to Ruby: ``` (defn max-profit [prices] (let [buy1 (atom (Double/POSITIVE_INFINITY)) buy2 (atom (Double/POSITIVE_INFINITY)) profit1 (atom 0) profit2 (atom 0)] (doseq [price prices] (reset! buy1 (min @buy1 price)) (reset! profit1 (max @profit1 (- price @buy1))) ...
dolphin
Please write the following solution using Elixir: You are given two **0-indexed** arrays `nums1` and `nums2` of length `n`, both of which are **permutations** of `[0, 1, ..., n - 1]`. A **good triplet** is a set of `3` **distinct** values which are present in **increasing order** by position both in `nums1` and `nums2...
dolphin
Please explain the following problem in detail and provide code in Elixir: You are given the `root` of a binary tree. We install cameras on the tree nodes where each camera at a node can monitor its parent, itself, and its immediate children. Return _the minimum number of cameras needed to monitor all nodes of the tre...
dolphin
Please explain the following problem in detail and provide code in Mojo: In LeetCode Store, there are `n` items to sell. Each item has a price. However, there are some special offers, and a special offer consists of one or more different kinds of items with a sale price. You are given an integer array `price` where `p...
dolphin
Please focus on the efficiency of this problem and provide code in c++: You are given a tree with `n` nodes numbered from `0` to `n - 1` in the form of a parent array `parent` where `parent[i]` is the parent of the `ith` node. The root of the tree is node `0`, so `parent[0] = -1` since it has no parent. You want to des...
dolphin
Please explain the reasoning behind the following solution and provide code in Lisp: You are given a 2D integer array `rectangles` where `rectangles[i] = [li, hi]` indicates that `ith` rectangle has a length of `li` and a height of `hi`. You are also given a 2D integer array `points` where `points[j] = [xj, yj]` is a p...
dolphin
Please write the following solution using Swift: You have `n` `tiles`, where each tile has one letter `tiles[i]` printed on it. Return _the number of possible non-empty sequences of letters_ you can make using the letters printed on those `tiles`. **Example 1:** **Input:** tiles = "AAB " **Output:** 8 **Explanation...
dolphin
Please explain the reasoning behind the following solution and provide code in R: There is an **undirected** graph with `n` nodes numbered from `0` to `n - 1` (**inclusive**). You are given a **0-indexed** integer array `values` where `values[i]` is the **value** of the `ith` node. You are also given a **0-indexed** 2D...
dolphin
Please focus on the functionality of this problem and provide code in Scheme: Given an integer array `nums`, return _the number of **subarrays** filled with_ `0`. A **subarray** is a contiguous non-empty sequence of elements within an array. **Example 1:** **Input:** nums = \[1,3,0,0,2,0,0,4\] **Output:** 6 **Explan...
dolphin
Please focus on the algorithm of this problem and provide code in ANSI C: A **triplet** is an array of three integers. You are given a 2D integer array `triplets`, where `triplets[i] = [ai, bi, ci]` describes the `ith` **triplet**. You are also given an integer array `target = [x, y, z]` that describes the **triplet** ...
dolphin
port this code from Elixir to Erlang: ```elixir defmodule TreeNode do defstruct [:val, :left, :right] end def delete_node(nil, _key), do: nil def delete_node(node = %TreeNode{val: key}, key) do if node.left == nil, do: node.right else if node.right == nil, do: node.left else temp = node.right while te...
dolphin
Please explain the following problem in detail and provide code in Scheme: You are given a 2D integer array `items` where `items[i] = [pricei, beautyi]` denotes the **price** and **beauty** of an item respectively. You are also given a **0-indexed** integer array `queries`. For each `queries[j]`, you want to determine...
dolphin
Please write the following solution using Lisp: International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows: * `'a'` maps to `".- "`, * `'b'` maps to `"-... "`, * `'c'` maps to `"-.-. "`, and so on. For convenience, the full table for the `26` lett...
dolphin
convert this code from Groovy to Erlang: ```groovy class TreeNode { int val TreeNode left TreeNode right TreeNode(int x) { val = x } } TreeNode constructMaximumBinaryTree(int[] nums) { def helper = { nums, left, right -> if (left > right) return null int maxIdx = left for (...
dolphin
Please focus on the algorithm of this problem and provide code in java: Given an array of `points` where `points[i] = [xi, yi]` represents a point on the **X-Y** plane and an integer `k`, return the `k` closest points to the origin `(0, 0)`. The distance between two points on the **X-Y** plane is the Euclidean distanc...
dolphin
Please explain the reasoning behind the following solution and provide code in ANSI C: Given two integer arrays `nums1` and `nums2`, return _an array of their intersection_. Each element in the result must appear as many times as it shows in both arrays and you may return the result in **any order**. **Example 1:** *...
dolphin
Please explain the following problem in detail and provide code in Dart: An **image smoother** is a filter of the size `3 x 3` that can be applied to each cell of an image by rounding down the average of the cell and the eight surrounding cells (i.e., the average of the nine cells in the blue smoother). If one or more ...
dolphin
Please focus on the algorithm of this problem and provide code in Objective-C: Given two integers `num` and `k`, consider a set of positive integers with the following properties: * The units digit of each integer is `k`. * The sum of the integers is `num`. Return _the **minimum** possible size of such a set, or_...
dolphin
Please write the following solution using Fortran: You are given an integer `n` and an integer `p` in the range `[0, n - 1]`. Representing a **0-indexed** array `arr` of length `n` where all positions are set to `0`'s, except position `p` which is set to `1`. You are also given an integer array `banned` containing som...
dolphin
Please explain the following problem in detail and provide code in ANSI C: Given an array of integers, return the maximum sum for a **non-empty** subarray (contiguous elements) with at most one element deletion. In other words, you want to choose a subarray and optionally delete one element from it so that there is sti...
dolphin
Please explain the following problem in detail and provide code in Scheme: According to [Wikipedia's article](https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life): "The **Game of Life**, also known simply as **Life**, is a cellular automaton devised by the British mathematician John Horton Conway in 1970. " The boar...
dolphin
Please explain the reasoning behind the following solution and provide code in Clojure: Given an integer array `nums`, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. You can return the answer in **any order**. You must write ...
dolphin
Please explain the reasoning behind the following solution and provide code in Clojure: The **pair sum** of a pair `(a,b)` is equal to `a + b`. The **maximum pair sum** is the largest **pair sum** in a list of pairs. * For example, if we have pairs `(1,5)`, `(2,3)`, and `(4,4)`, the **maximum pair sum** would be `ma...
dolphin
Please focus on the efficiency of this problem and provide code in Lua: 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 ind...
dolphin
Please focus on the algorithm of this problem and provide code in F#: You are given a **0-indexed** array of **unique** strings `words`. A **palindrome pair** is a pair of integers `(i, j)` such that: * `0 <= i, j < words.length`, * `i != j`, and * `words[i] + words[j]` (the concatenation of the two strings) is...
dolphin
translate this code from Scala to ANSI C: ```scala def isValid(s: String): Boolean = { val stack = collection.mutable.Stack[Char]() for (c <- s) { if (c == '(' || c == '{' || c == '[') { stack.push(c) } else if (stack.isEmpty || (c == ')' && stack.top != '(') || (c == '}' && stack.t...
dolphin
Please explain the following problem in detail and provide code in Visual Basic .NET: You are given two strings `word1` and `word2`. Merge the strings by adding letters in alternating order, starting with `word1`. If a string is longer than the other, append the additional letters onto the end of the merged string. Re...
dolphin
port this code to Mojo: ```rust use rand::Rng; struct Solution { mapping: std::collections::HashMap<usize, usize>, last: usize, } impl Solution { fn new(n: i32, blacklist: Vec<i32>) -> Self { let mut mapping = std::collections::HashMap::new(); let mut idx = 0; let mut n = n as usiz...
dolphin
Please explain the following problem in detail and provide code in C#: Given a string `s`, remove duplicate letters so that every letter appears once and only once. You must make sure your result is **the smallest in lexicographical order** among all possible results. **Example 1:** **Input:** s = "bcabc " **Output:...
dolphin
Please explain the following problem in detail and provide code in Swift: A dieter consumes `calories[i]` calories on the `i`\-th day. Given an integer `k`, for **every** consecutive sequence of `k` days (`calories[i], calories[i+1], ..., calories[i+k-1]` for all `0 <= i <= n-k`), they look at _T_, the total calories ...
dolphin
Please explain the following problem in detail and provide code in PHP: You are given an integer array `target`. You have an integer array `initial` of the same size as `target` with all elements initially zeros. In one operation you can choose **any** subarray from `initial` and increment each value by one. Return _...
dolphin
translate this code from Perl to Groovy: ```perl use strict; use warnings; use Heap::PriorityQueue; sub kth_smallest_array_sum { my ($mat, $k) = @_; my ($m, $n) = (scalar @$mat, scalar @{$mat->[0]}); my $minHeap = Heap::PriorityQueue->new(); $minHeap->insert([$mat->[0][0], 0, 0], $mat->[0][0]); m...
dolphin
convert this code to Haskell: ```r trap_water <- function(height) { n <- length(height) left <- 1 right <- n max_left <- 0 max_right <- 0 water <- 0 while (left < right) { if (height[left] <= height[right]) { max_left <- max(max_left, height[left]) water ...
dolphin
Please focus on the functionality of this problem and provide code in Ruby: You are given an array `nums` consisting of positive integers. Split the array into **one or more** disjoint subarrays such that: * Each element of the array belongs to **exactly one** subarray, and * The **GCD** of the elements of each s...
dolphin