instruction_seed
stringlengths
29
40.5k
source
stringclasses
6 values
Please explain the reasoning behind the following solution and provide code in F#: You are given two **0-indexed binary** strings `s` and `target` of the same length `n`. You can do the following operation on `s` **any** number of times: * Choose two **different** indices `i` and `j` where `0 <= i, j < n`. * Simul...
dolphin
Please focus on the algorithm of this problem and provide code in javascript: The **median** is the middle value in an ordered integer list. If the size of the list is even, there is no middle value, and the median is the mean of the two middle values. * For example, for `arr = [2,3,4]`, the median is `3`. * For e...
dolphin
port this code to Ruby: ```dart List<String> ambiguousCoordinates(String s) { List<String> generateNumber(String s) { if (s.isEmpty || (s.length > 1 && s[0] == '0' && s[s.length - 1] == '0')) { return []; } if (s.length > 1 && s[0] == '0') { return ["0.${s.substring(1)}"]; } List<Strin...
dolphin
Please explain the reasoning behind the following solution and provide code in ANSI C: Given three integer arrays `nums1`, `nums2`, and `nums3`, return _a **distinct** array containing all the values that are present in **at least two** out of the three arrays. You may return the values in **any** order_. **Example 1:...
dolphin
Please explain the following problem in detail and provide code in PHP: Bob is standing at cell `(0, 0)`, and he wants to reach `destination`: `(row, column)`. He can only travel **right** and **down**. You are going to help Bob by providing **instructions** for him to reach `destination`. The **instructions** are rep...
dolphin
Please explain the reasoning behind the following solution and provide code in Visual Basic .NET: You are given a **sorted unique** integer array `nums`. A **range** `[a,b]` is the set of all integers from `a` to `b` (inclusive). Return _the **smallest sorted** list of ranges that **cover all the numbers in the array...
dolphin
convert this code to python: ```ruby def min_start_value(nums) min_sum = 0 curr_sum = 0 nums.each do |num| curr_sum += num min_sum = [min_sum, curr_sum].min end return 1 - min_sum end ```
dolphin
Please explain the reasoning behind the following solution and provide code in ANSI C: Given an encoded string, return its decoded string. The encoding rule is: `k[encoded_string]`, where the `encoded_string` inside the square brackets is being repeated exactly `k` times. Note that `k` is guaranteed to be a positive i...
dolphin
translate this code to Mojo: ```lisp (defun find-digits-in-ascending-order (s) (let ((count (make-list 10 :initial-element 0))) (loop for c across s do (case c (#\z (incf (nth 0 count))) (#\w (incf (nth 2 count))) (#\u (incf (nth 4 count))) (#\...
dolphin
Please write the following solution using Ruby: **No-Zero integer** is a positive integer that **does not contain any `0`** in its decimal representation. Given an integer `n`, return _a list of two integers_ `[a, b]` _where_: * `a` and `b` are **No-Zero integers**. * `a + b = n` The test cases are generated so ...
dolphin
convert this code from R to Erlang: ```R maxDepth <- function(node) { if (is.null(node)) { return(0) } else { return(max(maxDepth(node$left), maxDepth(node$right)) + 1) } } subtreeWithAllDeepest <- function(root) { if (is.null(root)) { return(NULL) } leftDepth <- maxDepth(root$left) rightD...
dolphin
port this code to python: ```ruby def min_addition(s, t) s_len = s.length t_len = t.length i, j = 0, 0 while i < s_len && j < t_len if s[i] == t[j] j += 1 end i += 1 end return t_len - j end ```
dolphin
port this code to Object Pascal: ```scheme (define (max-length-between-equal-characters s) (define max-length -1) (define char-index-map (make-hash)) (define (update-max-length char index) (set! max-length (max max-length (- index (hash-ref char-index-map char) 1)))) (for-each (lambda (char index) ...
dolphin
port this code from java to javascript: ```java import java.util.List; import java.util.ArrayList; public List<Integer> findAnagrams(String s, String p) { List<Integer> result = new ArrayList<>(); if (s.length() < p.length()) return result; int[] s_count = new int[26]; int[] p_count = new int[26]; ...
dolphin
Please explain the reasoning behind the following solution and provide code in Object Pascal: You are asked to cut off all the trees in a forest for a golf event. The forest is represented as an `m x n` matrix. In this matrix: * `0` means the cell cannot be walked through. * `1` represents an empty cell that can b...
dolphin
translate this code to python: ```kotlin fun shortestUnrollableSequence(rolls: IntArray, k: Int): Int { val count = IntArray(k + 1) for (roll in rolls) { count[roll]++ } var len = 1 while (true) { var maxSubsequences = 1 for (i in 1..k) { maxSubsequences *= count...
dolphin
Please focus on the functionality of this problem and provide code in java: You are given an array `nums` consisting of positive integers. You are also given an integer array `queries` of size `m`. For the `ith` query, you want to make all of the elements of `nums` equal to `queries[i]`. You can perform the following ...
dolphin
convert this code from Rust to Object Pascal: ```rust use std::collections::HashMap; fn sort_frequency(nums: &[i32]) -> Vec<i32> { let mut frequency_map: HashMap<i32, i32> = HashMap::new(); for &num in nums { *frequency_map.entry(num).or_insert(0) += 1; } let mut bucket: Vec<Vec<i32>> = ve...
dolphin
Please explain the reasoning behind the following solution and provide code in Elixir: You are given an array of strings `nums` and an integer `k`. Each string in `nums` represents an integer without leading zeros. Return _the string that represents the_ `kth` _**largest integer** in_ `nums`. **Note**: Duplicate numb...
dolphin
Please focus on the algorithm 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 least common multiple of the subarray's elements is_ `k`. A **subarray** is a contiguous non-empty sequence of elements within an array....
dolphin
Please explain the following problem in detail and provide code in Ruby: Given the `root` of a binary tree, return _the sum of values of nodes with an **even-valued grandparent**_. If there are no nodes with an **even-valued grandparent**, return `0`. A **grandparent** of a node is the parent of its parent if it exist...
dolphin
Please explain the following problem in detail and provide code in Scala: In a gold mine `grid` of size `m x n`, each cell in this mine has an integer representing the amount of gold in that cell, `0` if it is empty. Return the maximum amount of gold you can collect under the conditions: * Every time you are locate...
dolphin
Please write the following solution using Scala: Design a max stack data structure that supports the stack operations and supports finding the stack's maximum element. Implement the `MaxStack` class: * `MaxStack()` Initializes the stack object. * `void push(int x)` Pushes element `x` onto the stack. * `int pop(...
dolphin
Please explain the following problem in detail and provide code in C#: 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 represen...
dolphin
Please explain the following problem in detail and provide code in Haskell: Given an array of intervals `intervals` where `intervals[i] = [starti, endi]`, return _the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping_. **Example 1:** **Input:** intervals = \[\[1,2\],\[2,...
dolphin
translate this code to Objective-C: ```lua function minimum_mountain_removals(nums) local n = #nums local left, right = {}, {} for i = 1, n do left[i] = 0 right[i] = 0 end for i = 1, n do left[i] = #left - table.concat(left, ",", 1, i - 1)):find(nums[i]..",", 1, true) or 0 ...
dolphin
port this code to Rust: ```php class TreeNode { public $val = null; public $left = null; public $right = null; function __construct($val = 0, $left = null, $right = null) { $this->val = $val; $this->left = $left; $this->right = $right; } } function findDuplicateSubtrees($roo...
dolphin
Please focus on the efficiency of this problem and provide code in Groovy: You are given a binary string `binary` consisting of only `0`'s or `1`'s. You can apply each of the following operations any number of times: * Operation 1: If the number contains the substring `"00 "`, you can replace it with `"10 "`. * ...
dolphin
port this code to Haskell: ```kotlin import java.util.* fun findMinHeightTrees(n: Int, edges: Array<IntArray>): List<Int> { if (n == 1) return listOf(0) val adjList = Array(n) { mutableSetOf<Int>() } for (edge in edges) { adjList[edge[0]].add(edge[1]) adjList[edge[1]].add(edge[0]) } ...
dolphin
translate this code to C#: ```java int minElements(int[] nums, int limit, int goal) { long sum = 0; for (int num : nums) sum += num; long diff = Math.abs(goal - sum); return (int)((diff + limit - 1) / limit); } ```
dolphin
Please focus on the algorithm of this problem and provide code in javascript: Given an integer array `nums`, find the **maximum** possible **bitwise OR** of a subset of `nums` and return _the **number of different non-empty subsets** with the maximum bitwise OR_. An array `a` is a **subset** of an array `b` if `a` can...
dolphin
convert this code from Visual Basic .NET to Perl: ```vb Public Class TreeNode Public Property val As Integer Public Property left As TreeNode Public Property right As TreeNode Public Sub New(ByVal val As Integer, Optional ByVal left As TreeNode = Nothing, Optional ByVal right As TreeNode = Nothing) ...
dolphin
translate this code to Ruby: ```javascript function findGCD(nums) { let min_val = Math.min(...nums); let max_val = Math.max(...nums); while(max_val % min_val !== 0) { [min_val, max_val] = [max_val % min_val, min_val]; } return min_val; } ```
dolphin
Please explain the following problem in detail and provide code in Lisp: You are given a string `text`. You should split it to k substrings `(subtext1, subtext2, ..., subtextk)` such that: * `subtexti` is a **non-empty** string. * The concatenation of all the substrings is equal to `text` (i.e., `subtext1 + subtex...
dolphin
Please explain the reasoning behind the following solution and provide code in Dart: Given two strings `a` and `b`, return _the minimum number of times you should repeat string_ `a` _so that string_ `b` _is a substring of it_. If it is impossible for `b`​​​​​​ to be a substring of `a` after repeating it, return `-1`. ...
dolphin
port this code from C# to Elixir: ```csharp public class SeatManager { private bool[] seats; public SeatManager(int n) { seats = new bool[n]; } public int Reserve() { for (int i = 0; i < seats.Length; i++) { if (!seats[i]) { seats[i] = true; re...
dolphin
translate this code from Perl to Julia: ```perl use strict; use warnings; package NaryTreeNode { sub new { my ($class, $val, $children) = @_; my $self = { val => $val, children => $children || [], }; return bless $self, $class; } } package BinaryTreeNode...
dolphin
Please focus on the functionality of this problem and provide code in Dart: Given a string containing digits from `2-9` inclusive, return all possible letter combinations that the number could represent. Return the answer in **any order**. A mapping of digits to letters (just like on the telephone buttons) is given be...
dolphin
Please explain the reasoning behind the following solution and provide code in Rust: You are given two strings `s` and `p` where `p` is a **subsequence** of `s`. You are also given a **distinct 0-indexed** integer array `removable` containing a subset of indices of `s` (`s` is also **0-indexed**). You want to choose a...
dolphin
Please explain the following problem in detail and provide code in F#: Given a string `s` and an integer `k`, reverse the first `k` characters for every `2k` characters counting from the start of the string. If there are fewer than `k` characters left, reverse all of them. If there are less than `2k` but greater than ...
dolphin
Please explain the reasoning behind the following solution and provide code in R: The **array-form** of an integer `num` is an array representing its digits in left to right order. * For example, for `num = 1321`, the array form is `[1,3,2,1]`. Given `num`, the **array-form** of an integer, and an integer `k`, retu...
dolphin
Please write the following solution using ANSI C: A **valid cut** in a circle can be: * A cut that is represented by a straight line that touches two points on the edge of the circle and passes through its center, or * A cut that is represented by a straight line that touches one point on the edge of the circle an...
dolphin
Please write the following solution using Ruby: Given an integer `n`, break it into the sum of `k` **positive integers**, where `k >= 2`, and maximize the product of those integers. Return _the maximum product you can get_. **Example 1:** **Input:** n = 2 **Output:** 1 **Explanation:** 2 = 1 + 1, 1 \* 1 = 1. **Exam...
dolphin
Please explain the reasoning behind the following solution and provide code in ANSI C: Design an iterator that supports the `peek` operation on an existing iterator in addition to the `hasNext` and the `next` operations. Implement the `PeekingIterator` class: * `PeekingIterator(Iterator nums)` Initializes the objec...
dolphin
Please explain the reasoning behind the following solution and provide code in Lisp: Given an array of **distinct** integers `nums` and a target integer `target`, return _the number of possible combinations that add up to_ `target`. The test cases are generated so that the answer can fit in a **32-bit** integer. **Ex...
dolphin
Please focus on the efficiency of this problem and provide code in ANSI C: A die simulator generates a random number from `1` to `6` for each roll. You introduced a constraint to the generator such that it cannot roll the number `i` more than `rollMax[i]` (**1-indexed**) consecutive times. Given an array of integers `...
dolphin
Please focus on the functionality of this problem and provide code in Groovy: Alice and Bob take turns playing a game, with Alice starting first. Initially, there is a number `n` on the chalkboard. On each player's turn, that player makes a move consisting of: * Choosing any `x` with `0 < x < n` and `n % x == 0`. *...
dolphin
Please write the following solution using ANSI C: Given a circular integer array `nums` (i.e., the next element of `nums[nums.length - 1]` is `nums[0]`), return _the **next greater number** for every element in_ `nums`. The **next greater number** of a number `x` is the first greater number to its traversing-order nex...
dolphin
Please explain the following problem in detail and provide code in Julia: You are given an undirected graph. You are given an integer `n` which is the number of nodes in the graph and an array `edges`, where each `edges[i] = [ui, vi]` indicates that there is an undirected edge between `ui` and `vi`. A **connected trio...
dolphin
Please write the following solution using python: Given an integer array nums, return all the triplets `[nums[i], nums[j], nums[k]]` such that `i != j`, `i != k`, and `j != k`, and `nums[i] + nums[j] + nums[k] == 0`. Notice that the solution set must not contain duplicate triplets. **Example 1:** **Input:** nums = \...
dolphin
Please explain the reasoning behind the following solution and provide code in Scala: There are `n` persons numbered from `0` to `n - 1` and a door. Each person can enter or exit through the door once, taking one second. You are given a **non-decreasing** integer array `arrival` of size `n`, where `arrival[i]` is the ...
dolphin
Please write the following solution using Rust: There are `n` different online courses numbered from `1` to `n`. You are given an array `courses` where `courses[i] = [durationi, lastDayi]` indicate that the `ith` course should be taken **continuously** for `durationi` days and must be finished before or on `lastDayi`. ...
dolphin
Please write the following solution using Visual Basic .NET: Given an `m x n` matrix `grid` where each cell is either a wall `'W'`, an enemy `'E'` or empty `'0'`, return _the maximum enemies you can kill using one bomb_. You can only place the bomb in an empty cell. The bomb kills all the enemies in the same row and c...
dolphin
Please write the following solution using Swift: Given an integer `n`, return _the number of positive integers in the range_ `[1, n]` _that have **at least one** repeated digit_. **Example 1:** **Input:** n = 20 **Output:** 1 **Explanation:** The only positive number (<= 20) with at least 1 repeated digit is 11. **E...
dolphin
Please write the following solution using F#: Given an integer array `nums` and an integer `k`, return _the number of **good** subarrays of_ `nums`. A subarray `arr` is **good** if it there are **at least** `k` pairs of indices `(i, j)` such that `i < j` and `arr[i] == arr[j]`. A **subarray** is a contiguous **non-em...
dolphin
translate this code to Perl: ```php function countSubArrays($arr, $k, $threshold) { $n = count($arr); $count = 0; $prefix_sum = array_fill(0, $n+1, 0); for ($i = 1; $i <= $n; $i++) { $prefix_sum[$i] = $prefix_sum[$i-1] + $arr[$i-1]; } for ($i = $k; $i <= $n; $i++) { $su...
dolphin
translate this code to PHP: ```typescript function longestIncreasingPath(matrix: number[][]): number { const dx = [0, 0, 1, -1]; const dy = [1, -1, 0, 0]; function dfs(memo: number[][], i: number, j: number): number { if (memo[i][j] !== 0) { return memo[i][j]; } let maxLen = 0; for (let k ...
dolphin
Please write the following solution using Lisp: A social media company is trying to monitor activity on their site by analyzing the number of tweets that occur in select periods of time. These periods can be partitioned into smaller **time chunks** based on a certain frequency (every **minute**, **hour**, or **day**). ...
dolphin
Please focus on the efficiency of this problem and provide code in Lisp: There is a special square room with mirrors on each of the four walls. Except for the southwest corner, there are receptors on each of the remaining corners, numbered `0`, `1`, and `2`. The square room has walls of length `p` and a laser ray from...
dolphin
port this code to Elixir: ```dart int minimumMaximum(int n, List<int> quantities) { int sumProducts = quantities.reduce((a, b) => a + b); int x = (sumProducts + n - 1) ~/ n; int remainingStores = n; for (int q in quantities) { remainingStores -= (q + x - 1) ~/ x; if (remainingStores < 0) { x = (su...
dolphin
convert this code to java: ```elixir defmodule Solution do def three_non_consecutive_buildings(s) do n = String.length(s) count = 0 for i <- 0..(n-3) do if s[i] != s[i+1] and s[i+1] != s[i+2] and s[i] != s[i+2] do count += 1 end end count end end ```
dolphin
Please write the following solution using Haskell: You are given a nested list of integers `nestedList`. Each element is either an integer or a list whose elements may also be integers or other lists. The **depth** of an integer is the number of lists that it is inside of. For example, the nested list `[1,[2,2],[[3],2...
dolphin
Please explain the reasoning behind the following solution and provide code in c++: Given a positive integer `n`, you can apply one of the following operations: 1. If `n` is even, replace `n` with `n / 2`. 2. If `n` is odd, replace `n` with either `n + 1` or `n - 1`. Return _the minimum number of operations needed ...
dolphin
translate this code to Julia: ``` min_operations <- function(root, result) { if (is.null(root)) { return(0) } if (root$val <= 1) { return(ifelse(root$val == result, 0, 1)) } else { left_operations <- min_operations(root$left, ifelse(root$val == 4, result xor 1, result)) right_operations <- min_o...
dolphin
Please focus on the algorithm of this problem and provide code in F#: You are given an encoded string `s`. To decode the string to a tape, the encoded string is read one character at a time and the following steps are taken: * If the character read is a letter, that letter is written onto the tape. * If the charac...
dolphin
translate this code from Go to Clojure: ```go package main import ( "fmt" "sort" ) func gcd(a, b int) int { if b == 0 { return a } return gcd(b, a%b) } func dfs(ans *[]int, nums []int, edges [][]int, u, p int, seen map[int]bool, gcds map[int]int) { for _, v := range edges[u] { ...
dolphin
Please explain the following problem in detail and provide code in Kotlin: Suppose you are at a party with `n` people labeled from `0` to `n - 1` and among them, there may exist one celebrity. The definition of a celebrity is that all the other `n - 1` people know the celebrity, but the celebrity does not know any of t...
dolphin
port this code from Dart to Fortran: ```dart bool isPowerOfFour(int n) { if (n <= 0) { return false; } while (n % 4 == 0) { n ~/= 4; } return n == 1; } ```
dolphin
Please write the following solution using Julia: You are given a list of `preferences` for `n` friends, where `n` is always **even**. For each person `i`, `preferences[i]` contains a list of friends **sorted** in the **order of preference**. In other words, a friend earlier in the list is more preferred than a friend ...
dolphin
port this code to javascript: ```vb Function CountHomogenous(s As String) As Integer Const MOD As Integer = 1000000007 Dim count As Integer = 1 Dim total As Integer = 0 For i As Integer = 1 To s.Length - 1 If s(i) = s(i - 1) Then count += 1 Else count = 1 ...
dolphin
Please explain the reasoning behind the following solution and provide code in Swift: Given an integer `rowIndex`, return the `rowIndexth` (**0-indexed**) row of the **Pascal's triangle**. In **Pascal's triangle**, each number is the sum of the two numbers directly above it as shown: **Example 1:** **Input:** rowInd...
dolphin
Please explain the reasoning behind the following solution and provide code in Perl: Given an integer array `nums` and two integers `k` and `p`, return _the number of **distinct subarrays** which have **at most**_ `k` _elements divisible by_ `p`. Two arrays `nums1` and `nums2` are said to be **distinct** if: * They...
dolphin
Please focus on the algorithm of this problem and provide code in Object Pascal: The **appeal** of a string is the number of **distinct** characters found in the string. * For example, the appeal of `"abbca "` is `3` because it has `3` distinct characters: `'a'`, `'b'`, and `'c'`. Given a string `s`, return _the **...
dolphin
Please focus on the efficiency of this problem and provide code in ANSI C: There is a strange printer with the following two special properties: * The printer can only print a sequence of **the same character** each time. * At each turn, the printer can print new characters starting from and ending at any place an...
dolphin
Please explain the reasoning behind the following solution and provide code in R: There are `n` cities numbered from `0` to `n - 1` and `n - 1` roads such that there is only one way to travel between two different cities (this network form a tree). Last year, The ministry of transport decided to orient the roads in one...
dolphin
Please write the following solution using F#: You are given an integer `n`. You roll a fair 6-sided dice `n` times. Determine the total number of **distinct** sequences of rolls possible such that the following conditions are satisfied: 1. The **greatest common divisor** of any **adjacent** values in the sequence is ...
dolphin
Please write the following solution using Dart: You are given an integer `n`. A **0-indexed** integer array `nums` of length `n + 1` is generated in the following way: * `nums[0] = 0` * `nums[1] = 1` * `nums[2 * i] = nums[i]` when `2 <= 2 * i <= n` * `nums[2 * i + 1] = nums[i] + nums[i + 1]` when `2 <= 2 * i +...
dolphin
Please explain the following problem in detail and provide code in C#: Given a binary array `nums`, you should delete one element from it. Return _the size of the longest non-empty subarray containing only_ `1`_'s in the resulting array_. Return `0` if there is no such subarray. **Example 1:** **Input:** nums = \[1,...
dolphin
convert this code to Visual Basic .NET: ```objective-c -(NSInteger)matchingCards:(NSArray<NSNumber *> *)cards { NSMutableDictionary<NSNumber *, NSNumber *> *lastOccurrence = [NSMutableDictionary dictionary]; NSInteger n = cards.count; NSInteger minConsecutive = INT_MAX; for (NSInteger i = 0; i < n; i++)...
dolphin
Please focus on the algorithm of this problem and provide code in Haskell: This is an **interactive problem**. There is a robot in a hidden grid, and you are trying to get it from its starting cell to the target cell in this grid. The grid is of size `m x n`, and each cell in the grid is either empty or blocked. It is...
dolphin
Please explain the following problem in detail and provide code in Elixir: You have some coins. The `i`\-th coin has a probability `prob[i]` of facing heads when tossed. Return the probability that the number of coins facing heads equals `target` if you toss every coin exactly once. **Example 1:** **Input:** prob = ...
dolphin
Please explain the following problem in detail and provide code in python: Given a string `s`, return _the length of the longest_ _substring_ _that contains at most **two distinct characters**_. **Example 1:** **Input:** s = "eceba " **Output:** 3 **Explanation:** The substring is "ece " which its length is 3. **E...
dolphin
Please write the following solution using Swift: 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,4\],\[2,3,3,2,3,1\]\] **Output:** 4 ...
dolphin
Please explain the following problem in detail and provide code in TypeScript: A phrase is a **palindrome** if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers. Given ...
dolphin
Please write the following solution using Objective-C: Given an integer array **sorted** in non-decreasing order, there is exactly one integer in the array that occurs more than 25% of the time, return that integer. **Example 1:** **Input:** arr = \[1,2,2,6,6,6,6,7,10\] **Output:** 6 **Example 2:** **Input:** arr =...
dolphin
Please write the following solution using Go: You are given a string `s`. An **awesome** substring is a non-empty substring of `s` such that we can make any number of swaps in order to make it a palindrome. Return _the length of the maximum length **awesome substring** of_ `s`. **Example 1:** **Input:** s = "324241...
dolphin
Please explain the following problem in detail and provide code in Object Pascal: You are given an integer `num`. You can swap two digits at most once to get the maximum valued number. Return _the maximum valued number you can get_. **Example 1:** **Input:** num = 2736 **Output:** 7236 **Explanation:** Swap the numb...
dolphin
Please explain the reasoning behind the following solution and provide code in Lua: A sequence is **special** if it consists of a **positive** number of `0`s, followed by a **positive** number of `1`s, then a **positive** number of `2`s. * For example, `[0,1,2]` and `[0,0,1,1,1,2]` are special. * In contrast, `[2,...
dolphin
Please focus on the algorithm of this problem and provide code in Perl: You are given an array of `words` where each word consists of lowercase English letters. `wordA` is a **predecessor** of `wordB` if and only if we can insert **exactly one** letter anywhere in `wordA` **without changing the order of the other char...
dolphin
port this code from Visual Basic .NET to python: ```vb.net Function MaximumBuildingHeight(grid as Integer()()) As Integer Dim n As Integer = grid.Length Dim row_maxes(n - 1) As Integer Dim col_maxes(n - 1) As Integer Dim max_total As Integer = 0 For i As Integer = 0 To n - 1 For j As In...
dolphin
convert this code from Ruby to Elixir: ```ruby def first_bad_version(n) left, right = 1, n while left < right mid = left + (right - left) / 2 if is_bad_version(mid) right = mid else left = mid + 1 end end return left end ```
dolphin
Please focus on the algorithm of this problem and provide code in javascript: Given a string `s`, return _the number of **homogenous** substrings of_ `s`_._ Since the answer may be too large, return it **modulo** `109 + 7`. A string is **homogenous** if all the characters of the string are the same. A **substring** i...
dolphin
Please explain the following problem in detail and provide code in Object Pascal: You are given a **0-indexed** array of positive integers `tasks`, representing tasks that need to be completed **in order**, where `tasks[i]` represents the **type** of the `ith` task. You are also given a positive integer `space`, which...
dolphin
Please explain the following problem in detail and provide code in Haskell: Given a **zero-based permutation** `nums` (**0-indexed**), build an array `ans` of the **same length** where `ans[i] = nums[nums[i]]` for each `0 <= i < nums.length` and return it. A **zero-based permutation** `nums` is an array of **distinct*...
dolphin
Please explain the reasoning behind the following solution and provide code in Go: A company has `n` employees with a unique ID for each employee from `0` to `n - 1`. The head of the company is the one with `headID`. Each employee has one direct manager given in the `manager` array where `manager[i]` is the direct man...
dolphin
convert this code from Fortran to Elixir: ```fortran function max_value(n, x) implicit none character(len=*), intent(in) :: n integer, intent(in) :: x logical :: is_negative integer :: pos, i character(len=len(n)) :: new_n is_negative = n(1:1) == '-' pos = 1 + int(is_negative) do i = pos, len(n)...
dolphin
Please explain the reasoning behind the following solution and provide code in Haskell: The **XOR total** of an array is defined as the bitwise `XOR` of **all its elements**, or `0` if the array is **empty**. * For example, the **XOR total** of the array `[2,5,6]` is `2 XOR 5 XOR 6 = 1`. Given an array `nums`, retu...
dolphin
Please explain the following problem in detail and provide code in Lua: You are given an `m x n` integer matrix `grid`. We define an **hourglass** as a part of the matrix with the following form: Return _the **maximum** sum of the elements of an hourglass_. **Note** that an hourglass cannot be rotated and must be en...
dolphin
Please explain the reasoning behind the following solution and provide code in PHP: Design a **Skiplist** without using any built-in libraries. A **skiplist** is a data structure that takes `O(log(n))` time to add, erase and search. Comparing with treap and red-black tree which has the same function and performance, t...
dolphin
translate this code to R: ```fsharp let maxAlternatingSum (nums: int[]) = let mutable odd, even = 0, 0 for num in nums do let newOdd = max(even + num, odd) even <- max(odd - num, even) odd <- newOdd odd ```
dolphin