instruction_seed
stringlengths
29
40.5k
source
stringclasses
6 values
Please focus on the algorithm of this problem and provide code in Perl: You are given two 2D integer arrays, `items1` and `items2`, representing two sets of items. Each array `items` has the following properties: * `items[i] = [valuei, weighti]` where `valuei` represents the **value** and `weighti` represents the **...
dolphin
Please write the following solution using PHP: We distribute some number of `candies`, to a row of **`n = num_people`** people in the following way: We then give 1 candy to the first person, 2 candies to the second person, and so on until we give `n` candies to the last person. Then, we go back to the start of the ro...
dolphin
Please focus on the algorithm of this problem and provide code in TypeScript: There is a garden of `n` flowers, and each flower has an integer beauty value. The flowers are arranged in a line. You are given an integer array `flowers` of size `n` and each `flowers[i]` represents the beauty of the `ith` flower. A garden...
dolphin
port this code from Scheme to Visual Basic .NET: ```scheme (define (MyCalendarTwo) (let ((singles '()) (doubles '())) (define (book start end) (let ((overlap? (lambda (a b) (and (< start b) (> end a))))) (cond ((ormap (lambda...
dolphin
Please focus on the functionality of this problem and provide code in Groovy: You are given two integers `m` and `n`. Consider an `m x n` grid where each cell is initially white. You can paint each cell **red**, **green**, or **blue**. All cells **must** be painted. Return _the number of ways to color the grid with **...
dolphin
port this code to Erlang: ```vb Function CalculateTime(keyboard As String, word As String) As Integer Dim time As Integer = 0 Dim prev_index As Integer = 0 Dim char_to_index As New Dictionary(Of Char, Integer) For i As Integer = 0 To 25 char_to_index.Add(keyboard(i), i) Next For Each c...
dolphin
Please explain the following problem in detail and provide code in Clojure: The **min-product** of an array is equal to the **minimum value** in the array **multiplied by** the array's **sum**. * For example, the array `[3,2,5]` (minimum value is `2`) has a min-product of `2 * (3+2+5) = 2 * 10 = 20`. Given an array...
dolphin
convert this code from Haskell to Scheme: ```haskell import Data.List (sort) constructArray :: [Int] -> Bool constructArray target = let n = length target totalSum = sum target in if totalSum `mod` n /= 0 then False else let x = totalSum `div` n arr = take n $ repeat 1 ...
dolphin
port this code from Go to Swift: ```go func maxCompatibilitySum(students [][]int, mentors [][]int) int { m := len(students) n := len(students[0]) maxScoreSum := 0 for mask := 0; mask < 1<<m; mask++ { mentorScores := make([]int, m) studentIndices := make([]int, m) fo...
dolphin
translate this code to Fortran: ```kotlin fun winner(n: Int, k: Int): Int { return if (n == 1) 1 else (winner(n - 1, k) + k - 1) % n + 1 } ```
dolphin
Please focus on the algorithm of this problem and provide code in c++: There is a robot starting at the position `(0, 0)`, the origin, on a 2D plane. Given a sequence of its moves, judge if this robot **ends up at** `(0, 0)` after it completes its moves. You are given a string `moves` that represents the move sequence...
dolphin
convert this code from Scheme to R: ```scheme (define (count-partitions nums k) (define total-sum (apply + nums)) (define n (length nums)) (define mod 1000000007) (if (< total-sum (* k 2)) 0 (let ((dp (make-list (add1 n) 1))) (do ((i 1 (add1 i))) ((>= i k)) (do ((j (...
dolphin
Please explain the reasoning behind the following solution and provide code in PHP: Given an array of strings `words` (**without duplicates**), return _all the **concatenated words** in the given list of_ `words`. A **concatenated word** is defined as a string that is comprised entirely of at least two shorter words (...
dolphin
translate this code to Julia: ```lua function findMaxLength(nums) local max_length, zeroes, ones = 0, 0, 0 local count_map = {[0] = -1} for i, num in ipairs(nums) do if num == 0 then zeroes = zeroes + 1 else ones = ones + 1 end if not count_map[zeroe...
dolphin
convert this code to TypeScript: ```lua local TrieNode = {} TrieNode.__index = TrieNode function TrieNode:new() local node = setmetatable({}, TrieNode) node.children = {} for i = 1, 26 do node.children[i] = nil end node.is_word = false return node end local WordDictionary = {} WordDict...
dolphin
convert this code from Elixir to Visual Basic .NET: ```elixir defmodule TreeNode do defstruct val: nil, left: nil, right: nil end def average_of_levels(root) do result = [] queue = [root] while queue != [] do sum = 0 count = 0 temp = [] while queue != [] do node = List.first(queue) ...
dolphin
Please explain the reasoning behind the following solution and provide code in Scala: You are given a string `s` of lowercase English letters and an integer array `shifts` of the same length. Call the `shift()` of a letter, the next letter in the alphabet, (wrapping around so that `'z'` becomes `'a'`). * For exampl...
dolphin
Please focus on the efficiency of this problem and provide code in Groovy: There is a country of `n` cities numbered from `0` to `n - 1` where **all the cities are connected** by bi-directional roads. The roads are represented as a 2D integer array `edges` where `edges[i] = [xi, yi, timei]` denotes a road between citie...
dolphin
Please explain the reasoning behind the following solution and provide code in Lisp: Given a string `s` representing a valid expression, implement a basic calculator to evaluate it, and return _the result of the evaluation_. **Note:** You are **not** allowed to use any built-in function which evaluates strings as math...
dolphin
Please explain the reasoning behind the following solution and provide code in Haskell: You are given `n`​​​​​​ tasks labeled from `0` to `n - 1` represented by a 2D integer array `tasks`, where `tasks[i] = [enqueueTimei, processingTimei]` means that the `i​​​​​​th`​​​​ task will be available to process at `enqueueTime...
dolphin
port this code from Perl to Elixir: ```perl sub swapPairs { my ($head) = @_; return $head if !$head || !$head->{next}; my $second = $head->{next}; $head->{next} = swapPairs($second->{next}); $second->{next} = $head; return $second; } ```
dolphin
convert this code from Scheme to Elixir: ```scheme (define (subarraysDivByK nums k) (define prefix-sums-mod-k (make-vector k 0)) (vector-set! prefix-sums-mod-k 0 1) (define running-sum 0) (define count 0) (for-each (lambda (num) (set! running-sum (+ running-sum num)) (define mod (modulo (+ run...
dolphin
Please explain the following problem in detail and provide code in Erlang: 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** uppercase a...
dolphin
Please explain the following problem in detail and provide code in Swift: There is a singly-linked list `head` and we want to delete a node `node` in it. You are given the node to be deleted `node`. You will **not be given access** to the first node of `head`. All the values of the linked list are **unique**, and it ...
dolphin
Please focus on the functionality of this problem and provide code in Objective-C: Given an integer array `nums` of size `n`, return _the number with the value **closest** to_ `0` _in_ `nums`. If there are multiple answers, return _the number with the **largest** value_. **Example 1:** **Input:** nums = \[-4,-2,1,4,8...
dolphin
convert this code from Go to Ruby: ```go func maxBallValue(inventory []int, orders int) int { n := len(inventory) sort.Sort(sort.Reverse(sort.IntSlice(inventory))) ballValue := 1 totalValue := 0 i := 0 for orders > 0 { if i < n-1 && inventory[i] > inventory[i+1] && orders >= ba...
dolphin
port this code to Kotlin: ```objective-c #import <Foundation/Foundation.h> @interface Solution:NSObject +(int)minJumps:(NSArray<NSNumber *> *)arr; @end @implementation Solution +(int)minJumps:(NSArray<NSNumber *> *)arr{ NSInteger n = arr.count; if (n <= 1) { return 0; } NSMutableDictionary<NSN...
dolphin
Please focus on the efficiency of this problem and provide code in Clojure: You are given a **0-indexed** `m x n` binary matrix `grid`. A **0-indexed** `m x n` difference matrix `diff` is created with the following procedure: * Let the number of ones in the `ith` row be `onesRowi`. * Let the number of ones in the...
dolphin
translate this code to Objective-C: ```mojo sub twoSum(numbers as List[int], target as int) returns List[int]: my $left = 0 my $right = len(numbers) - 1 while $left < $right: my $current_sum = numbers[$left] + numbers[$right] if $current_sum == $target: return [$left + 1, $right ...
dolphin
Please write the following solution using Scheme: Convert a non-negative integer `num` to its English words representation. **Example 1:** **Input:** num = 123 **Output:** "One Hundred Twenty Three " **Example 2:** **Input:** num = 12345 **Output:** "Twelve Thousand Three Hundred Forty Five " **Example 3:** **I...
dolphin
Please explain the following problem in detail and provide code in python: You are currently designing a dynamic array. You are given a **0-indexed** integer array `nums`, where `nums[i]` is the number of elements that will be in the array at time `i`. In addition, you are given an integer `k`, the **maximum** number o...
dolphin
convert this code to Haskell: ```R num_strictly_increasing_subarrays <- function(nums) { n <- length(nums) count <- 0 sum <- 0 for (i in 2:n) { if (nums[i] > nums[i - 1]) { count <- count + 1 } else { count <- 0 } sum <- sum + count } return(sum + n) } ```
dolphin
Please write the following solution using Julia: A **boolean expression** is an expression that evaluates to either `true` or `false`. It can be in one of the following shapes: * `'t'` that evaluates to `true`. * `'f'` that evaluates to `false`. * `'!(subExpr)'` that evaluates to **the logical NOT** of the inner...
dolphin
Please focus on the functionality of this problem and provide code in R: The set `[1, 2, 3, ..., n]` contains a total of `n!` unique permutations. By listing and labeling all of the permutations in order, we get the following sequence for `n = 3`: 1. `"123 "` 2. `"132 "` 3. `"213 "` 4. `"231 "` 5. `"312 "` 6. `...
dolphin
Please write the following solution using Groovy: You are given a **0-indexed** integer array `nums` of **even** length. As long as `nums` is **not** empty, you must repetitively: * Find the minimum number in `nums` and remove it. * Find the maximum number in `nums` and remove it. * Calculate the average of the...
dolphin
Please explain the following problem in detail and provide code in C#: Given an integer array `nums` of size `n`, return _the minimum number of moves required to make all array elements equal_. In one move, you can increment `n - 1` elements of the array by `1`. **Example 1:** **Input:** nums = \[1,2,3\] **Output:**...
dolphin
port this code to Perl: ```python def maxAbsValExpr(arr1, arr2): result = 0 max_sum = [float('-inf')] * 4 for i in range(len(arr1)): max_sum[0] = max(max_sum[0], arr1[i] + arr2[i] + i) max_sum[1] = max(max_sum[1], arr1[i] - arr2[i] + i) max_sum[2] = max(max_sum[2], -arr1[i] + arr2[i...
dolphin
Please explain the reasoning behind the following solution and provide code in Ruby: Given a `root` of an [N-ary tree](https://leetcode.com/articles/introduction-to-n-ary-trees/), you need to compute the length of the diameter of the tree. The diameter of an N-ary tree is the length of the **longest** path between any...
dolphin
Please focus on the efficiency of this problem and provide code in Haskell: There are `n` people and `40` types of hats labeled from `1` to `40`. Given a 2D integer array `hats`, where `hats[i]` is a list of all hats preferred by the `ith` person. Return _the number of ways that the `n` people wear different hats to ...
dolphin
port this code from Haskell to Ruby: ```haskell stoneGameVI :: [Int] -> [Int] -> Int stoneGameVI aliceValues bobValues = let n = length aliceValues sums = reverse $ sort [(aliceValues !! i + bobValues !! i, i) | i <- [0..n-1]] aliceScore = sum [aliceValues !! i | (_,i) <- takeWhile (\(s,_) -> s > 0...
dolphin
translate this code from Scheme to Kotlin: ```scheme (define (convert-bst root) (define (convert-bst-helper root sum) (if (not (null? root)) (let ((right (convert-bst-helper (tree-right root) sum))) (set-tree-right! root right) (set! sum (+ sum (tree-value root))) (set-tree-v...
dolphin
convert this code to Erlang: ```scala object Solution { def isTree(n: Int, edges: Array[Array[Int]]): Boolean = { val neighbors = Array.fill(n)(List.empty[Int]) for (edge <- edges) { neighbors(edge(0)) ::= edge(1) neighbors(edge(1)) ::= edge(0) } val visited =...
dolphin
port this code to Lua: ```mojo sub sum_of_digits(n as int) as int { my $total = 0; my $positive = True; while $n > 0 { my $digit = $n % 10; $n //= 10; if $positive { $total += $digit; } else { $total -= $digit; } $positive = !$positi...
dolphin
Please focus on the functionality of this problem and provide code in c++: Given the array `nums`, for each `nums[i]` find out how many numbers in the array are smaller than it. That is, for each `nums[i]` you have to count the number of valid `j's` such that `j != i` **and** `nums[j] < nums[i]`. Return the answer in ...
dolphin
Please write the following solution using Swift: A string is a **valid parentheses string** (denoted **VPS**) if it meets one of the following: * It is an empty string `" "`, or a single character not equal to `"( "` or `") "`, * It can be written as `AB` (`A` concatenated with `B`), where `A` and `B` are **VPS**'...
dolphin
Please explain the reasoning behind the following solution and provide code in Clojure: We have an array of integers, `nums`, and an array of `requests` where `requests[i] = [starti, endi]`. The `ith` request asks for the sum of `nums[starti] + nums[starti + 1] + ... + nums[endi - 1] + nums[endi]`. Both `starti` and `e...
dolphin
Please focus on the functionality of this problem and provide code in Rust: 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 comput...
dolphin
Please focus on the efficiency of this problem and provide code in Go: You are given a string `num` representing **the digits** of a very large integer and an integer `k`. You are allowed to swap any two adjacent digits of the integer **at most** `k` times. Return _the minimum integer you can obtain also as a string_....
dolphin
Please focus on the functionality of this problem and provide code in Groovy: Suppose we have a file system that stores both files and directories. An example of one system is represented in the following picture: Here, we have `dir` as the only directory in the root. `dir` contains two subdirectories, `subdir1` and `...
dolphin
translate this code from c++ to Dart: ```cpp int maxBooks(vector<int>& books) { int n = books.size(); int max_books = 0; for (int l = 0; l < n; ++l) { int r = l + 1, books_taken = books[l], min_taken = books[l]; max_books = max(max_books, books_taken); while (r < n) { ...
dolphin
Please focus on the efficiency of this problem and provide code in Haskell: You are given an integer `n` indicating there are `n` specialty retail stores. There are `m` product types of varying amounts, which are given as a **0-indexed** integer array `quantities`, where `quantities[i]` represents the number of product...
dolphin
convert this code from Visual Basic .NET to Elixir: ```vb.net Public Function MaxDiff(nums As Integer()) As Integer If nums.Length < 2 Then Return -1 End If Dim min_elem As Integer = nums(0) Dim max_diff As Integer = -1 For i As Integer = 1 To nums.Length - 1 If nums(i) > m...
dolphin
Please focus on the efficiency of this problem and provide code in F#: A binary tree is **uni-valued** if every node in the tree has the same value. Given the `root` of a binary tree, return `true` _if the given tree is **uni-valued**, or_ `false` _otherwise._ **Example 1:** **Input:** root = \[1,1,1,1,1,null,1\] **...
dolphin
Please focus on the functionality of this problem and provide code in c++: 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` where: `arr[i] ...
dolphin
Please write the following solution using Dart: You have a binary tree with a small defect. There is **exactly one** invalid node where its right child incorrectly points to another node at the **same depth** but to the **invalid node's right**. Given the root of the binary tree with this defect, `root`, return _the r...
dolphin
Please focus on the algorithm of this problem and provide code in Object Pascal: Given the radius and the position of the center of a circle, implement the function `randPoint` which generates a uniform random point inside the circle. Implement the `Solution` class: * `Solution(double radius, double x_center, doubl...
dolphin
port this code to Erlang: ```r largest_odd_number <- function(num) { for (i in rev(seq_len(nchar(num)))) { if (as.integer(substr(num, i, i)) %% 2 != 0) { return(substr(num, 1, i)) } } return("") } ```
dolphin
convert this code from Swift to Go: ```swift func isGoodString(_ s: String) -> Bool { var dict = [Character: Int]() for c in s { dict[c, default: 0] += 1 } let values = Set(dict.values) return values.count == 1 } ```
dolphin
Please focus on the functionality of this problem and provide code in Lisp: Given an integer n, return _the smallest **prime palindrome** greater than or equal to_ `n`. An integer is **prime** if it has exactly two divisors: `1` and itself. Note that `1` is not a prime number. * For example, `2`, `3`, `5`, `7`, `11...
dolphin
Please explain the reasoning behind the following solution and provide code in Perl: Given an `m x n` integer matrix `heightMap` representing the height of each unit cell in a 2D elevation map, return _the volume of water it can trap after raining_. **Example 1:** **Input:** heightMap = \[\[1,4,3,1,3,2\],\[3,2,1,3,2,...
dolphin
Please focus on the algorithm of this problem and provide code in Object Pascal: The **variance** of a string is defined as the largest difference between the number of occurrences of **any** `2` characters present in the string. Note the two characters may or may not be the same. Given a string `s` consisting of lowe...
dolphin
Please focus on the algorithm of this problem and provide code in R: 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 element at the ...
dolphin
Please explain the following problem in detail and provide code in Kotlin: A tree is an undirected graph in which any two vertices are connected by _exactly_ one path. In other words, any connected graph without simple cycles is a tree. Given a tree of `n` nodes labelled from `0` to `n - 1`, and an array of `n - 1` `e...
dolphin
Please focus on the functionality of this problem and provide code in Lua: 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 `"cx...
dolphin
Please focus on the algorithm of this problem and provide code in Kotlin: 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 tree...
dolphin
Please explain the reasoning behind the following solution and provide code in Dart: You are given an integer array `nums`. You must perform **exactly one** operation where you can **replace** one element `nums[i]` with `nums[i] * nums[i]`. Return _the **maximum** possible subarray sum after **exactly one** operation_...
dolphin
Please write the following solution using Scala: Given 2 integers `n` and `start`. Your task is return **any** permutation `p` of `(0,1,2.....,2^n -1)` such that : * `p[0] = start` * `p[i]` and `p[i+1]` differ by only one bit in their binary representation. * `p[0]` and `p[2^n -1]` must also differ by only one b...
dolphin
port this code from Elixir to c++: ```elixir defmodule Solution do def xor_queries(arr, queries) do n = length(arr) prefix_xor = new_array(n+1) prefix_xor[0] = 0 for i <- 1..n do prefix_xor[i] = prefix_xor[i-1] lxor arr[i-1] end results = new_array(length(queries)) for i <- 0..(le...
dolphin
Please explain the reasoning behind the following solution and provide code in Scala: Given strings `s1` and `s2`, return _the minimum contiguous substring part of_ `s1`_, so that_ `s2` _is a subsequence of the part_. If there is no such window in `s1` that covers all characters in `s2`, return the empty string `" "`....
dolphin
Please explain the reasoning behind the following solution and provide code in javascript: You are given a positive integer `n`, you can do the following operation **any** number of times: * Add or subtract a **power** of `2` from `n`. Return _the **minimum** number of operations to make_ `n` _equal to_ `0`. A num...
dolphin
convert this code from Fortran to ANSI C: ```fortran function evalRPN(tokens) result (result) character(*), dimension(:), intent(in) :: tokens integer :: i, n, a, b integer, dimension(:), allocatable :: stack n = size(tokens) allocate(stack(n)) do i = 1, n if (tokens(i) == '+') then ...
dolphin
Please focus on the efficiency of this problem and provide code in Lua: Given an integer `n` and an integer array `rounds`. We have a circular track which consists of `n` sectors labeled from `1` to `n`. A marathon will be held on this track, the marathon consists of `m` rounds. The `ith` round starts at sector `rounds...
dolphin
translate this code from Visual Basic .NET to Julia: ```vb.net Function minPartitions(n As String) As Integer Dim max_digit As Integer = 0 For Each c As Char In n max_digit = Math.Max(max_digit, Integer.Parse(c)) If max_digit = 9 Then Exit For End If Next Return max_d...
dolphin
Please explain the reasoning behind the following solution and provide code in Rust: You are given a stream of points on the X-Y plane. Design an algorithm that: * **Adds** new points from the stream into a data structure. **Duplicate** points are allowed and should be treated as different points. * Given a query ...
dolphin
Please explain the reasoning behind the following solution and provide code in Erlang: You are given a directed graph with `n` nodes labeled from `0` to `n - 1`, where each node has **exactly one** outgoing edge. The graph is represented by a given **0-indexed** integer array `edges` of length `n`, where `edges[i]` in...
dolphin
Please write the following solution using javascript: You are given a string, `message`, and a positive integer, `limit`. You must **split** `message` into one or more **parts** based on `limit`. Each resulting part should have the suffix `" "`, where `"b "` is to be **replaced** with the total number of parts and `"a...
dolphin
Please explain the following problem in detail and provide code in Lisp: You are given two lists of closed intervals, `firstList` and `secondList`, where `firstList[i] = [starti, endi]` and `secondList[j] = [startj, endj]`. Each list of intervals is pairwise **disjoint** and in **sorted order**. Return _the intersecti...
dolphin
port this code from R to python: ```R min_operations <- function(nums) { min_prefix <- 0 prefix <- 0 for (num in nums) { prefix <- prefix + num min_prefix <- min(min_prefix, prefix) } if (min_prefix < 0) { return(-min_prefix) } else { return(0) } } ```
dolphin
Please focus on the functionality of this problem and provide code in Haskell: Given a string array `words`, return _the maximum value of_ `length(word[i]) * length(word[j])` _where the two words do not share common letters_. If no such two words exist, return `0`. **Example 1:** **Input:** words = \[ "abcw ", "baz "...
dolphin
Please explain the reasoning behind the following solution and provide code in Lisp: Given an integer `n`, your task is to count how many strings of length `n` can be formed under the following rules: * Each character is a lower case vowel (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`) * Each vowel `'a'` may only be followed...
dolphin
Please explain the following problem in detail and provide code in ANSI C: 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 le...
dolphin
translate this code to Kotlin: ```java public int sumOfFlooredPairs(int[] nums) { int mod = 1000000007; int maxVal = Integer.MIN_VALUE; for (int num : nums) { maxVal = Math.max(maxVal, num); } int[] count = new int[maxVal + 1]; long[] prefSum = new long[maxVal + 1]; for (int num : n...
dolphin
Please explain the following problem in detail and provide code in Scala: You have two types of tiles: a `2 x 1` domino shape and a tromino shape. You may rotate these shapes. Given an integer n, return _the number of ways to tile an_ `2 x n` _board_. Since the answer may be very large, return it **modulo** `109 + 7`....
dolphin
Please focus on the efficiency of this problem and provide code in Kotlin: Given two nodes of a binary tree `p` and `q`, return _their lowest common ancestor (LCA)_. Each node will have a reference to its parent node. The definition for `Node` is below: class Node { public int val; public Node left; publi...
dolphin
port this code to javascript: ```cpp #include <string> #include <vector> using namespace std; string findContestMatch(int n) { vector<string> matches(n); for (int i = 1; i <= n; i++) { matches[i - 1] = to_string(i); } while (n > 1) { for (int i = 0; i < n / 2; i++) { matche...
dolphin
convert this code to Objective-C: ```c #include <stdio.h> #include <limits.h> int minimumWorkSessions(int* tasks, int tasksSize, int sessionTime) { int n = tasksSize; int dp[1 << n]; for (int i = 0; i < (1 << n); i++) { dp[i] = INT_MAX; } dp[0] = 0; for (int mask = 1; mask < (1 << n); m...
dolphin
Please explain the following problem in detail and provide code in Fortran: Two strings `X` and `Y` are similar if we can swap two letters (in different positions) of `X`, so that it equals `Y`. Also two strings `X` and `Y` are similar if they are equal. For example, `"tars "` and `"rats "` are similar (swapping at po...
dolphin
translate this code to Lua: ```cpp #include <cmath> #include <vector> int smallestDivisor(std::vector<int>& nums, int threshold) { int left = 1, right = 1e6; while (left < right) { int mid = (left + right) / 2; int sum = 0; for (int n : nums) { sum += std::ceil(1.0 * n / mid...
dolphin
Please explain the following problem in detail and provide code in Julia: You are given an `m x n` matrix of characters `box` representing a side-view of a box. Each cell of the box is one of the following: * A stone `'#'` * A stationary obstacle `'*'` * Empty `'.'` The box is rotated **90 degrees clockwise**, ...
dolphin
Please explain the reasoning behind the following solution and provide code in java: There are `n` children standing in a line. Each child is assigned a rating value given in the integer array `ratings`. You are giving candies to these children subjected to the following requirements: * Each child must have at leas...
dolphin
Please explain the reasoning behind the following solution and provide code in Kotlin: Given an array of unique integers, `arr`, where each integer `arr[i]` is strictly greater than `1`. We make a binary tree using these integers, and each number may be used for any number of times. Each non-leaf node's value should b...
dolphin
Please focus on the functionality of this problem and provide code in Haskell: Given an integer array `nums`, return _the sum of divisors of the integers in that array that have exactly four divisors_. If there is no such integer in the array, return `0`. **Example 1:** **Input:** nums = \[21,4,7\] **Output:** 32 **E...
dolphin
Please write the following solution using F#: You have been tasked with writing a program for a popular bank that will automate all its incoming transactions (transfer, deposit, and withdraw). The bank has `n` accounts numbered from `1` to `n`. The initial balance of each account is stored in a **0-indexed** integer ar...
dolphin
Please explain the reasoning behind the following solution and provide code in Groovy: Given an `m x n` integer matrix `matrix`, if an element is `0`, set its entire row and column to `0`'s. You must do it [in place](https://en.wikipedia.org/wiki/In-place_algorithm). **Example 1:** **Input:** matrix = \[\[1,1,1\],\[...
dolphin
convert this code to Julia: ```cpp struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(nullptr) {} }; ListNode* deleteMiddle(ListNode* head) { if (!head || !head->next) return head; ListNode* slow = head; ListNode* fast = head; ListNode* prev = nullptr; while ...
dolphin
Please explain the following problem in detail and provide code in Elixir: You are given a **0-indexed** integer array `books` of length `n` where `books[i]` denotes the number of books on the `ith` shelf of a bookshelf. You are going to take books from a **contiguous** section of the bookshelf spanning from `l` to `r...
dolphin
port this code from Go to Kotlin: ```go package main import ( "fmt" ) func maxBeauty(flowers []int, newFlowers int, target int, full int, partial int) int { beauty := 0 for _, f := range flowers { if f >= target { beauty += full } else { beauty += partial * f } } newFlowersLeft := newFlowers sort.In...
dolphin
Please write the following solution using Erlang: You are given an `m x n` grid `rooms` initialized with these three possible values. * `-1` A wall or an obstacle. * `0` A gate. * `INF` Infinity means an empty room. We use the value `231 - 1 = 2147483647` to represent `INF` as you may assume that the distance to...
dolphin
translate this code to TypeScript: ```fortran function count_stretchy_words(s, words) result(count) character(*), intent(in) :: s character(:), dimension(:), intent(in) :: words integer :: i, j, k, count count = 0 do k = 1, size(words) i = 1 j = 1 do while (i <= len(s) .and. j <= len(words(k))) ...
dolphin
Please explain the reasoning behind the following solution and provide code in TypeScript: Given a binary tree with the following rules: 1. `root.val == 0` 2. If `treeNode.val == x` and `treeNode.left != null`, then `treeNode.left.val == 2 * x + 1` 3. If `treeNode.val == x` and `treeNode.right != null`, then `treeN...
dolphin