instruction_seed
stringlengths
29
40.5k
source
stringclasses
6 values
Please explain the reasoning behind the following solution and provide code in Perl: Given the `head` of a sorted linked list, _delete all duplicates such that each element appears only once_. Return _the linked list **sorted** as well_. **Example 1:** **Input:** head = \[1,1,2\] **Output:** \[1,2\] **Example 2:** ...
dolphin
Please explain the reasoning behind the following solution and provide code in Swift: 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` a...
dolphin
convert this code to python: ```erlang create_recipe_list(Recipes, Ingredients, Supplies) -> RecipeSet = sets:new(), create_recipe(Recipes, Ingredients, Supplies, RecipeSet), sets:to_list(RecipeSet). create_recipe(Recipes, Ingredients, Supplies, Recipe, RecipeSet) -> case sets:is_element(Recipe, Recipe...
dolphin
Please write the following solution using javascript: The Tribonacci sequence Tn is defined as follows: T0 = 0, T1 = 1, T2 = 1, and Tn+3 = Tn + Tn+1 + Tn+2 for n >= 0. Given `n`, return the value of Tn. **Example 1:** **Input:** n = 4 **Output:** 4 **Explanation:** T\_3 = 0 + 1 + 1 = 2 T\_4 = 1 + 1 + 2 = 4 **Examp...
dolphin
convert this code to Erlang: ```fortran function findSmallestNum(pattern) result(num) character(len=*), intent(in) :: pattern character(len=10) :: num = '123456789' integer :: i = 1, j do while (i <= len_trim(pattern)) if (pattern(i:i) == 'D') then j = i do while (j <= le...
dolphin
Please explain the reasoning behind the following solution and provide code in TypeScript: There is an `m x n` binary grid `matrix` with all the values set `0` initially. Design an algorithm to randomly pick an index `(i, j)` where `matrix[i][j] == 0` and flips it to `1`. All the indices `(i, j)` where `matrix[i][j] ==...
dolphin
Please focus on the efficiency of this problem and provide code in Dart: Given a character array `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 a single space. Your code must solve the problem **in-place,** i.e. without a...
dolphin
translate this code to Kotlin: ```javascript function countPatternsInWord(patterns, word) { let count = 0; for (const pattern of patterns) { if (word.includes(pattern)) { count++; } } return count; } ```
dolphin
Please explain the following problem in detail and provide code in python: Given a `m x n` matrix `grid` which is sorted in non-increasing order both row-wise and column-wise, return _the number of **negative** numbers in_ `grid`. **Example 1:** **Input:** grid = \[\[4,3,2,-1\],\[3,2,1,-1\],\[1,1,-1,-2\],\[-1,-1,-2,-...
dolphin
Please explain the reasoning behind the following solution and provide code in Haskell: Given an array `nums` of distinct integers, return _all the possible permutations_. You can return the answer in **any order**. **Example 1:** **Input:** nums = \[1,2,3\] **Output:** \[\[1,2,3\],\[1,3,2\],\[2,1,3\],\[2,3,1\],\[3,1...
dolphin
translate this code from c++ to TypeScript: ```cpp class Node { public: int val; Node* left; Node* right; Node* parent; }; Node* inorderSuccessor(Node* node) { if (node->right) { node = node->right; while (node->left) { node = node->left; } return node; ...
dolphin
Please write the following solution using Fortran: There are `n` pieces arranged in a line, and each piece is colored either by `'A'` or by `'B'`. You are given a string `colors` of length `n` where `colors[i]` is the color of the `ith` piece. Alice and Bob are playing a game where they take **alternating turns** remo...
dolphin
convert this code to Clojure: ```swift class Employee { var id: Int var importance: Int var subordinates: [Int] init(_ id: Int, _ importance: Int, _ subordinates: [Int]) { self.id = id self.importance = importance self.subordinates = subordinates } } func getTotalImport...
dolphin
convert this code from Perl to java: ```perl sub min_travel_cost { my ($days, $costs) = @_; my $n = scalar(@$days); my @dp = (0) x ($n + 1); for (my $i = 1; $i <= $n; $i++) { $dp[$i] = $dp[$i - 1] + $costs->[0]; my $j = $i - 1; while ($j >= 0 and $days->[$i - 1] - $days->[$j...
dolphin
Please explain the following problem in detail and provide code in Perl: The Leetcode file system keeps a log each time some user performs a _change folder_ operation. The operations are described below: * `"../ "` : Move to the parent folder of the current folder. (If you are already in the main folder, **remain i...
dolphin
Please focus on the functionality of this problem and provide code in PHP: You have a bomb to defuse, and your time is running out! Your informer will provide you with a **circular** array `code` of length of `n` and a key `k`. To decrypt the code, you must replace every number. All the numbers are replaced **simultan...
dolphin
Please write the following solution using Ruby: In this problem, a tree is an **undirected graph** that is connected and has no cycles. You are given a graph that started as a tree with `n` nodes labeled from `1` to `n`, with one additional edge added. The added edge has two **different** vertices chosen from `1` to `...
dolphin
convert this code to Lua: ```clojure (defn convert-bst [root] (let [sum (atom 0)] (defn convert [node] (when node (convert (:right node)) (swap! sum + (:val node)) (swap! (:val node) + @sum) (convert (:left node)) node)) (convert root))) ```
dolphin
convert this code to PHP: ```julia function pillowHolder(n::Int, time::Int)::Int time = rem(time, 2*n-2) if time <= n-1 return time + 1 else return 2*n - time - 1 end end ```
dolphin
port this code to Scala: ``` def widest_vertical_area(points) { def sorted_points = points.sort{it[0]} def max_width = 0 (1..<sorted_points.size()).each{ max_width = Math.max(max_width, sorted_points[it][0] - sorted_points[it-1][0]) } return max_width - 1 } ```
dolphin
port this code to python: ```java public int maxCandies(int[] candies, int k) { int left = 1; int right = 0; for (int candy : candies) { right = Math.max(right, candy); } while (left <= right) { int mid = left + (right - left) / 2; int count = 0; for (int candy ...
dolphin
port this code from c++ to Groovy: ```cpp #include <string> #include <algorithm> #include <vector> int maxProduct(std::string s) { int n = s.length(); std::vector<std::vector<int>> dp(n, std::vector<int>(n, 0)); for (int i = 0; i < n; i++) dp[i][i] = 1; for (int len = 2; len <= n; len++) { fo...
dolphin
Please explain the following problem in detail and provide code in C#: Given a 2D integer array `matrix`, return _the **transpose** of_ `matrix`. The **transpose** of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices. **Example 1:** **Input:** matrix = \[\[1,2,3\],\...
dolphin
Please explain the reasoning behind the following solution and provide code in Lisp: You are given two integer arrays `persons` and `times`. In an election, the `ith` vote was cast for `persons[i]` at time `times[i]`. For each query at a time `t`, find the person that was leading the election at time `t`. Votes cast a...
dolphin
Please write the following solution using TypeScript: 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 write the following solution using javascript: You are given the `root` node of a binary search tree (BST) and a `value` to insert into the tree. Return _the root node of the BST after the insertion_. It is **guaranteed** that the new value does not exist in the original BST. **Notice** that there may exist mul...
dolphin
Please write the following solution using javascript: You are given a string `s` and two integers `x` and `y`. You can perform two types of operations any number of times. * Remove substring `"ab "` and gain `x` points. * For example, when removing `"ab "` from `"cabxbae "` it becomes `"cxbae "`. * Remove su...
dolphin
Please explain the reasoning behind the following solution and provide code in Elixir: Koko loves to eat bananas. There are `n` piles of bananas, the `ith` pile has `piles[i]` bananas. The guards have gone and will come back in `h` hours. Koko can decide her bananas-per-hour eating speed of `k`. Each hour, she chooses...
dolphin
Please explain the reasoning behind the following solution and provide code in C#: You are given an `m x n` binary matrix `grid` where each cell is either `0` (empty) or `1` (occupied). You are then given stamps of size `stampHeight x stampWidth`. We want to fit the stamps such that they follow the given **restriction...
dolphin
port this code to C#: ```scala def findLUSLength(strs: Array[String]): Int = { var maxLength = -1 for (i <- 0 until strs.length) { var isUncommon = true for (j <- 0 until strs.length) { if (i != j && isSubsequence(strs(i), strs(j))) { isUncommon = false } ...
dolphin
translate this code to Julia: ```cpp #include <vector> #include <queue> #include <algorithm> using namespace std; vector<int> getOrder(vector<vector<int>>& tasks) { vector<int> taskIndices(tasks.size()); for (int i = 0; i < tasks.size(); i++) taskIndices[i] = i; sort(taskIndices.begin(), taskIndices.end()...
dolphin
Please explain the reasoning behind the following solution and provide code in Visual Basic .NET: A message containing letters from `A-Z` can be **encoded** into numbers using the following mapping: 'A' -> "1 " 'B' -> "2 " ... 'Z' -> "26 " To **decode** an encoded message, all the digits must be grouped then mappe...
dolphin
Please explain the following problem in detail and provide code in F#: 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:** num...
dolphin
Please focus on the efficiency of this problem and provide code in Go: Given two **sorted 0-indexed** integer arrays `nums1` and `nums2` as well as an integer `k`, return _the_ `kth` _(**1-based**) smallest product of_ `nums1[i] * nums2[j]` _where_ `0 <= i < nums1.length` _and_ `0 <= j < nums2.length`. **Example 1:** ...
dolphin
Please focus on the algorithm of this problem and provide code in c++: You are given a string `s` of even length. Split this string into two halves of equal lengths, and let `a` be the first half and `b` be the second half. Two strings are **alike** if they have the same number of vowels (`'a'`, `'e'`, `'i'`, `'o'`, `...
dolphin
Please explain the following problem in detail and provide code in C#: There are `n` points on a road you are driving your taxi on. The `n` points on the road are labeled from `1` to `n` in the direction you are going, and you want to drive from point `1` to point `n` to make money by picking up passengers. You cannot ...
dolphin
Please explain the reasoning behind the following solution and provide code in Rust: Given an integer array `nums`, return _all the different possible non-decreasing subsequences of the given array with at least two elements_. You may return the answer in **any order**. **Example 1:** **Input:** nums = \[4,6,7,7\] **...
dolphin
Please explain the reasoning behind the following solution and provide code in Clojure: Given an array of integers `arr`, you are initially positioned at the first index of the array. In one step you can jump from index `i` to index: * `i + 1` where: `i + 1 < arr.length`. * `i - 1` where: `i - 1 >= 0`. * `j` wh...
dolphin
convert this code to Haskell: ```vb.net Public Function IsScramble(s1 As String, s2 As String) As Boolean If s1 = s2 Then Return True End If If s1.Length <> s2.Length OrElse String.Concat(s1.OrderBy(Function(c) c)) <> String.Concat(s2.OrderBy(Function(c) c)) Then Return False End If ...
dolphin
Please explain the reasoning behind the following solution and provide code in TypeScript: Given the `root` of a binary tree, return _the **maximum width** of the given tree_. The **maximum width** of a tree is the maximum **width** among all levels. The **width** of one level is defined as the length between the end...
dolphin
port this code to Erlang: ```fsharp let min_xor_sum (nums1: int[]) (nums2: int[]) = let n = nums1.Length Array.sort nums1 Array.sortByDescending nums2 id let mutable sum = 0 for i in 0..n-1 do sum <- sum + (nums1.[i] ^ nums2.[i]) sum ```
dolphin
translate this code to PHP: ```python def are_almost_equal(s, goal): if s == goal: return True count = 0 index1, index2 = -1, -1 for i in range(len(s)): if s[i] != goal[i]: count += 1 if index1 == -1: index1 = i else: in...
dolphin
Please write the following solution using Kotlin: A series of highways connect `n` cities numbered from `0` to `n - 1`. You are given a 2D integer array `highways` where `highways[i] = [city1i, city2i, tolli]` indicates that there is a highway that connects `city1i` and `city2i`, allowing a car to go from `city1i` to `...
dolphin
Please explain the reasoning behind the following solution and provide code in javascript: You are given an integer array `nums` of length `n`. Assume `arrk` to be an array obtained by rotating `nums` by `k` positions clock-wise. We define the **rotation function** `F` on `nums` as follow: * `F(k) = 0 * arrk[0] + 1...
dolphin
Please explain the following problem in detail and provide code in Clojure: You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day. You want to maximize your profit by choosing a **single day** to buy one stock and choosing a **different day in the future** to sell that stock....
dolphin
Please focus on the algorithm of this problem and provide code in Clojure: Implement a basic calculator to evaluate a simple expression string. The expression string contains only non-negative integers, `'+'`, `'-'`, `'*'`, `'/'` operators, and open `'('` and closing parentheses `')'`. The integer division should **tr...
dolphin
convert this code to PHP: ```ruby def maximum_building_height(grid) n = grid.length row_maxes = Array.new(n, 0) col_maxes = Array.new(n, 0) max_total = 0 for i in 0..n-1 do for j in 0..n-1 do row_maxes[i] = [row_maxes[i], grid[i][j]].max col_maxes[j] = [col_maxes...
dolphin
convert this code from Elixir to Haskell: ```elixir defmodule Solution do def robot_sim(commands, obstacles) do dx = [0, 1, 0, -1] dy = [1, 0, -1, 0] x = y = di = 0 obstacle_set = MapSet.new(obstacles) ans = 0 Enum.each(commands, fn cmd -> if cmd == -2 do di = rem(di - 1, 4) ...
dolphin
Please focus on the efficiency of this problem and provide code in C#: Given a singly linked list, return a random node's value from the linked list. Each node must have the **same probability** of being chosen. Implement the `Solution` class: * `Solution(ListNode head)` Initializes the object with the head of the ...
dolphin
translate this code from Erlang to Go: ```erlang find_same_binary_value_parts(Arr) -> Ones = lists:sum(Arr), case Ones rem 3 of 0 -> Target = Ones div 3, case Target of 0 -> [0, length(Arr) - 2]; _ -> Count = 0, ...
dolphin
translate this code to Object Pascal: ```dart int maximumColorDistance(List<int> colors) { int n = colors.length; int left = 0; int right = n - 1; while (colors[left] == colors[right] && left < right) { if (colors[left + 1] != colors[left]) { right = left + 1; } else if (colors[right - 1] != color...
dolphin
Please write the following solution using javascript: Design and implement a data structure for a [Least Frequently Used (LFU)](https://en.wikipedia.org/wiki/Least_frequently_used) cache. Implement the `LFUCache` class: * `LFUCache(int capacity)` Initializes the object with the `capacity` of the data structure. * ...
dolphin
Please write the following solution using Haskell: A program was supposed to print an array of integers. The program forgot to print whitespaces and the array is printed as a string of digits `s` and all we know is that all integers in the array were in the range `[1, k]` and there are no leading zeros in the array. G...
dolphin
translate this code to Objective-C: ```go func areSentencesSimilar(sentence1 []string, sentence2 []string, similarPairs [][]string) bool { if len(sentence1) != len(sentence2) { return false } similarityMap := make(map[string]map[string]bool) for _, pair := range similarPairs { if _, ok :...
dolphin
port this code to Swift: ```php function countMaxOrSubsets($nums) { $max_OR = 0; foreach ($nums as $num) { $max_OR |= $num; } $OR_subsets = [0]; foreach ($nums as $num) { $tmp = $OR_subsets; foreach ($OR_subsets as $x) { array_push($tmp, $x | $num); } ...
dolphin
Please write the following solution using python: The school cafeteria offers circular and square sandwiches at lunch break, referred to by numbers `0` and `1` respectively. All students stand in a queue. Each student either prefers square or circular sandwiches. The number of sandwiches in the cafeteria is equal to t...
dolphin
Please focus on the efficiency of this problem and provide code in PHP: There is a test that has `n` types of questions. You are given an integer `target` and a **0-indexed** 2D integer array `types` where `types[i] = [counti, marksi]` indicates that there are `counti` questions of the `ith` type, and each one of them ...
dolphin
port this code from Scheme to Erlang: ```scheme (define (get-next n) (define (sum-of-squares digit) (* digit digit)) (define (sum-of-digits n) (if (zero? n) 0 (+ (sum-of-squares (remainder n 10)) (sum-of-digits (quotient n 10))))) (sum-of-digits n)) (define (is-happy n) (de...
dolphin
translate this code to Swift: ```erlang split_into_fibonacci(Num) -> ans = [], backtrack(0, 0, 0), ans. backtrack(Index, Prev1, Prev2) -> case Index == length(Num) of true -> length(ans) >= 3; false -> Curr = 0, backtrack_1(Index, Prev1, Prev2, Curr) end. ba...
dolphin
Please write the following solution using Erlang: Given two strings `s` and `goal`, return `true` _if you can swap two letters in_ `s` _so the result is equal to_ `goal`_, otherwise, return_ `false`_._ Swapping letters is defined as taking two indices `i` and `j` (0-indexed) such that `i != j` and swapping the charact...
dolphin
Please write the following solution using Fortran: Consider all the leaves of a binary tree, from left to right order, the values of those leaves form a **leaf value sequence**_._ For example, in the given tree above, the leaf value sequence is `(6, 7, 4, 9, 8)`. Two binary trees are considered _leaf-similar_ if thei...
dolphin
Please write the following solution using Lisp: You are given a string `s` of length `n`, and an integer `k`. You are tasked to find the **longest subsequence repeated** `k` times in string `s`. A **subsequence** is a string that can be derived from another string by deleting some or no characters without changing the...
dolphin
Please write the following solution using ANSI C: You are given an `m x n` integer matrix `grid` containing **distinct** positive integers. You have to replace each integer in the matrix with a positive integer satisfying the following conditions: * The **relative** order of every two elements that are in the same ...
dolphin
Please write the following solution using Haskell: You are given two **2D** integer arrays `nums1` and `nums2.` * `nums1[i] = [idi, vali]` indicate that the number with the id `idi` has a value equal to `vali`. * `nums2[i] = [idi, vali]` indicate that the number with the id `idi` has a value equal to `vali`. Each...
dolphin
Please write the following solution using Groovy: Given a string containing digits from `2-9` inclusive, return all possible letter combinations that the number could represent. Return the answer in **any order**. A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not ...
dolphin
translate this code to TypeScript: ```scala def shortestPalindrome(s: String): String = { val n: Int = s.length val rev_s: String = s.reverse for (i <- 0 until n) { if (s.substring(0, n - i) == rev_s.substring(i)) { return rev_s.substring(0, i) + s } } "" } ```
dolphin
translate this code to R: ```scala def minDaysToCompleteTasks(tasks: Array[Int], space: Int): Int = { var taskLastComplete = Map[Int, Int]() var days = 0 for (task <- tasks) { if (taskLastComplete.contains(task)) { val passedDays = days - taskLastComplete(task) if (passedDays < space) { d...
dolphin
convert this code to Julia: ```python from collections import deque def findMaxValueOfEquation(points, k): res = -float("inf") q = deque() for p in points: while q and p[0] - q[0][1] > k: q.popleft() if q: res = max(res, p[1] + p[0] + q[0][0]) ...
dolphin
Please explain the following problem in detail and provide code in Rust: 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 ord...
dolphin
convert this code to Go: ```clojure (defn dfs [node parent tree values first-max] (let [current-sum (nth values node)] (doseq [child (tree node)] (when (not= child parent) (let [child-sum (dfs child node tree values first-max)] (set! current-sum (bit-xor current-sum child-sum))))) (set...
dolphin
Please focus on the efficiency of this problem and provide code in Rust: Given an integer array `nums`, _find three numbers whose product is maximum and return the maximum product_. **Example 1:** **Input:** nums = \[1,2,3\] **Output:** 6 **Example 2:** **Input:** nums = \[1,2,3,4\] **Output:** 24 **Example 3:** ...
dolphin
translate this code from Scheme to Fortran: ```scheme (define (shortest-distance colors queries) (define (get-index-positions lst val) (cond ((null? lst) '()) ((= (car lst) val) (cons 0 (get-index-positions (cdr lst) val))) (else (map (lambda (x) (+ 1 x)) (get-index-positions (cdr lst) val))))...
dolphin
convert this code to python: ```swift func canConvert(str1: String, str2: String) -> Bool { if str1 == str2 { return true } var conversion = [Character: Character]() for (c1, c2) in zip(str1, str2) { if let existing = conversion[c1], existing != c2 { return false } conversion[c1] = c2 } ...
dolphin
Please explain the reasoning behind the following solution and provide code in javascript: Given an integer array `nums` of length `n`, you want to create an array `ans` of length `2n` where `ans[i] == nums[i]` and `ans[i + n] == nums[i]` for `0 <= i < n` (**0-indexed**). Specifically, `ans` is the **concatenation** o...
dolphin
Please focus on the efficiency of this problem and provide code in Objective-C: Given an array of integers `arr` and an integer `k`. A value `arr[i]` is said to be stronger than a value `arr[j]` if `|arr[i] - m| > |arr[j] - m|` where `m` is the **median** of the array. If `|arr[i] - m| == |arr[j] - m|`, then `arr[i]...
dolphin
Please explain the following problem in detail and provide code in Object Pascal: Design a HashSet without using any built-in hash table libraries. Implement `MyHashSet` class: * `void add(key)` Inserts the value `key` into the HashSet. * `bool contains(key)` Returns whether the value `key` exists in the HashSet ...
dolphin
Please write the following solution using Haskell: Given a string `s`, partition `s` such that every substring of the partition is a **palindrome**. Return _all possible palindrome partitioning of_ `s`. **Example 1:** **Input:** s = "aab" **Output:** \[\["a","a","b"\],\["aa","b"\]\] **Example 2:** **Input:** s = "a...
dolphin
Please write the following solution using Perl: A **distinct string** is a string that is present only **once** in an array. Given an array of strings `arr`, and an integer `k`, return _the_ `kth` _**distinct string** present in_ `arr`. If there are **fewer** than `k` distinct strings, return _an **empty string**_ `" ...
dolphin
port this code to Go: ```lua function moveZeroes(nums) local index = 1 for i = 1, #nums do if nums[i] ~= 0 then nums[index] = nums[i] index = index + 1 end end for i = index, #nums do nums[i] = 0 end end ```
dolphin
Please explain the reasoning behind the following solution and provide code in java: Given a binary string `s` **​​​​​without leading zeros**, return `true`​​​ _if_ `s` _contains **at most one contiguous segment of ones**_. Otherwise, return `false`. **Example 1:** **Input:** s = "1001 " **Output:** false **Explanat...
dolphin
Please explain the reasoning behind the following solution and provide code in Lua: You are given a positive integer `n` representing the number of nodes in a tree, numbered from `0` to `n - 1` (**inclusive**). You are also given a 2D integer array `edges` of length `n - 1`, where `edges[i] = [node1i, node2i]` denotes ...
dolphin
Please write the following solution using javascript: We stack glasses in a pyramid, where the **first** row has `1` glass, the **second** row has `2` glasses, and so on until the 100th row. Each glass holds one cup of champagne. Then, some champagne is poured into the first glass at the top. When the topmost glass is...
dolphin
Please explain the following problem in detail and provide code in Dart: Given a string `s`, find two **disjoint palindromic subsequences** of `s` such that the **product** of their lengths is **maximized**. The two subsequences are **disjoint** if they do not both pick a character at the same index. Return _the **max...
dolphin
Please explain the following problem in detail and provide code in Julia: Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (`push`, `peek`, `pop`, and `empty`). Implement the `MyQueue` class: * `void push(int x)` Pushes eleme...
dolphin
translate this code from Visual Basic .NET to Clojure: ```vb.net Imports System.Collections.Generic Module Module1 Function CountExcellentPairs(nums As Integer(), k As Integer) As Integer Dim frequency As New Dictionary(Of Integer, Integer) For Each num As Integer In nums If Not freque...
dolphin
Please explain the following problem in detail and provide code in python: There is a function `signFunc(x)` that returns: * `1` if `x` is positive. * `-1` if `x` is negative. * `0` if `x` is equal to `0`. You are given an integer array `nums`. Let `product` be the product of all values in the array `nums`. Re...
dolphin
Please explain the reasoning behind the following solution and provide code in Rust: You are given a list of songs where the `ith` song has a duration of `time[i]` seconds. Return _the number of pairs of songs for which their total duration in seconds is divisible by_ `60`. Formally, we want the number of indices `i`,...
dolphin
Please focus on the algorithm of this problem and provide code in Fortran: You have `n` bags numbered from `0` to `n - 1`. You are given two **0-indexed** integer arrays `capacity` and `rocks`. The `ith` bag can hold a maximum of `capacity[i]` rocks and currently contains `rocks[i]` rocks. You are also given an integer...
dolphin
Please write the following solution using R: Given the `head` of a singly linked list, return _the middle node of the linked list_. If there are two middle nodes, return **the second middle** node. **Example 1:** **Input:** head = \[1,2,3,4,5\] **Output:** \[3,4,5\] **Explanation:** The middle node of the list is no...
dolphin
convert this code to C#: ```kotlin fun minVisibleWhiteTiles(floor: String, numCarpets: Int, carpetLen: Int): Int { val n = floor.length var res = n for (i in 0..n - carpetLen) { var count = floor.substring(i, i + carpetLen).count { it == '1' } for (k in 1..numCarpets) { if (k * c...
dolphin
convert this code from Haskell to Perl: ```haskell module MyHashSet ( MyHashSet, add, remove, contains ) where import Data.Array.IO newtype MyHashSet = MyHashSet (IOUArray Int Bool) new :: IO MyHashSet new = MyHashSet <$> newArray (0, 1000000) False add :: Int -> MyHashSet -> IO () add key (MyHashSe...
dolphin
translate this code from Ruby to python: ```ruby def change(amount, coins) dp = [1] + [0] * amount coins.each do |coin| (coin..amount).each do |i| dp[i] += dp[i - coin] end end dp[amount] end ```
dolphin
Please focus on the algorithm of this problem and provide code in Fortran: You are given two positive integer arrays `nums` and `target`, of the same length. In one operation, you can choose any two **distinct** indices `i` and `j` where `0 <= i, j < nums.length` and: * set `nums[i] = nums[i] + 2` and * set `nums...
dolphin
Please write the following solution using Go: There are `n` soldiers standing in a line. Each soldier is assigned a **unique** `rating` value. You have to form a team of 3 soldiers amongst them under the following rules: * Choose 3 soldiers with index (`i`, `j`, `k`) with rating (`rating[i]`, `rating[j]`, `rating[k...
dolphin
translate this code to Lua: ```elixir defmodule Solution do require Enum def max_sum_submatrix(matrix, k) do rows = length(matrix) cols = length(matrix[0]) max_sum = :math.inf() for l <- 0..cols-1 do sums = Enum.map(0..rows-1, &(&1)) for r <- l..cols-1 do Enum.each(0..rows-1, f...
dolphin
port this code from c++ to Lisp: ```cpp int maxDepth(std::string s) { int depth = 0, max_depth = 0; for (char c : s) { if (c == '(') { depth++; max_depth = std::max(depth, max_depth); } else if (c == ')') { depth--; } } return max_depth; } ``...
dolphin
port this code to Fortran: ```elixir defmodule Solution do def search(nums, target) do left = 0 right = length(nums) - 1 while left <= right do mid = div(left + right, 2) if Enum.at(nums, mid) == target do return mid elsif Enum.at(nums, mid) >= Enum.at(nums, left) do if t...
dolphin
Please explain the following problem in detail and provide code in Elixir: You are given the array `paths`, where `paths[i] = [cityAi, cityBi]` means there exists a direct path going from `cityAi` to `cityBi`. _Return the destination city, that is, the city without any path outgoing to another city._ It is guaranteed ...
dolphin
Please explain the reasoning behind the following solution and provide code in Rust: You are given a string `text`. You should split it to k substrings `(subtext1, subtext2, ..., subtextk)` such that: * `subtexti` is a **non-empty** string. * The concatenation of all the substrings is equal to `text` (i.e., `subte...
dolphin
Please explain the following problem in detail and provide code in Erlang: You are given a **0-indexed** **circular** string array `words` and a string `target`. A **circular array** means that the array's end connects to the array's beginning. * Formally, the next element of `words[i]` is `words[(i + 1) % n]` and t...
dolphin