instruction_seed
stringlengths
29
40.5k
source
stringclasses
6 values
Please write the following solution using Fortran: We can represent a sentence as an array of words, for example, the sentence `"I am happy with leetcode "` can be represented as `arr = [ "I ", "am ",happy ", "with ", "leetcode "]`. Given two sentences `sentence1` and `sentence2` each represented as a string array and...
dolphin
translate this code to java: ```clojure (defn delete-columns [strs] (let [n (count strs) m (count (first strs))] (count (filter #(not (apply < %)) (for i (range m) (map #(nth % i) strs)))))) (delete-columns ["cba " "daf " "ghi "]) ; 1 (delete-columns ["a " "b "]) ;...
dolphin
Please write the following solution using Visual Basic .NET: You are given an array `points` containing the coordinates of points on a 2D plane, sorted by the x-values, where `points[i] = [xi, yi]` such that `xi < xj` for all `1 <= i < j <= points.length`. You are also given an integer `k`. Return _the maximum value o...
dolphin
Please explain the reasoning behind the following solution and provide code in python: You are given two **0-indexed** strings `word1` and `word2`. A **move** consists of choosing two indices `i` and `j` such that `0 <= i < word1.length` and `0 <= j < word2.length` and swapping `word1[i]` with `word2[j]`. Return `tru...
dolphin
convert this code to C#: ```groovy import java.util.LinkedList import java.util.HashMap int minJumps(int[] arr) { int n = arr.length if (n <= 1) { return 0 } HashMap<Integer, LinkedList<Integer>> value_indices = new HashMap<>() for (int i = 0; i < n; i++) { if (!value_indices.conta...
dolphin
port this code to Visual Basic .NET: ```elixir defmodule Sudoku do def is_valid(board, row, col, c) do for i <- 0..8 do if board[i][col] == c, do: return false if board[row][i] == c, do: return false if board[3 * (row // 3) + i // 3][3 * (col // 3) + i mod 3] == c, do: return false end t...
dolphin
translate this code from Elixir to javascript: ```elixir defmodule Solution do @moduledoc """ Given an array of integers `nums` and an integer `target`. Return the number of non-empty subsequences of `nums` such that the sum of the minimum and maximum element on it is less or equal to `target`. Since the answe...
dolphin
Please focus on the efficiency of this problem and provide code in Lisp: There are `n` people standing in a line labeled from `1` to `n`. The first person in the line is holding a pillow initially. Every second, the person holding the pillow passes it to the next person standing in the line. Once the pillow reaches the...
dolphin
Please focus on the functionality of this problem and provide code in Scheme: You are given two integers `n` and `k` and two integer arrays `speed` and `efficiency` both of length `n`. There are `n` engineers numbered from `1` to `n`. `speed[i]` and `efficiency[i]` represent the speed and efficiency of the `ith` engine...
dolphin
Please write the following solution using Visual Basic .NET: There is a computer that can run an unlimited number of tasks **at the same time**. You are given a 2D integer array `tasks` where `tasks[i] = [starti, endi, durationi]` indicates that the `ith` task should run for a total of `durationi` seconds (not necessar...
dolphin
Please explain the following problem in detail and provide code in Visual Basic .NET: Given an array of integers `nums` and an integer `target`, return _indices of the two numbers such that they add up to `target`_. You may assume that each input would have **_exactly_ one solution**, and you may not use the _same_ el...
dolphin
Please write the following solution using Object Pascal: Given the coordinates of two **rectilinear** rectangles in a 2D plane, return _the total area covered by the two rectangles_. The first rectangle is defined by its **bottom-left** corner `(ax1, ay1)` and its **top-right** corner `(ax2, ay2)`. The second rectang...
dolphin
Please focus on the algorithm of this problem and provide code in ANSI C: Given an array of strings `queries` and a string `pattern`, return a boolean array `answer` where `answer[i]` is `true` if `queries[i]` matches `pattern`, and `false` otherwise. A query word `queries[i]` matches `pattern` if you can insert lower...
dolphin
Please focus on the algorithm of this problem and provide code in F#: Given an integer `num`, return _three consecutive integers (as a sorted array)_ _that **sum** to_ `num`. If `num` cannot be expressed as the sum of three consecutive integers, return _an **empty** array._ **Example 1:** **Input:** num = 33 **Output...
dolphin
Please explain the reasoning behind the following solution and provide code in java: A **wonderful** string is a string where **at most one** letter appears an **odd** number of times. * For example, `"ccjjc "` and `"abab "` are wonderful, but `"ab "` is not. Given a string `word` that consists of the first ten low...
dolphin
Please focus on the functionality of this problem and provide code in TypeScript: You are given a positive integer `num`. You may swap any two digits of `num` that have the same **parity** (i.e. both odd digits or both even digits). Return _the **largest** possible value of_ `num` _after **any** number of swaps._ **E...
dolphin
port this code from Visual Basic .NET to Dart: ```vb.net Public Function SmallestFairNumber(ByVal n As Integer) As Integer While True Dim k As Integer = n Dim even As Integer = 0 Dim odd As Integer = 0 While k > 0 If k Mod 2 = 0 Then even += 1 ...
dolphin
translate this code from Clojure to Visual Basic .NET: ```clojure (defn find-original-array [encoded first] (let [arr (cons first []) n (dec (count encoded))] (dotimes [i n] (let [xored (bit-xor (nth encoded i) (nth arr i))] (conj! arr xored)))) arr) ``` Note: The `!` in `conj!` means tha...
dolphin
Please explain the reasoning behind the following solution and provide code in Go: Given an array of strings `strs`, return _the length of the **longest uncommon subsequence** between them_. If the longest uncommon subsequence does not exist, return `-1`. An **uncommon subsequence** between an array of strings is a st...
dolphin
Please explain the reasoning behind the following solution and provide code in Fortran: An array is **squareful** if the sum of every pair of adjacent elements is a **perfect square**. Given an integer array nums, return _the number of permutations of_ `nums` _that are **squareful**_. Two permutations `perm1` and `pe...
dolphin
translate this code to Groovy: ```erlang -module(numWays). -export([numWays/2]). numWays(0, _) -> 0; numWays(1, K) -> K; numWays(N, K) -> Same = K, Different = K * (K - 1), numWays(N, 2, Same, Different, K). numWays(N, N, Same, Different, _) -> Same + Different; numWays(N, I, Same, Different, K) -> ...
dolphin
Please write the following solution using Objective-C: You are given a positive integer `n`. Continuously replace `n` with the sum of its **prime factors**. * Note that if a prime factor divides `n` multiple times, it should be included in the sum as many times as it divides `n`. Return _the smallest value_ `n` _w...
dolphin
Please explain the reasoning behind the following solution and provide code in python: Given the `head` of a singly linked list that is sorted in **non-decreasing** order using the **absolute values** of its nodes, return _the list sorted in **non-decreasing** order using the **actual values** of its nodes_. **Example...
dolphin
Please explain the reasoning behind the following solution and provide code in Perl: Given a string `date` representing a [Gregorian calendar](https://en.wikipedia.org/wiki/Gregorian_calendar) date formatted as `YYYY-MM-DD`, return _the day number of the year_. **Example 1:** **Input:** date = "2019-01-09 " **Output...
dolphin
Please explain the reasoning behind the following solution and provide code in Go: You are given an integer array `cards` where `cards[i]` represents the **value** of the `ith` card. A pair of cards are **matching** if the cards have the **same** value. Return _the **minimum** number of **consecutive** cards you have ...
dolphin
Please write the following solution using javascript: You are given an immutable linked list, print out all values of each node in reverse with the help of the following interface: * `ImmutableListNode`: An interface of immutable linked list, you are given the head of the list. You need to use the following functio...
dolphin
Please focus on the algorithm of this problem and provide code in Ruby: 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 in...
dolphin
Please focus on the efficiency of this problem and provide code in Julia: A cell `(r, c)` of an excel sheet is represented as a string `" "` where: * denotes the column number `c` of the cell. It is represented by **alphabetical letters**. * For example, the `1st` column is denoted by `'A'`, the `2nd` by `'B'`...
dolphin
Please explain the reasoning behind the following solution and provide code in c++: Given the `root` of a binary tree, the depth of each node is **the shortest distance to the root**. Return _the smallest subtree_ such that it contains **all the deepest nodes** in the original tree. A node is called **the deepest** i...
dolphin
Please explain the reasoning behind the following solution and provide code in PHP: Given a list of `phrases`, generate a list of Before and After puzzles. A _phrase_ is a string that consists of lowercase English letters and spaces only. No space appears in the start or the end of a phrase. There are no consecutive s...
dolphin
Please write the following solution using Dart: There is a city composed of `n x n` blocks, where each block contains a single building shaped like a vertical square prism. You are given a **0-indexed** `n x n` integer matrix `grid` where `grid[r][c]` represents the **height** of the building located in the block at ro...
dolphin
Please explain the following problem in detail and provide code in Kotlin: Strings `s1` and `s2` are `k`**\-similar** (for some non-negative integer `k`) if we can swap the positions of two letters in `s1` exactly `k` times so that the resulting string equals `s2`. Given two anagrams `s1` and `s2`, return the smallest...
dolphin
Please focus on the efficiency of this problem and provide code in Swift: There are `n` **piles** of coins on a table. Each pile consists of a **positive number** of coins of assorted denominations. In one move, you can choose any coin on **top** of any pile, remove it, and add it to your wallet. Given a list `piles`...
dolphin
Please focus on the algorithm of this problem and provide code in C#: Consider a matrix `M` with dimensions `width * height`, such that every cell has value `0` or `1`, and any **square** sub-matrix of `M` of size `sideLength * sideLength` has at most `maxOnes` ones. Return the maximum possible number of ones that the...
dolphin
Please focus on the efficiency of this problem and provide code in Swift: Winter is coming! During the contest, your first job is to design a standard heater with a fixed warm radius to warm all the houses. Every house can be warmed, as long as the house is within the heater's warm radius range. Given the positions o...
dolphin
convert this code from Object Pascal to javascript: ```pascal function AverageEvenDivisibleByThree(nums: array of Integer): Integer; var total, count, num: Integer; begin total := 0; count := 0; for num in nums do begin if (num mod 2 = 0) and (num mod 3 = 0) then begin total := total + num; ...
dolphin
port this code to Scala: ```objective-c BOOL isDistinct(int n) { NSMutableSet *uniqueDigits = [NSMutableSet new]; while (n > 0) { int digit = n % 10; if ([uniqueDigits containsObject:@(digit)]) { return NO; } [uniqueDigits addObject:@(digit)]; n /= 10; } ...
dolphin
Please explain the following problem in detail and provide code in ANSI C: Consider a function that implements an algorithm **similar** to [Binary Search](https://leetcode.com/explore/learn/card/binary-search/). The function has two input parameters: `sequence` is a sequence of integers, and `target` is an integer valu...
dolphin
translate this code from F# to Perl: ```fsharp let modValue = 1000000007 let decimalValueOfBinaryString n = let mutable res = 0 let mutable length = 0 for i in 1..n do let mutable k = i while k > 0 do res <- (res * 2 + k % 2) % modValue k <- k / 2 le...
dolphin
Please write the following solution using Julia: Given the `root` of a binary tree, return _the postorder traversal of its nodes' values_. **Example 1:** **Input:** root = \[1,null,2,3\] **Output:** \[3,2,1\] **Example 2:** **Input:** root = \[\] **Output:** \[\] **Example 3:** **Input:** root = \[1\] **Output:**...
dolphin
port this code to java: ```fortran function reconstructMatrix(upper, lower, colsum) result(result) integer :: upper, lower, colsum(:), n, i, j integer, dimension(2, :), allocatable :: result n = size(colsum) allocate(result(2,n)) result = 0 do i = 1, n if (colsum(i) == 2) then result(1,i) = ...
dolphin
Please explain the reasoning behind the following solution and provide code in Scheme: You are given the `root` of a binary search tree (BST) and an integer `val`. Find the node in the BST that the node's value equals `val` and return the subtree rooted with that node. If such a node does not exist, return `null`. **...
dolphin
port this code from Object Pascal to Scheme: ```pascal type TreeNode = class val: Integer; left: TreeNode; right: TreeNode; constructor Create(x: Integer); end; BSTIterator = class private stack: TStack<TreeNode>; procedure PushLeft(node: TreeNode); public constructor Create(root:...
dolphin
Please write the following solution using C#: You are given a doubly linked list, which contains nodes that have a next pointer, a previous pointer, and an additional **child pointer**. This child pointer may or may not point to a separate doubly linked list, also containing these special nodes. These child lists may h...
dolphin
port this code to Visual Basic .NET: ```scheme (define (max-consecutive-floors-without-special-floor bottom top special) (sort special <) (let ((max-consecutive (- (car special) bottom 1))) (let loop ((i 0)) (if (< i (- (length special) 1)) (let ((consecutive (- (list-ref special (+ i 1)) (list-...
dolphin
port this code from Ruby to Rust: ```ruby def abbreviated_product(left, right) count_zeros = 0 product = 1 (left..right).each do |i| product *= i end while product % 10 == 0 count_zeros += 1 product /= 10 end if product >= 10 product_string = product.to_s ...
dolphin
convert this code to Lua: ```haskell wiggleMaxLength :: [Int] -> Int wiggleMaxLength nums | length nums < 2 = length nums | otherwise = max up down where (up, down) = foldl update (1, 1) $ zip nums (tail nums) update (u, d) (x, y) | x < y = (d+1, d+1) | x > y = (u+1, u+...
dolphin
convert this code to Swift: ```go func findTarget(root *TreeNode, k int) bool { nodes := make(map[int]bool) return findNode(root, k, nodes) } func findNode(root *TreeNode, k int, nodes map[int]bool) bool { if root == nil { return false } if nodes[k-root.Val] { return true } ...
dolphin
Please focus on the functionality of this problem and provide code in Scheme: You are given a positive integer `n`. Each digit of `n` has a sign according to the following rules: * The **most significant digit** is assigned a **positive** sign. * Each other digit has an opposite sign to its adjacent digits. Retur...
dolphin
port this code to Julia: ```objective-c @interface TreeNode : NSObject @property (nonatomic, assign) NSInteger val; @property (nonatomic, strong) TreeNode *left; @property (nonatomic, strong) TreeNode *right; - (instancetype)initWithVal:(NSInteger)val left:(TreeNode *)left right:(TreeNode *)right; @end @implementat...
dolphin
Please focus on the algorithm of this problem and provide code in Lua: There is a row of `m` houses in a small city, each house must be painted with one of the `n` colors (labeled from `1` to `n`), some houses that have been painted last summer should not be painted again. A neighborhood is a maximal group of continuo...
dolphin
Please explain the following problem in detail and provide code in Clojure: A **permutation** of an array of integers is an arrangement of its members into a sequence or linear order. * For example, for `arr = [1,2,3]`, the following are all the permutations of `arr`: `[1,2,3], [1,3,2], [2, 1, 3], [2, 3, 1], [3,1,2]...
dolphin
translate this code to Ruby: ```haskell concatenationValue :: [Int] -> Int concatenationValue nums = go nums 0 where go [] acc = acc go [x] acc = acc + x go (x:xs) acc = go (init xs) (acc + read (show x ++ show (last xs))) ``` Note that the function `read` is used to convert the concatenated string into ...
dolphin
Please explain the reasoning behind the following solution and provide code in Rust: Given two strings `str1` and `str2` of the same length, determine whether you can transform `str1` into `str2` by doing **zero or more** _conversions_. In one conversion you can convert **all** occurrences of one character in `str1` t...
dolphin
Please focus on the algorithm of this problem and provide code in TypeScript: You are given two strings, `word1` and `word2`. You want to construct a string in the following manner: * Choose some **non-empty** subsequence `subsequence1` from `word1`. * Choose some **non-empty** subsequence `subsequence2` from `wor...
dolphin
Please focus on the functionality of this problem and provide code in Visual Basic .NET: We have `n` cities labeled from `1` to `n`. Two different cities with labels `x` and `y` are directly connected by a bidirectional road if and only if `x` and `y` share a common divisor **strictly greater** than some `threshold`. M...
dolphin
port this code to javascript: ```clojure (defn inorder [node nodes] (when node (inorder (.left node) nodes) (when (and (.val (nth nodes 1)) (> (.val (nth nodes 1)) (.val node))) (when (nil? (nth nodes 0)) (assoc nodes 0 (nth nodes 1))) (assoc nodes 2 node)) (assoc nodes 1 node) (inorder (....
dolphin
port this code from Mojo to TypeScript: ```mojo class TreeNode(val, left, right): def __init__(self): self.val = val self.left = left self.right = right def KthLargestLevelSum(root, k): level_sums = [] q = Queue() q.put(root) while not q.empty(): level_sum = 0 ...
dolphin
translate this code from Dart to Swift: ```dart import 'dart:math'; int numSquarefulPerms(List<int> nums) { int count = 0; Set<int> keySet = nums.toSet(); Map<int, int> counter = {}; for (int num in nums) { counter[num] = counter.containsKey(num) ? counter[num] + 1 : 1; } bool isSquare(int n) => sqrt(...
dolphin
Please focus on the algorithm of this problem and provide code in Scheme: In a row of dominoes, `tops[i]` and `bottoms[i]` represent the top and bottom halves of the `ith` domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.) We may rotate the `ith` domino, so that `tops[i]` and `bo...
dolphin
Please explain the following problem in detail and provide code in F#: You are given two positive integer arrays `nums` and `numsDivide`. You can delete any number of elements from `nums`. Return _the **minimum** number of deletions such that the **smallest** element in_ `nums` _**divides** all the elements of_ `numsD...
dolphin
Please write the following solution using ANSI C: You are given the `root` of a binary search tree (BST) and an integer `val`. Find the node in the BST that the node's value equals `val` and return the subtree rooted with that node. If such a node does not exist, return `null`. **Example 1:** **Input:** root = \[4,2...
dolphin
Please write the following solution using F#: You are given an array `nums` consisting of **positive** integers. You have to take each integer in the array, **reverse its digits**, and add it to the end of the array. You should apply this operation to the original integers in `nums`. Return _the number of **distinct*...
dolphin
Please explain the reasoning behind the following solution and provide code in R: Implement [pow(x, n)](http://www.cplusplus.com/reference/valarray/pow/), which calculates `x` raised to the power `n` (i.e., `xn`). **Example 1:** **Input:** x = 2.00000, n = 10 **Output:** 1024.00000 **Example 2:** **Input:** x = 2.1...
dolphin
Please focus on the algorithm of this problem and provide code in Kotlin: You have a **browser** of one tab where you start on the `homepage` and you can visit another `url`, get back in the history number of `steps` or move forward in the history number of `steps`. Implement the `BrowserHistory` class: * `BrowserH...
dolphin
port this code from C# to Haskell: ```csharp using System.Collections.Generic; using System.Linq; public class Solution { public int NumBusesToDestination(int[][] routes, int source, int target) { if (source == target) { return 0; } var stopToBuses = new Dictionary<int,...
dolphin
Please explain the following problem in detail and provide code in Object Pascal: We can represent a sentence as an array of words, for example, the sentence `"I am happy with leetcode "` can be represented as `arr = [ "I ", "am ",happy ", "with ", "leetcode "]`. Given two sentences `sentence1` and `sentence2` each re...
dolphin
Please explain the following problem in detail and provide code in Scala: You are given an integer `n` and an array of **unique** integers `blacklist`. Design an algorithm to pick a random integer in the range `[0, n - 1]` that is **not** in `blacklist`. Any integer that is in the mentioned range and not in `blacklist`...
dolphin
Please focus on the algorithm of this problem and provide code in Ruby: You are given an `m x n` `grid` where each cell can have one of three values: * `0` representing an empty cell, * `1` representing a fresh orange, or * `2` representing a rotten orange. Every minute, any fresh orange that is **4-directional...
dolphin
Please focus on the algorithm of this problem and provide code in Kotlin: Given an array `arr` that represents a permutation of numbers from `1` to `n`. You have a binary string of size `n` that initially has all its bits set to zero. At each step `i` (assuming both the binary string and `arr` are 1-indexed) from `1` ...
dolphin
Please explain the reasoning behind the following solution and provide code in Elixir: Under the grammar given below, strings can represent a set of lowercase words. Let `R(expr)` denote the set of words the expression represents. The grammar can best be understood through simple examples: * Single letters represen...
dolphin
Please write the following solution using python: A sequence of numbers is called **arithmetic** if it consists of at least two elements, and the difference between every two consecutive elements is the same. More formally, a sequence `s` is arithmetic if and only if `s[i+1] - s[i] == s[1] - s[0]` for all valid `i`. F...
dolphin
port this code to Scheme: ```ruby def min_operations(nums, queries) answer = [] queries.each do |query| operations = 0 nums.each do |num| operations += (num - query).abs end answer << operations end answer end ```
dolphin
Please write the following solution using Object Pascal: You are given an array `people` where `people[i]` is the weight of the `ith` person, and an **infinite number of boats** where each boat can carry a maximum weight of `limit`. Each boat carries at most two people at the same time, provided the sum of the weight o...
dolphin
Please explain the following problem in detail and provide code in Groovy: A parentheses string is a **non-empty** string consisting only of `'('` and `')'`. It is valid if **any** of the following conditions is **true**: * It is `()`. * It can be written as `AB` (`A` concatenated with `B`), where `A` and `B` are ...
dolphin
Please explain the following problem in detail and provide code in Rust: Roman numerals are represented by seven different symbols: `I`, `V`, `X`, `L`, `C`, `D` and `M`. **Symbol** **Value** I 1 V 5 X 10 L 50 C 100 D 500 M 1000 ...
dolphin
Please write the following solution using Mojo: Given the `root` of a binary tree, construct a string consisting of parenthesis and integers from a binary tree with the preorder traversal way, and return it. Omit all the empty parenthesis pairs that do not affect the one-to-one mapping relationship between the string ...
dolphin
Please focus on the functionality of this problem and provide code in Clojure: Given an integer array `nums` and an integer `k`, return _the number of **subarrays** of_ `nums` _where the greatest common divisor of the subarray's elements is_ `k`. A **subarray** is a contiguous non-empty sequence of elements within an ...
dolphin
port this code to Elixir: ```erlang -module(max_and_sum). -export([max_and_sum/2]). max_and_sum(Nums, NumSlots) -> Slot = lists:seq(0, NumSlots), max_and_sum_helper(Nums, Slot, NumSlots). max_and_sum_helper([], Slot, _) -> lists:sum(Slot); max_and_sum_helper([Num | Tail], Slot, NumSlots) -> NewSlot = ...
dolphin
port this code to Dart: ```ruby def largest_overlap(img1, img2) n = img1.length max_overlap = 0 for row_shift in (-n+1)..(n-1) for col_shift in (-n+1)..(n-1) overlap = 0 (max(row_shift,0)...min(n+row_shift,n)).each do |i| (max(col_shift,0)...min(n+col_shift,n...
dolphin
Please explain the reasoning behind the following solution and provide code in Objective-C: Given an array `nums` of **distinct** positive integers, return _the number of tuples_ `(a, b, c, d)` _such that_ `a * b = c * d` _where_ `a`_,_ `b`_,_ `c`_, and_ `d` _are elements of_ `nums`_, and_ `a != b != c != d`_._ **Exam...
dolphin
translate this code to ANSI C: ```rust fn find_the_city(n: i32, edges: Vec<Vec<i32>>, distance_threshold: i32) -> i32 { let inf = 1_000_000; let mut distance = vec![vec![inf; n as usize]; n as usize]; for edge in edges.iter() { distance[edge[0] as usize][edge[1] as usize] = edge[2]; distance...
dolphin
translate this code to Lua: ```java import java.util.*; public String largestMultipleOfThree(int[] digits) { int sum = 0, count[] = new int[3]; for (int d : digits) { sum += d; count[d % 3]++; } if (sum % 3 == 1) { if (count[1] >= 1) count[1]--; else count[2] -= 2...
dolphin
convert this code to Perl: ```ruby def minimum_coin_moves(root) required_moves = 0 def dfs(node) return 0 if node.nil? left = dfs(node.left) right = dfs(node.right) required_moves += (left.abs + right.abs) node.val + left + right - 1 end dfs(root) required_moves end ```
dolphin
port this code to TypeScript: ```R numOfArrays <- function(n, maxValue){ mod <- 10^9 + 7 dp <- rep(0, maxValue + 1) for(i in 1:(maxValue)){ dp[i] <- i } for(i in 2:n){ for(j in maxValue:1){ dp[j] <- (dp[j] + dp[j-1]) %% mod } } return(dp[maxValue]) } ```
dolphin
translate this code from Go to Elixir: ```go func maxSumNumbersWithEqualSumOfDigits(nums []int) int { digitSumToMax := make(map[int]int) ans := -1 for _, num := range nums { sumOfDigits := 0 for num > 0 { sumOfDigits += num % 10 num /= 10 } ...
dolphin
Please explain the reasoning behind the following solution and provide code in Perl: You are given an integer array `deck` where `deck[i]` represents the number written on the `ith` card. Partition the cards into **one or more groups** such that: * Each group has **exactly** `x` cards where `x > 1`, and * All the...
dolphin
port this code to Go: ```dart import 'dart:collection'; int maxSumEvents(List<List<int>> events, int k) { events.sort((a, b) => a[1].compareTo(b[1])); var queue = PriorityQueue<List<int>>(compareEvents); var value = 0; for (var event in events) { var startDay = event[0]; var endDay = event[1]; v...
dolphin
convert this code from python to Objective-C: ```python def calculate_summation_of_absolute_differences(nums): n = len(nums) result = [0] * n for i in range(n): for j in range(n): if i != j: result[i] += abs(nums[i] - nums[j]) return result ```
dolphin
Please write the following solution using Clojure: Given an integer array `nums`, move all the even integers at the beginning of the array followed by all the odd integers. Return _**any array** that satisfies this condition_. **Example 1:** **Input:** nums = \[3,1,2,4\] **Output:** \[2,4,3,1\] **Explanation:** The ...
dolphin
Please explain the reasoning behind the following solution and provide code in Clojure: Given two integer arrays `nums1` and `nums2` of length `n`, count the pairs of indices `(i, j)` such that `i < j` and `nums1[i] + nums1[j] > nums2[i] + nums2[j]`. Return _the **number of pairs** satisfying the condition._ **Exampl...
dolphin
Please explain the reasoning behind the following solution and provide code in Lisp: You are given an `m x n` binary matrix `grid`. In one operation, you can choose **any** row or column and flip each value in that row or column (i.e., changing all `0`'s to `1`'s, and all `1`'s to `0`'s). Return `true` _if it is poss...
dolphin
translate this code from java to Fortran: ```java public int characterReplacement(String s, int k) { int n = s.length(); int left = 0, right = 0, maxFreq = 0, result = 0; int[] freq = new int[26]; for (right = 0; right < n; right++) { freq[s.charAt(right) - 'A']++; maxFreq = Math.ma...
dolphin
Please focus on the efficiency of this problem and provide code in Julia: There is an undirected connected tree with `n` nodes labeled from `0` to `n - 1` and `n - 1` edges. You are given a **0-indexed** integer array `nums` of length `n` where `nums[i]` represents the value of the `ith` node. You are also given a 2D ...
dolphin
Please write the following solution using Swift: 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 of integers `nums`, return...
dolphin
translate this code from Lisp to C#: ```lisp (defun decode (encoded) (let* ((n (+ (length encoded) 1)) (total-xor (loop for i from 1 to n reduce (logxor acc i))) (non-first-xor (loop for i from 1 below n by 2 reduce (logxor acc (nth i encoded))...
dolphin
Please explain the reasoning behind the following solution and provide code in Haskell: The [Hamming distance](https://en.wikipedia.org/wiki/Hamming_distance) between two integers is the number of positions at which the corresponding bits are different. Given two integers `x` and `y`, return _the **Hamming distance** ...
dolphin
Please explain the reasoning behind the following solution and provide code in Scheme: Given an initial array `arr`, every day you produce a new array using the array of the previous day. On the `i`\-th day, you do the following operations on the array of day `i-1` to produce the array of day `i`: 1. If an element i...
dolphin
Please explain the reasoning behind the following solution and provide code in Scheme: Given two strings `s1` and `s2`, return _the lowest **ASCII** sum of deleted characters to make two strings equal_. **Example 1:** **Input:** s1 = "sea ", s2 = "eat " **Output:** 231 **Explanation:** Deleting "s " from "sea " a...
dolphin
Please write the following solution using SmallTalk: Given a string `s` containing just the characters `'('`, `')'`, `'{'`, `'}'`, `'['` and `']'`, determine if the input string is valid. An input string is valid if: 1. Open brackets must be closed by the same type of brackets. 2. Open brackets must be closed in th...
dolphin