instruction_seed
stringlengths
29
40.5k
source
stringclasses
6 values
Please focus on the algorithm of this problem and provide code in F#: Given a string `s` and an integer `k`, rearrange `s` such that the same characters are **at least** distance `k` from each other. If it is not possible to rearrange the string, return an empty string `" "`. **Example 1:** **Input:** s = "aabbcc ",...
dolphin
Please explain the reasoning behind the following solution and provide code in Kotlin: You are given an array of integers `nums` represents the numbers written on a chalkboard. Alice and Bob take turns erasing exactly one number from the chalkboard, with Alice starting first. If erasing a number causes the bitwise XOR...
dolphin
Please explain the reasoning behind the following solution and provide code in Lisp: You are given an array of strings `words`. Each element of `words` consists of **two** lowercase English letters. Create the **longest possible palindrome** by selecting some elements from `words` and concatenating them in **any order...
dolphin
Please explain the following problem in detail and provide code in Rust: 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 t...
dolphin
Please explain the following problem in detail and provide code in F#: Given an integer `num`, return _a string representing its hexadecimal representation_. For negative integers, [two's complement](https://en.wikipedia.org/wiki/Two%27s_complement) method is used. All the letters in the answer string should be lowerc...
dolphin
Please explain the following problem in detail and provide code in Julia: 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 ass...
dolphin
port this code to Julia: ```vb.net Public Function CountSquareFreeSubsets(nums As Integer()) As Integer Dim counter As New Dictionary(Of Integer, Integer) For Each num In nums If counter.ContainsKey(num) Then counter(num) += 1 Else counter(num) = 1 End If Next...
dolphin
Please write the following solution using c++: You are given a string `num` consisting of digits only. Return _the **largest palindromic** integer (in the form of a string) that can be formed using digits taken from_ `num`. It should not contain **leading zeroes**. **Notes:** * You do **not** need to use all the d...
dolphin
port this code from Fortran to c++: ```fortran function find_prefix_word_index(sentence, searchWord) character(len=*), intent(in) :: sentence, searchWord integer :: i, word_start, word_end, sentence_len, search_len sentence_len = len(sentence); search_len = len(searchWord) word_start = 1; word_end = 1 ...
dolphin
Please explain the reasoning behind the following solution and provide code in Scheme: Given an array of integers `nums` and an integer `limit`, return the size of the longest **non-empty** subarray such that the absolute difference between any two elements of this subarray is less than or equal to `limit`_._ **Exampl...
dolphin
Please explain the following problem in detail and provide code in Rust: Given a binary tree, determine if it is **height-balanced**. **Example 1:** **Input:** root = \[3,9,20,null,null,15,7\] **Output:** true **Example 2:** **Input:** root = \[1,2,2,3,3,null,null,4,4\] **Output:** false **Example 3:** **Input:**...
dolphin
Please focus on the efficiency of this problem and provide code in Mojo: You are given a `m x n` matrix `grid` consisting of **non-negative** integers where `grid[row][col]` represents the **minimum** time required to be able to visit the cell `(row, col)`, which means you can visit the cell `(row, col)` only when the ...
dolphin
Please focus on the functionality of this problem and provide code in Perl: Design the `CombinationIterator` class: * `CombinationIterator(string characters, int combinationLength)` Initializes the object with a string `characters` of **sorted distinct** lowercase English letters and a number `combinationLength` as ...
dolphin
Please explain the reasoning behind the following solution and provide code in TypeScript: Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. According to the [definition of LCA on Wikipedia](https://en.wikipedia.org/wiki/Lowest_common_ancestor): "The lowest common ancestor is d...
dolphin
Please explain the reasoning behind the following solution and provide code in Groovy: You are given two strings `s` and `t` of the same length and an integer `maxCost`. You want to change `s` to `t`. Changing the `ith` character of `s` to `ith` character of `t` costs `|s[i] - t[i]|` (i.e., the absolute difference bet...
dolphin
Please focus on the functionality of this problem and provide code in R: You are given an array of `intervals`, where `intervals[i] = [starti, endi]` and each `starti` is **unique**. The **right interval** for an interval `i` is an interval `j` such that `startj >= endi` and `startj` is **minimized**. Note that `i` ma...
dolphin
translate this code to F#: ```java public int minDays(int[] bloomDay, int m, int k) { int left = Arrays.stream(bloomDay).min().getAsInt(); int right = Arrays.stream(bloomDay).max().getAsInt(); while (left < right) { int mid = left + (right - left) / 2; int bouquets = 0, flowers = 0; ...
dolphin
Please explain the following problem in detail and provide code in ANSI C: Given two integers `left` and `right` that represent the range `[left, right]`, return _the bitwise AND of all numbers in this range, inclusive_. **Example 1:** **Input:** left = 5, right = 7 **Output:** 4 **Example 2:** **Input:** left = 0,...
dolphin
Please write the following solution using Objective-C: 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 **truncate toward zero**...
dolphin
translate this code to TypeScript: ```java public int numberOfLists(String num) { int mod = 1000000007; int n = num.length(); int[][] dp = new int[n + 1][n + 1]; dp[0][0] = 1; for (int i = 0; i < n; ++i) { for (int j = 1; j <= n; ++j) { if (num.charAt(i) == '0') continue; ...
dolphin
Please focus on the functionality of this problem and provide code in Swift: Every **valid email** consists of a **local name** and a **domain name**, separated by the `'@'` sign. Besides lowercase letters, the email may contain one or more `'.'` or `'+'`. * For example, in `"alice@leetcode.com "`, `"alice "` is the...
dolphin
Please explain the following problem in detail and provide code in Mojo: You are given an integer array `banned` and two integers `n` and `maxSum`. You are choosing some number of integers following the below rules: * The chosen integers have to be in the range `[1, n]`. * Each integer can be chosen **at most once...
dolphin
Please write the following solution using Scala: An **n-bit gray code sequence** is a sequence of `2n` integers where: * Every integer is in the **inclusive** range `[0, 2n - 1]`, * The first integer is `0`, * An integer appears **no more than once** in the sequence, * The binary representation of every pair o...
dolphin
Please explain the following problem in detail and provide code in java: You are given an integer array `cookies`, where `cookies[i]` denotes the number of cookies in the `ith` bag. You are also given an integer `k` that denotes the number of children to distribute **all** the bags of cookies to. All the cookies in the...
dolphin
convert this code from Haskell to c++: ```haskell data Node a = Node { val :: a, next :: Maybe (Node a), random :: Maybe (Node a) } deriving Show copyRandomList :: Node a -> Node a copyRandomList head = if head == Nothing then Nothing else let curr = head while curr = do let temp = Node (val cu...
dolphin
Please explain the following problem in detail and provide code in R: You are given an integer array `cards` of length `4`. You have four cards, each containing a number in the range `[1, 9]`. You should arrange the numbers on these cards in a mathematical expression using the operators `['+', '-', '*', '/']` and the p...
dolphin
Please explain the reasoning behind the following solution and provide code in c++: There are `n` houses in a village. We want to supply water for all the houses by building wells and laying pipes. For each house `i`, we can either build a well inside it directly with cost `wells[i - 1]` (note the `-1` due to **0-inde...
dolphin
Please explain the reasoning behind the following solution and provide code in Scheme: A **pangram** is a sentence where every letter of the English alphabet appears at least once. Given a string `sentence` containing only lowercase English letters, return `true` _if_ `sentence` _is a **pangram**, or_ `false` _otherwi...
dolphin
port this code to Go: ```python def is_ugly(n: int) -> bool: if n <= 0: return False for factor in [2, 3, 5]: while n % factor == 0: n //= factor return n == 1 ```
dolphin
convert this code to javascript: ```rust struct Bitset { array: Vec<u32>, length: usize, } impl Bitset { fn new(size: usize) -> Self { let array_length = (size + 31) / 32; let array = vec![0; array_length]; Bitset { array, length: size, } } f...
dolphin
port this code from Go to java: ```go func findPivot(n int) int { total := n * (n + 1) / 2 leftSum := 0 for x := 1; x <= n; x++ { leftSum += x if 2 * leftSum == total { return x } } return -1 } ```
dolphin
Please explain the following problem in detail and provide code in Scheme: You are given a string `s`. We want to partition the string into as many parts as possible so that each letter appears in at most one part. Note that the partition is done so that after concatenating all the parts in order, the resultant string...
dolphin
Please write the following solution using Scheme: You are given an integer array `nums` of length `n` which represents a permutation of all the integers in the range `[0, n - 1]`. The number of **global inversions** is the number of the different pairs `(i, j)` where: * `0 <= i < j < n` * `nums[i] > nums[j]` The...
dolphin
Please write the following solution using ANSI C: There are `n` workers. You are given two integer arrays `quality` and `wage` where `quality[i]` is the quality of the `ith` worker and `wage[i]` is the minimum wage expectation for the `ith` worker. We want to hire exactly `k` workers to form a paid group. To hire a gr...
dolphin
Please focus on the functionality of this problem and provide code in Kotlin: You are given an `m x n` grid `grid` of values `0`, `1`, or `2`, where: * each `0` marks **an empty land** that you can pass by freely, * each `1` marks **a building** that you cannot pass through, and * each `2` marks **an obstacle** ...
dolphin
port this code from python to Ruby: ```python def find_second_greater(nums): n = len(nums) answer = [-1] * n for i in range(n): k = -1 for j in range(i + 1, n): if nums[j] > nums[i]: if k == -1: k = j else: a...
dolphin
Please focus on the algorithm of this problem and provide code in Object Pascal: It is a sweltering summer day, and a boy wants to buy some ice cream bars. At the store, there are `n` ice cream bars. You are given an array `costs` of length `n`, where `costs[i]` is the price of the `ith` ice cream bar in coins. The bo...
dolphin
Please explain the reasoning behind the following solution and provide code in Rust: You are given an integer array `nums`. A number `x` is **lonely** when it appears only **once**, and no **adjacent** numbers (i.e. `x + 1` and `x - 1)` appear in the array. Return _**all** lonely numbers in_ `nums`. You may return the...
dolphin
Please explain the reasoning behind the following solution and provide code in C#: You are given an integer `finalSum`. Split it into a sum of a **maximum** number of **unique** positive even integers. * For example, given `finalSum = 12`, the following splits are **valid** (unique positive even integers summing up ...
dolphin
translate this code to F#: ```ruby def is_safe(cols, row) col = cols.length (0...col).each do |i| return false if cols[i] == row || (i - col).abs == (cols[i] - row).abs end true end def backtrack(n, cols) return 1 if cols.length == n count = 0 (0...n).each do |i| if is_safe...
dolphin
translate this code from java to C#: ```java public class Solution { public String fractionAddition(String expression) { int A = 0, B = 1; int i = 0; while(i < expression.length()) { int sign = expression.charAt(i++) == '+' ? 1 : -1; int num = 0, den = 0; ...
dolphin
Please explain the following problem in detail and provide code in javascript: A decimal number is called **deci-binary** if each of its digits is either `0` or `1` without any leading zeros. For example, `101` and `1100` are **deci-binary**, while `112` and `3001` are not. Given a string `n` that represents a positiv...
dolphin
Please write the following solution using Lisp: Given the `root` of a binary tree and an array of `TreeNode` objects `nodes`, return _the lowest common ancestor (LCA) of **all the nodes** in_ `nodes`. All the nodes will exist in the tree, and all values of the tree's nodes are **unique**. Extending the **[definition o...
dolphin
Please focus on the algorithm of this problem and provide code in PHP: You are given an array of points in the **X-Y** plane `points` where `points[i] = [xi, yi]`. Return _the minimum area of a rectangle formed from these points, with sides parallel to the X and Y axes_. If there is not any such rectangle, return `0`....
dolphin
Please explain the reasoning behind the following solution and provide code in python: Given an array of strings `words`, find the **longest** string in `words` such that **every prefix** of it is also in `words`. * For example, let `words = [ "a ", "app ", "ap "]`. The string `"app "` has prefixes `"ap "` and `"a "...
dolphin
Please explain the following problem in detail and provide code in Julia: **HTML entity parser** is the parser that takes HTML code as input and replace all the entities of the special characters by the characters itself. The special characters and their entities for HTML are: * **Quotation Mark:** the entity is `&...
dolphin
Please explain the reasoning behind the following solution and provide code in Kotlin: Given an integer array `nums`, move all `0`'s to the end of it while maintaining the relative order of the non-zero elements. **Note** that you must do this in-place without making a copy of the array. **Example 1:** **Input:** nu...
dolphin
Please explain the reasoning behind the following solution and provide code in Haskell: 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`, a...
dolphin
convert this code from javascript to Mojo: ```javascript function rectangleArea(rectangles) { const mod = 1e9 + 7; let n = rectangles.length; let X = new Set(), Y = new Set(); for (const rect of rectangles) { X.add(rect[0]); X.add(rect[2]); Y.add(rect[1]); Y.add(rect[3]);...
dolphin
port this code from Object Pascal to Dart: ```pascal type TMinStack = class private FStack: array of Integer; FMinStack: array of Integer; public constructor Create(); procedure Push(val: Integer); procedure Pop(); function Top(): Integer; function GetMin(): Integer; end; constructo...
dolphin
Please focus on the algorithm of this problem and provide code in Dart: 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 write the following solution using Go: 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 lowercase English letters (`'a'` through `...
dolphin
translate this code to Haskell: ```perl package MyCircularQueue; sub new { my ($class, $k) = @_; my $self = { size => $k, data => [(0) x $k], front => -1, rear => -1, }; bless $self, $class; return $self; } sub enQueue { my ($self, $value) = @_; return 0 if ...
dolphin
Please focus on the algorithm of this problem and provide code in PHP: You are playing a variation of the game Zuma. In this variation of Zuma, there is a **single row** of colored balls on a board, where each ball can be colored red `'R'`, yellow `'Y'`, blue `'B'`, green `'G'`, or white `'W'`. You also have several c...
dolphin
Please focus on the efficiency of this problem and provide code in PHP: You are given an `m x n` matrix `mat` that has its rows sorted in non-decreasing order and an integer `k`. You are allowed to choose **exactly one element** from each row to form an array. Return _the_ `kth` _smallest array sum among all possible...
dolphin
port this code from python to PHP: ```python def can_sort_using_swap(nums): for i in range(1, len(nums)): if nums[i] < nums[i - 1]: nums[i], nums[i - 1] = nums[i - 1], nums[i] if sorted(nums) == nums: return True nums[i], nums[i - 1] = nums[i - 1], nums[i]...
dolphin
Please explain the following problem in detail and provide code in Scala: Given two strings: `s1` and `s2` with the same size, check if some permutation of string `s1` can break some permutation of string `s2` or vice-versa. In other words `s2` can break `s1` or vice-versa. A string `x` can break string `y` (both of s...
dolphin
Please write the following solution using python: Given an array of **distinct** integers `arr`, find all pairs of elements with the minimum absolute difference of any two elements. Return a list of pairs in ascending order(with respect to pairs), each pair `[a, b]` follows * `a, b` are from `arr` * `a < b` * `...
dolphin
translate this code to Groovy: ```rust fn remove_duplicate_letters(s: String) -> String { let mut count = vec![0; 256]; let mut visited = vec![false; 256]; let mut st = Vec::new(); for ch in s.chars() { count[ch as usize] += 1; } for ch in s.chars() { count[ch as usize] -= 1; ...
dolphin
Please explain the reasoning behind the following solution and provide code in Dart: Given a string `s` and an integer `k`, rearrange `s` such that the same characters are **at least** distance `k` from each other. If it is not possible to rearrange the string, return an empty string `" "`. **Example 1:** **Input:** ...
dolphin
Please write the following solution using F#: You are given a **0-indexed** array of positive integers `w` where `w[i]` describes the **weight** of the `ith` index. You need to implement the function `pickIndex()`, which **randomly** picks an index in the range `[0, w.length - 1]` (**inclusive**) and returns it. The *...
dolphin
port this code from Kotlin to Scala: ```kotlin fun maxStudents(seats: Array<Array<Char>>): Int { var count = 0 val m = seats.size val n = seats[0].size for (i in 0 until m) { for (j in 0 until n) { if (seats[i][j] == '.') { if ((j == 0 || seats[i][j-1] == '#') && (j ...
dolphin
Please write the following solution using PHP: An **ugly number** is a positive integer whose prime factors are limited to `2`, `3`, and `5`. Given an integer `n`, return _the_ `nth` _**ugly number**_. **Example 1:** **Input:** n = 10 **Output:** 12 **Explanation:** \[1, 2, 3, 4, 5, 6, 8, 9, 10, 12\] is the sequence...
dolphin
Please explain the following problem in detail and provide code in Groovy: The **distance of a pair** of integers `a` and `b` is defined as the absolute difference between `a` and `b`. Given an integer array `nums` and an integer `k`, return _the_ `kth` _smallest **distance among all the pairs**_ `nums[i]` _and_ `nums...
dolphin
Please focus on the functionality of this problem and provide code in ANSI C: A **subarray** of a **0-indexed** integer array is a contiguous **non-empty** sequence of elements within an array. The **alternating subarray sum** of a subarray that ranges from index `i` to `j` (**inclusive**, `0 <= i <= j < nums.length`)...
dolphin
port this code to Go: ```julia using DataStructures function nearest_leaf_node(root, k) distances = Dict() dfs(root, distances) visited = Set() queue = Queue([node for node in keys(distances) if node.val == k]) while !isempty(queue) node = dequeue!(queue) if isleaf(node) ...
dolphin
Please explain the reasoning behind the following solution and provide code in Kotlin: You are given a **0-indexed** integer array `order` of length `n`, a **permutation** of integers from `1` to `n` representing the **order** of insertion into a **binary search tree**. A binary search tree is defined as follows: * ...
dolphin
Please explain the following problem in detail and provide code in javascript: There is a long table with a line of plates and candles arranged on top of it. You are given a **0-indexed** string `s` consisting of characters `'*'` and `'|'` only, where a `'*'` represents a **plate** and a `'|'` represents a **candle**. ...
dolphin
Please explain the reasoning behind the following solution and provide code in Scala: There is an integer array `perm` that is a permutation of the first `n` positive integers, where `n` is always **odd**. It was encoded into another integer array `encoded` of length `n - 1`, such that `encoded[i] = perm[i] XOR perm[i...
dolphin
Please write the following solution using Lisp: 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 multiple ...
dolphin
Please explain the reasoning behind the following solution and provide code in ANSI C: There exists an undirected and unrooted tree with `n` nodes indexed from `0` to `n - 1`. You are given an integer `n` and a 2D integer array edges of length `n - 1`, where `edges[i] = [ai, bi]` indicates that there is an edge between...
dolphin
convert this code from Visual Basic .NET to Object Pascal: ```vb.net Function MissingRolls(rolls As List(Of Integer), mean As Integer, n As Integer) As List(Of Integer) Dim rollSum As Integer = rolls.Sum() Dim totalSum As Integer = mean * (n + rolls.Count()) Dim missingSum As Integer = totalSum - rollSum ...
dolphin
Please focus on the algorithm of this problem and provide code in Go: A city's **skyline** is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Given the locations and heights of all the buildings, return _the **skyline** formed by these buildings collectively_. ...
dolphin
Please explain the reasoning behind the following solution and provide code in Erlang: Given `2n` balls of `k` distinct colors. You will be given an integer array `balls` of size `k` where `balls[i]` is the number of balls of color `i`. All the balls will be **shuffled uniformly at random**, then we will distribute th...
dolphin
Please explain the reasoning behind the following solution and provide code in c++: Given a string `s` of lower and upper case English letters. A good string is a string which doesn't have **two adjacent characters** `s[i]` and `s[i + 1]` where: * `0 <= i <= s.length - 2` * `s[i]` is a lower-case letter and `s[i ...
dolphin
Please explain the reasoning behind the following solution and provide code in Ruby: There is an undirected tree with `n` nodes labeled from `0` to `n - 1`. You are given the integer `n` and a 2D integer array `edges` of length `n - 1`, where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and ...
dolphin
Please explain the following problem in detail and provide code in Elixir: A **Fibonacci** tree is a binary tree created using the order function `order(n)`: * `order(0)` is the empty tree. * `order(1)` is a binary tree with only **one node**. * `order(n)` is a binary tree that consists of a root node with the l...
dolphin
convert this code from python to Ruby: ```python def findPeakGrid(mat: List[List[int]]) -> List[int]: m, n = len(mat), len(mat[0]) l, r = 0, n - 1 while l < r: mid = (l + r) // 2 max_row = 0 for i in range(1, m): if mat[i][mid] > mat[max_row][mid]: max_r...
dolphin
Please explain the following problem in detail and provide code in R: You are given an integer array `nums` sorted in **non-decreasing** order. Build and return _an integer array_ `result` _with the same length as_ `nums` _such that_ `result[i]` _is equal to the **summation of absolute differences** between_ `nums[i]`...
dolphin
Please explain the following problem in detail and provide code in Objective-C: Given a **non-negative** integer `num`, return `true` _if_ `num` _can be expressed as the sum of any **non-negative** integer and its reverse, or_ `false` _otherwise._ **Example 1:** **Input:** num = 443 **Output:** true **Explanation:** ...
dolphin
translate this code from Mojo to Go: ```mojo sub maxFruits(fruits, startPos, k) { var n = length(fruits); var left = [0] * (n + 1); var right = [0] * (n + 1); var j = 0; for i in range(n) { while j < n and fruits[j][0] - fruits[i][0] <= k { right[i + 1] += fruits[j][1]; ...
dolphin
Please write the following solution using Haskell: A **confusing number** is a number that when rotated `180` degrees becomes a different number with **each digit valid**. We can rotate digits of a number by `180` degrees to form new digits. * When `0`, `1`, `6`, `8`, and `9` are rotated `180` degrees, they become ...
dolphin
port this code from Groovy to Go: ``` def validArrangement(pairs) { def graph = [:].withDefault { [] } pairs.each { start, end -> graph[start] << end } def result = [] def current = pairs[0][0] while (graph) { def pair = [current, graph[current].pop()] if (graph[current...
dolphin
Please explain the reasoning behind the following solution and provide code in Perl: Given two integer arrays `pushed` and `popped` each with distinct values, return `true` _if this could have been the result of a sequence of push and pop operations on an initially empty stack, or_ `false` _otherwise._ **Example 1:** ...
dolphin
Please explain the following problem in detail and provide code in F#: Given a 2D `grid` of size `m x n` and an integer `k`. You need to shift the `grid` `k` times. In one shift operation: * Element at `grid[i][j]` moves to `grid[i][j + 1]`. * Element at `grid[i][n - 1]` moves to `grid[i + 1][0]`. * Element at ...
dolphin
Please write the following solution using TypeScript: One way to serialize a binary tree is to use **preorder traversal**. When we encounter a non-null node, we record the node's value. If it is a null node, we record using a sentinel value such as `'#'`. For example, the above binary tree can be serialized to the str...
dolphin
translate this code to Fortran: ```csharp public bool Search(int[] nums, int target) { int left = 0; int right = nums.Length - 1; while (left <= right) { int mid = left + (right - left) / 2; if (nums[mid] == target) { return true; } if (nums[mid] == nums[left]) { ...
dolphin
translate this code from python to Dart: ```python def findLexSmallestString(s: str, a: int, b: int) -> str: def add_odd(s: str, a: int) -> str: return ''.join([str((int(ch) + a) % 10) if idx % 2 else ch for idx, ch in enumerate(s)]) def rotate(s: str, k: int) -> str: k %= len(s) return...
dolphin
Please focus on the functionality of this problem and provide code in python: There is an `n x n` grid, with the top-left cell at `(0, 0)` and the bottom-right cell at `(n - 1, n - 1)`. You are given the integer `n` and an integer array `startPos` where `startPos = [startrow, startcol]` indicates that a robot is initia...
dolphin
port this code to TypeScript: ```erlang min_operations(Nums, Target) -> N = length(Nums), SumNums = lists:sum(Nums), SumTarget = lists:sum(Target), Diff = floor((SumTarget - SumNums) / 2), Cnt = lists:foldl(fun (I, Acc) -> if lists:nth(I, Nums) > lists:nth(I, Target) -> Acc + flo...
dolphin
Please write the following solution using python: Given an integer array `nums`, move all `0`'s to the end of it while maintaining the relative order of the non-zero elements. **Note** that you must do this in-place without making a copy of the array. **Example 1:** **Input:** nums = \[0,1,0,3,12\] **Output:** \[1,3...
dolphin
Please explain the reasoning behind the following solution and provide code in C#: You are given an array `trees` where `trees[i] = [xi, yi]` represents the location of a tree in the garden. Fence the entire garden using the minimum length of rope, as it is expensive. The garden is well-fenced only if **all the trees ...
dolphin
translate this code to java: ```groovy def total_ways_to_split_ranges(ranges) { final MOD = 10**9 + 7 ranges.sort { it[1] } def overlapping = 0, non_overlapping = 1, prev_end = -1 ranges.each { start, end -> if (start <= prev_end) { overlapping++ } else { non_ove...
dolphin
Please explain the reasoning behind the following solution and provide code in TypeScript: A school is trying to take an annual photo of all the students. The students are asked to stand in a single file line in **non-decreasing order** by height. Let this ordering be represented by the integer array `expected` where `...
dolphin
Please focus on the algorithm of this problem and provide code in Lua: You would like to make dessert and are preparing to buy the ingredients. You have `n` ice cream base flavors and `m` types of toppings to choose from. You must follow these rules when making your dessert: * There must be **exactly one** ice cream...
dolphin
Please explain the following problem in detail and provide code in Ruby: Given a list of `words`, list of single `letters` (might be repeating) and `score` of every character. Return the maximum score of **any** valid set of words formed by using the given letters (`words[i]` cannot be used two or more times). It is ...
dolphin
Please write the following solution using PHP: Given two strings `s` and `t`, transform string `s` into string `t` using the following operation any number of times: * Choose a **non-empty** substring in `s` and sort it in place so the characters are in **ascending order**. * For example, applying the operatio...
dolphin
Please focus on the functionality of this problem and provide code in Julia: There are `m` boys and `n` girls in a class attending an upcoming party. You are given an `m x n` integer matrix `grid`, where `grid[i][j]` equals `0` or `1`. If `grid[i][j] == 1`, then that means the `ith` boy can invite the `jth` girl to th...
dolphin
Please explain the following problem in detail and provide code in Scala: 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 an array of `events` where `events[i] = [startDayi, endDayi]`. Every event `i` starts at `startDayi` and ends at `endDayi`. You can attend an event `i` at any day `d` where `startTimei <= d <= endTimei`. You can only att...
dolphin