instruction_seed stringlengths 29 40.5k | source stringclasses 6
values |
|---|---|
Please focus on the algorithm of this problem and provide code in Lisp:
You are given a **0-indexed** integer array `nums`. You can apply the following operation any number of times:
* Pick any element from `nums` and put it at the end of `nums`.
The prefix sum array of `nums` is an array `prefix` of the same lengt... | dolphin |
convert this code from R to python:
```R
twoSum <- function(numbers, target) {
left <- 1
right <- length(numbers)
while (left < right) {
current_sum <- numbers[left] + numbers[right]
if (current_sum == target) {
return(c(left, right))
} else if (current_sum < target) {
left <- left + 1
... | dolphin |
translate this code to TypeScript:
```scala
def restoreString(s: String, indices: Array[Int]): String = {
val n = s.length
val shuffled = new Array[Char](n)
for (i <- 0 until n) {
shuffled(indices(i)) = s(i)
}
shuffled.mkString
}
``` | dolphin |
Please write the following solution using java:
There is a **bi-directional** graph with `n` vertices, where each vertex is labeled from `0` to `n - 1` (**inclusive**). The edges in the graph are represented as a 2D integer array `edges`, where each `edges[i] = [ui, vi]` denotes a bi-directional edge between vertex `ui... | dolphin |
Please focus on the functionality of this problem and provide code in javascript:
You are assigned to put some amount of boxes onto **one truck**. You are given a 2D array `boxTypes`, where `boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]`:
* `numberOfBoxesi` is the number of boxes of type `i`.
* `numberOfUni... | dolphin |
Please explain the following problem in detail and provide code in Rust:
Consider all the leaves of a binary tree, from left to right order, the values of those leaves form a **leaf value sequence**_._
For example, in the given tree above, the leaf value sequence is `(6, 7, 4, 9, 8)`.
Two binary trees are considered ... | dolphin |
Please focus on the efficiency of this problem and provide code in R:
You are given a **sorted** array `nums` of `n` non-negative integers and an integer `maximumBit`. You want to perform the following query `n` **times**:
1. Find a non-negative integer `k < 2maximumBit` such that `nums[0] XOR nums[1] XOR ... XOR num... | dolphin |
convert this code to Lua:
```elixir
defmodule Solution do
def topological_sort(n, group, before_items) do
adj_list = Enum.map(0..(n-1), fn _ -> [] end)
in_degree = Enum.map(0..(n-1), fn _ -> 0 end)
group_list = Enum.map(0..(m-1), fn _ -> [] end)
for i <- 0..(n-1) do
if group[i] != -1 do
... | dolphin |
Please explain the reasoning behind the following solution and provide code in Swift:
You are given an integer array `stations` that represents the positions of the gas stations on the **x-axis**. You are also given an integer `k`.
You should add `k` new gas stations. You can add the stations anywhere on the **x-axis*... | dolphin |
translate this code from Clojure to Julia:
```clojure
(defn max-subarray-sum [arr]
(let [n (count arr)
max-sum (nth arr 0)
curr-sum (nth arr 0)
max-with-deletion (nth arr 0)
left-sum (repeatedly n #(nth arr %))
right-sum (repeatedly n #(nth arr (- n % 1)))]
(loop [i 1]
... | dolphin |
translate this code to c++:
```javascript
function numberOfWays(n) {
const MOD = 1000000007;
let dp = new Array(n + 1).fill(0);
dp[0] = 1;
dp[1] = 1;
for (let i = 2; i <= n; i++)
dp[i] = (dp[i - 1] + dp[i - 2]) % MOD;
return dp[n];
}
```
| dolphin |
Please explain the reasoning behind the following solution and provide code in Objective-C:
You are given a **0-indexed** string `blocks` of length `n`, where `blocks[i]` is either `'W'` or `'B'`, representing the color of the `ith` block. The characters `'W'` and `'B'` denote the colors white and black, respectively.
... | dolphin |
Please explain the following problem in detail and provide code in Clojure:
You are given a **perfect binary tree** where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:
struct Node {
int val;
Node \*left;
Node \*right;
Node \*next;
}
Populate... | dolphin |
port this code to Ruby:
```lisp
(defun find-min-cost (cost)
(let ((n (length cost))
(dp (make-array (1+ n))))
(setf (aref dp 0) 0)
(setf (aref dp 1) 0)
(dotimes (i (- n 1))
(setf (aref dp (+ i 2))
(min (+ (aref dp (+ i 1)) (aref cost (+ i 1)))
(+ (aref dp i) (are... | dolphin |
Please explain the reasoning behind the following solution and provide code in python:
You are given an array of strings `tokens` that represents an arithmetic expression in a [Reverse Polish Notation](http://en.wikipedia.org/wiki/Reverse_Polish_notation).
Evaluate the expression. Return _an integer that represents th... | dolphin |
Please focus on the algorithm of this problem and provide code in Lua:
Given a string `path`, which is an **absolute path** (starting with a slash `'/'`) to a file or directory in a Unix-style file system, convert it to the simplified **canonical path**.
In a Unix-style file system, a period `'.'` refers to the curren... | dolphin |
translate this code from java to javascript:
```java
import java.util.HashSet;
public boolean isValidMatrix(int[][] matrix) {
int n = matrix.length;
for (int i = 0; i < n; ++i) {
HashSet<Integer> row = new HashSet<>(), col = new HashSet<>();
for (int j = 0; j < n; ++j) {
row.add(mat... | dolphin |
Please focus on the functionality of this problem and provide code in PHP:
There is a **family tree** rooted at `0` consisting of `n` nodes numbered `0` to `n - 1`. You are given a **0-indexed** integer array `parents`, where `parents[i]` is the parent for node `i`. Since node `0` is the **root**, `parents[0] == -1`.
... | dolphin |
Please explain the following problem in detail and provide code in R:
Given an integer array `nums`, return _the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle_.
**Example 1:**
**Input:** nums = \[2,2,3,4\]
**Output:** 3
**Explanation:** Valid combinatio... | dolphin |
convert this code from Lisp to Scheme:
```lisp
(defun is-path-crossing (path)
(let ((x 0)
(y 0)
(visited (make-hash-table)))
(setf (gethash (list x y) visited) t)
(loop for direction across path do
(ecase direction
(#\N (incf y))
(#\E (incf x))
(#\... | dolphin |
convert this code from Perl to Scala:
```perl
sub is_power_of_two {
my $n = shift;
return 0 if $n <= 0;
return ($n & ($n - 1)) == 0;
}
``` | dolphin |
Please write the following solution using Rust:
You are given two non-negative integer arrays `price` and `tastiness`, both arrays have the same length `n`. You are also given two non-negative integers `maxAmount` and `maxCoupons`.
For every integer `i` in range `[0, n - 1]`:
* `price[i]` describes the price of `it... | dolphin |
Please explain the following problem in detail and provide code in Perl:
Given two strings `s1` and `s2`, return `true` _if_ `s2` _contains a permutation of_ `s1`_, or_ `false` _otherwise_.
In other words, return `true` if one of `s1`'s permutations is the substring of `s2`.
**Example 1:**
**Input:** s1 = "ab ", s2... | dolphin |
Please write the following solution using Groovy:
A sequence of numbers is called an **arithmetic progression** if the difference between any two consecutive elements is the same.
Given an array of numbers `arr`, return `true` _if the array can be rearranged to form an **arithmetic progression**. Otherwise, return_ `f... | dolphin |
Please focus on the algorithm of this problem and provide code in Perl:
You are given the `root` of a binary tree with **unique values**.
In one operation, you can choose any two nodes **at the same level** and swap their values.
Return _the minimum number of operations needed to make the values at each level sorted ... | dolphin |
Please focus on the algorithm of this problem and provide code in Lua:
Given a 2D `grid` of `0`s and `1`s, return the number of elements in the largest **square** subgrid that has all `1`s on its **border**, or `0` if such a subgrid doesn't exist in the `grid`.
**Example 1:**
**Input:** grid = \[\[1,1,1\],\[1,0,1\],\... | dolphin |
port this code to Fortran:
```lisp
(defun sum-game (num)
(let* ((n (length num))
(sum1 0)
(sum2 0)
(cnt1 0)
(cnt2 0))
(dotimes (i (floor n 2))
(if (= (aref num i) ?\?)
(incf cnt1)
(incf sum1 (- (aref num i) 48))))
(dotimes (i (ceiling n 2) n)
(... | dolphin |
Please explain the following problem in detail and provide code in java:
Given an undirected tree consisting of `n` vertices numbered from `1` to `n`. A frog starts jumping from **vertex 1**. In one second, the frog jumps from its current vertex to another **unvisited** vertex if they are directly connected. The frog c... | dolphin |
Please write the following solution using Object Pascal:
You have `n` robots. You are given two **0-indexed** integer arrays, `chargeTimes` and `runningCosts`, both of length `n`. The `ith` robot costs `chargeTimes[i]` units to charge and costs `runningCosts[i]` units to run. You are also given an integer `budget`.
Th... | dolphin |
port this code to java:
```haskell
chalkReplacer :: [Int] -> Int -> Int
chalkReplacer chalk k = go chalk (k `mod` totalChalk) 0
where
totalChalk = sum chalk
go (x:xs) k i
| k < x = i
| otherwise = go xs (k - x) (i + 1)
go [] _ _ = 0
``` | dolphin |
Please explain the reasoning behind the following solution and provide code in F#:
Given an integer array `nums` sorted in **non-decreasing order**, remove the duplicates [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm) such that each unique element appears only **once**. The **relative order** of the e... | dolphin |
convert this code to javascript:
```swift
func maxProduct(_ words: [String]) -> Int {
let n = words.count
var mask = [Int](repeating: 0, count: n)
for i in 0..<n {
for c in words[i] {
mask[i] |= (1 << (c.asciiValue! - Character("a").asciiValue!))
}
}
var maxProduct =... | dolphin |
port this code to Fortran:
```julia
struct ListNode
val::Int
next::Union{ListNode,Nothing}
end
function addTwoNumbers(l1::Union{ListNode,Nothing}, l2::Union{ListNode,Nothing})
result = ListNode(0)
current = result
carry = 0
while l1!==nothing || l2!==nothing || carry!=0
s = (l1==nothing... | dolphin |
Please write the following solution using Ruby:
There exists an undirected and initially unrooted tree with `n` nodes indexed 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 `bi` in th... | dolphin |
convert this code from C# to Scheme:
```csharp
public class Node {
public int val;
public Node left;
public Node right;
public Node random;
public Node(int val = 0, Node left = null, Node right = null, Node random = null) {
this.val = val;
this.left = left;
this.right = righ... | dolphin |
Please explain the reasoning behind the following solution and provide code in Perl:
You have an `inventory` of different colored balls, and there is a customer that wants `orders` balls of **any** color.
The customer weirdly values the colored balls. Each colored ball's value is the number of balls **of that color** ... | dolphin |
Please explain the reasoning behind the following solution and provide code in java:
You are given an integer array `nums`. The **range** of a subarray of `nums` is the difference between the largest and smallest element in the subarray.
Return _the **sum of all** subarray ranges of_ `nums`_._
A subarray is a contigu... | dolphin |
translate this code from Haskell to Visual Basic .NET:
```haskell
wiggleSort :: [Int] -> [Int]
wiggleSort [] = []
wiggleSort xs = wiggleSortHelper $ zipWith ($) (cycle [id, reverse]) $ group xs
wiggleSortHelper :: [[Int]] -> [Int]
wiggleSortHelper [] = []
wiggleSortHelper xs = concat $ map (\ys -> [head ys]) xs ++ wig... | dolphin |
Please explain the following problem in detail and provide code in PHP:
A **ramp** in an integer array `nums` is a pair `(i, j)` for which `i < j` and `nums[i] <= nums[j]`. The **width** of such a ramp is `j - i`.
Given an integer array `nums`, return _the maximum width of a **ramp** in_ `nums`. If there is no **ramp*... | dolphin |
translate this code from Go to Perl:
```go
func ratioSubstringCount(s string, num1 int, num2 int) int {
count0, count1 := 0, 0
frequency := map[int]int{0: 1}
result := 0
for _, c := range s {
if c == '0' {
count0++
} else {
count1++
}
curr_diff :... | dolphin |
Please write the following solution using Mojo:
We have `n` buildings numbered from `0` to `n - 1`. Each building has a number of employees. It's transfer season, and some employees want to change the building they reside in.
You are given an array `requests` where `requests[i] = [fromi, toi]` represents an employee's... | dolphin |
convert this code to Groovy:
```cpp
bool isPowerOfFour(int n) {
if (n <= 0) return false;
while (n % 4 == 0) {
n /= 4;
}
return n == 1;
}
```
| dolphin |
Please explain the following problem in detail and provide code in Julia:
A conveyor belt has packages that must be shipped from one port to another within `days` days.
The `ith` package on the conveyor belt has a weight of `weights[i]`. Each day, we load the ship with packages on the conveyor belt (in the order given... | dolphin |
Please explain the reasoning behind the following solution and provide code in Ruby:
During the NBA playoffs, we always set the rather strong team to play with the rather weak team, like make the rank `1` team play with the rank `nth` team, which is a good strategy to make the contest more interesting.
Given `n` teams... | dolphin |
Please focus on the algorithm of this problem and provide code in Lua:
Given a string `num` which represents an integer, return `true` _if_ `num` _is a **strobogrammatic number**_.
A **strobogrammatic number** is a number that looks the same when rotated `180` degrees (looked at upside down).
**Example 1:**
**Input:... | dolphin |
Please explain the reasoning behind the following solution and provide code in R:
Given an array of strings `wordsDict` and two strings that already exist in the array `word1` and `word2`, return _the shortest distance between the occurrence of these two words in the list_.
**Note** that `word1` and `word2` may be the... | dolphin |
Please explain the following problem in detail and provide code in python:
Given the `head` of a linked list, return _the list after sorting it in **ascending order**_.
**Example 1:**
**Input:** head = \[4,2,1,3\]
**Output:** \[1,2,3,4\]
**Example 2:**
**Input:** head = \[-1,5,3,4,0\]
**Output:** \[-1,0,3,4,5\]
**... | dolphin |
convert this code to c++:
```csharp
using System;
using System.Collections.Generic;
public class Solution {
public int count_unique_substrings(string s) {
int n = s.Length;
HashSet<string> unique_substrings = new HashSet<string>();
for (int i = 0; i < n; i++) {
for (int j = i + ... | dolphin |
Please explain the reasoning behind the following solution and provide code in Objective-C:
You are given an array `nums` of positive integers and a **positive** integer `k`.
A subset of `nums` is **beautiful** if it does not contain two integers with an absolute difference equal to `k`.
Return _the number of **non-e... | dolphin |
convert this code to javascript:
```F#
let getLastMoment (n:int) (k:int) (time:int[][]) : int =
let mutable left = [for j in 0..k-1 -> time.[j].[0] + time.[j].[2], j] |> List.ofArray |> List.sort
let mutable right = []
let rec loop n =
match n with
| 0 -> ()
| _ ->
while... | dolphin |
Please explain the reasoning behind the following solution and provide code in java:
You are given the array `paths`, where `paths[i] = [cityAi, cityBi]` means there exists a direct path going from `cityAi` to `cityBi`. _Return the destination city, that is, the city without any path outgoing to another city._
It is g... | dolphin |
Please write the following solution using javascript:
Given two binary search trees `root1` and `root2`, return _a list containing all the integers from both trees sorted in **ascending** order_.
**Example 1:**
**Input:** root1 = \[2,1,4\], root2 = \[1,0,3\]
**Output:** \[0,1,1,2,3,4\]
**Example 2:**
**Input:** roo... | dolphin |
Please focus on the algorithm of this problem and provide code in Erlang:
We have `n` cities and `m` bi-directional `roads` where `roads[i] = [ai, bi]` connects city `ai` with city `bi`. Each city has a name consisting of exactly three upper-case English letters given in the string array `names`. Starting at any city `... | dolphin |
Please explain the reasoning behind the following solution and provide code in Visual Basic .NET:
Given an array of points on the **X-Y** plane `points` where `points[i] = [xi, yi]`, return _the area of the largest triangle that can be formed by any three different points_. Answers within `10-5` of the actual answer wi... | dolphin |
Please write the following solution using Clojure:
You are given a **0-indexed** integer array `nums` of length `n`.
You can perform the following operation as many times as you want:
* Pick an index `i` that you haven't picked before, and pick a prime `p` **strictly less than** `nums[i]`, then subtract `p` from `n... | dolphin |
Please write the following solution using Scala:
You are given `n` rectangles represented by a **0-indexed** 2D integer array `rectangles`, where `rectangles[i] = [widthi, heighti]` denotes the width and height of the `ith` rectangle.
Two rectangles `i` and `j` (`i < j`) are considered **interchangeable** if they have... | dolphin |
Please explain the reasoning behind the following solution and provide code in Haskell:
Given the strings `s1` and `s2` of size `n` and the string `evil`, return _the number of **good** strings_.
A **good** string has size `n`, it is alphabetically greater than or equal to `s1`, it is alphabetically smaller than or eq... | dolphin |
convert this code to Ruby:
```elixir
defmodule Solution do
def is_escape_possible(blocked, source, target) do
blocked_set = blocked
|> Enum.map(fn [x, y] -> "#{x}_#{y}" end)
|> Enum.into(%{})
visited = %{}
max_steps = 200
def dfs(x, y, tx, ty, steps, blocked_set, ... | dolphin |
Please explain the following problem in detail and provide code in Clojure:
Given a `root` of an [N-ary tree](https://leetcode.com/articles/introduction-to-n-ary-trees/), you need to compute the length of the diameter of the tree.
The diameter of an N-ary tree is the length of the **longest** path between any two node... | dolphin |
translate this code from Visual Basic .NET to Rust:
```
MIN-COST-SPLIT(nums, k):
n = LENGTH(nums)
count = [0] * 1001
dp = [0] * (n + 1)
i = 0
for j = 0 to n-1:
count[nums[j]] += 1
if count[nums[j]] == 2:
dp[j+1] = dp[i] + k + (j - i + 1)
else if coun... | dolphin |
Please write the following solution using ANSI C:
Given a string `s` representing a valid expression, implement a basic calculator to evaluate it, and return _the result of the evaluation_.
**Note:** You are **not** allowed to use any built-in function which evaluates strings as mathematical expressions, such as `eval... | dolphin |
translate this code to Perl:
```julia
mutable struct Leaderboard
players::Dict{Int,Int}
end
function addScore(lb::Leaderboard, playerId::Int, score::Int)
if haskey(lb.players, playerId)
lb.players[playerId] += score
else
lb.players[playerId] = score
end
end
function top(lb::Leaderboard... | dolphin |
port this code from TypeScript to Objective-C:
```typescript
function getMoneyAmount(n: number): number {
const dp: number[][] = Array.from({ length: n + 1 }, () => new Array(n + 1).fill(0));
for (let i = n - 1; i >= 1; i--) {
for (let j = i + 1; j <= n; j++) {
let min_cost = Number.POSITIVE... | dolphin |
Please explain the following problem in detail and provide code in Ruby:
Design and implement a data structure for a compressed string iterator. The given compressed string will be in the form of each letter followed by a positive integer representing the number of this letter existing in the original uncompressed stri... | dolphin |
Please write the following solution using Haskell:
In the "100 game " two players take turns adding, to a running total, any integer from `1` to `10`. The player who first causes the running total to **reach or exceed** 100 wins.
What if we change the game so that players **cannot** re-use integers?
For example, two ... | dolphin |
Please focus on the functionality of this problem and provide code in Objective-C:
A city is represented as a **bi-directional connected** graph with `n` vertices where each vertex is labeled from `1` to `n` (**inclusive**). The edges in the graph are represented as a 2D integer array `edges`, where each `edges[i] = [u... | dolphin |
Please explain the reasoning behind the following solution and provide code in Erlang:
Implement the `BSTIterator` class that represents an iterator over the **[in-order traversal](https://en.wikipedia.org/wiki/Tree_traversal#In-order_(LNR))** of a binary search tree (BST):
* `BSTIterator(TreeNode root)` Initializes... | dolphin |
Please focus on the functionality of this problem and provide code in TypeScript:
You are given an array of integers `stones` where `stones[i]` is the weight of the `ith` stone.
We are playing a game with the stones. On each turn, we choose the **heaviest two stones** and smash them together. Suppose the heaviest two ... | dolphin |
Please focus on the functionality of this problem and provide code in Dart:
Given an array of integers `nums`, sort the array in **increasing** order based on the frequency of the values. If multiple values have the same frequency, sort them in **decreasing** order.
Return the _sorted array_.
**Example 1:**
**Input:... | dolphin |
Please focus on the algorithm of this problem and provide code in Groovy:
An **alphabetical continuous string** is a string consisting of consecutive letters in the alphabet. In other words, it is any substring of the string `"abcdefghijklmnopqrstuvwxyz "`.
* For example, `"abc "` is an alphabetical continuous strin... | dolphin |
Please explain the reasoning behind the following solution and provide code in C#:
There are `k` workers who want to move `n` boxes from an old warehouse to a new one. You are given the two integers `n` and `k`, and a 2D integer array `time` of size `k x 4` where `time[i] = [leftToRighti, pickOldi, rightToLefti, putNew... | dolphin |
Please explain the reasoning behind the following solution and provide code in Visual Basic .NET:
You are given a series of video clips from a sporting event that lasted `time` seconds. These video clips can be overlapping with each other and have varying lengths.
Each video clip is described by an array `clips` where... | dolphin |
Please focus on the algorithm of this problem and provide code in python:
You are working in a ball factory where you have `n` balls numbered from `lowLimit` up to `highLimit` **inclusive** (i.e., `n == highLimit - lowLimit + 1`), and an infinite number of boxes numbered from `1` to `infinity`.
Your job at this factor... | dolphin |
port this code to TypeScript:
```cpp
int countHomogenous(string s) {
const int MOD = 1e9 + 7;
long long count = 1, total = 0;
for (int i = 1; i < s.size(); ++i) {
count = (s[i] == s[i - 1]) ? count + 1 : 1;
total = (total + count) % MOD;
}
return total + count;
}
```
| dolphin |
Please write the following solution using Erlang:
Let the function `f(s)` be the **frequency of the lexicographically smallest character** in a non-empty string `s`. For example, if `s = "dcce "` then `f(s) = 2` because the lexicographically smallest character is `'c'`, which has a frequency of 2.
You are given an arr... | dolphin |
Please explain the following problem in detail and provide code in Elixir:
You are given a **0-indexed** string `s` and are tasked with finding two **non-intersecting palindromic** substrings of **odd** length such that the product of their lengths is maximized.
More formally, you want to choose four integers `i`, `j`... | dolphin |
Please explain the following problem in detail and provide code in Lisp:
Given two strings `s` and `t`, return `true` _if_ `t` _is an anagram of_ `s`_, and_ `false` _otherwise_.
An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters ... | dolphin |
translate this code to Scheme:
```swift
class Solution {
func max(_ a: Int, _ b: Int) -> Int {
return a > b ? a : b
}
func findMax(nums: [Int], start: Int, end: Int) -> Int {
var maxVal = nums[start]
for i in start+1...end {
maxVal = max(maxVal, nums[i])
... | dolphin |
Please focus on the functionality of this problem and provide code in TypeScript:
You are given two **0-indexed** integer arrays `nums` and `removeQueries`, both of length `n`. For the `ith` query, the element in `nums` at the index `removeQueries[i]` is removed, splitting `nums` into different segments.
A **segment**... | dolphin |
convert this code from PHP to Scala:
````php
function defective_sensor($sensor1, $sensor2) {
for ($i = 0; $i < count($sensor1); $i++) {
if ($sensor1[$i] != $sensor2[$i]) {
if (array_slice($sensor1, $i+1) == array_slice($sensor2, $i, -1)) {
return 2;
} else if (array_s... | dolphin |
Please focus on the functionality of this problem and provide code in Julia:
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 |
Please focus on the efficiency of this problem and provide code in Mojo:
There is an `8 x 8` chessboard containing `n` pieces (rooks, queens, or bishops). You are given a string array `pieces` of length `n`, where `pieces[i]` describes the type (rook, queen, or bishop) of the `ith` piece. In addition, you are given a 2... | dolphin |
Please focus on the functionality of this problem and provide code in Object Pascal:
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 gro... | dolphin |
Please explain the following problem in detail and provide code in Dart:
You are given an integer array, `nums`, and an integer `k`. `nums` comprises of only `0`'s and `1`'s. In one move, you can choose two **adjacent** indices and swap their values.
Return _the **minimum** number of moves required so that_ `nums` _ha... | dolphin |
translate this code to Haskell:
```perl
sub least_moves {
my $board = shift;
my $n = scalar @$board;
my @visited = ();
my $steps = 0;
my @queue = (1);
push @visited, 1;
while (@queue) {
my $size = scalar @queue;
for (my $i = 0; $i < $size; $i++) {
my $curr = shift... | dolphin |
Please explain the following problem in detail and provide code in javascript:
We have a wooden plank of the length `n` **units**. Some ants are walking on the plank, each ant moves with a speed of **1 unit per second**. Some of the ants move to the **left**, the other move to the **right**.
When two ants moving in tw... | dolphin |
port this code from c++ to Swift:
```cpp
#include <vector>
#include <queue>
#include <limits>
#include <utility>
std::pair<int, int> smallestRange(std::vector<std::vector<int>>& nums) {
auto listComparator = [](const auto& a, const auto& b) {
return a.first > b.first;
};
std::priority_queue<std::p... | dolphin |
Please explain the following problem in detail and provide code in Groovy:
Given a string `s`, return _the length of the longest repeating substrings_. If no repeating substring exists, return `0`.
**Example 1:**
**Input:** s = "abcd "
**Output:** 0
**Explanation:** There is no repeating substring.
**Example 2:**
... | dolphin |
port this code to Scala:
```ruby
def answer_queries(nums, queries)
n = queries.length
max_time = queries.map(&:first).max
ans = Array.new(n)
prefix_sum = Array.new(max_time + 2, 0)
first_idx = Array.new(101, -1)
last_idx = Array.new(101, -1)
idx = 0
nums.each_with_index do |num, i|
... | dolphin |
Please explain the reasoning behind the following solution and provide code in Go:
An array `arr` a **mountain** if the following properties hold:
* `arr.length >= 3`
* There exists some `i` with `0 < i < arr.length - 1` such that:
* `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]`
* `arr[i] > arr[i + 1] ... | dolphin |
Please focus on the algorithm of this problem and provide code in Rust:
There is a long and thin painting that can be represented by a number line. The painting was painted with multiple overlapping segments where each segment was painted with a **unique** color. You are given a 2D integer array `segments`, where `segm... | dolphin |
convert this code to R:
```go
func minimumMoves(arr []int) int {
dp := make([][]int, len(arr))
for i := range dp {
dp[i] = make([]int, len(arr))
for j := range dp[i] {
dp[i][j] = -1
}
}
var minRemovals func(int, int) int
minRemovals = func(i, j int) int {
... | dolphin |
Please explain the following problem in detail and provide code in javascript:
You are given a string `s` that consists of lower case English letters and brackets.
Reverse the strings in each pair of matching parentheses, starting from the innermost one.
Your result should **not** contain any brackets.
**Example 1:*... | dolphin |
Please explain the reasoning behind the following solution and provide code in Go:
Given a string `formula` representing a chemical formula, return _the count of each atom_.
The atomic element always starts with an uppercase character, then zero or more lowercase letters, representing the name.
One or more digits rep... | dolphin |
Please focus on the functionality of this problem and provide code in Perl:
You are given a list of songs where the `ith` song has a duration of `time[i]` seconds.
Return _the number of pairs of songs for which their total duration in seconds is divisible by_ `60`. Formally, we want the number of indices `i`, `j` such... | dolphin |
port this code from Groovy to Elixir:
```groovy
import java.util.Random
class RandomizedCollection {
Map<Integer, Set<Integer>> indices
List<Integer> nums
RandomizedCollection() {
indices = [:].withDefault { HashSet<>() }
nums = []
}
boolean insert(int val) {
nums.add(val)... | dolphin |
Please write the following solution using Haskell:
Given an integer `n`, return _`true` if it is a power of three. Otherwise, return `false`_.
An integer `n` is a power of three, if there exists an integer `x` such that `n == 3x`.
**Example 1:**
**Input:** n = 27
**Output:** true
**Explanation:** 27 = 33
**Example ... | dolphin |
Please explain the following problem in detail and provide code in Elixir:
You are given an integer array `power` where `power[i]` is the power of the `ith` monster.
You start with `0` mana points, and each day you increase your mana points by `gain` where `gain` initially is equal to `1`.
Each day, after gaining `ga... | dolphin |
Please explain the following problem in detail and provide code in Go:
You are given an `m x n` integer grid `accounts` where `accounts[i][j]` is the amount of money the `ith` customer has in the `jth` bank. Return _the **wealth** that the richest customer has._
A customer's **wealth** is... | dolphin |
Please write the following solution using Object Pascal:
You are given an integer array `nums` of length `n`.
Assume `arrk` to be an array obtained by rotating `nums` by `k` positions clock-wise. We define the **rotation function** `F` on `nums` as follow:
* `F(k) = 0 * arrk[0] + 1 * arrk[1] + ... + (n - 1) * arrk[... | dolphin |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.