instruction_seed stringlengths 29 40.5k | source stringclasses 6
values |
|---|---|
convert this code to Perl:
```typescript
class TreeNode {
val: number
left: TreeNode | null
right: TreeNode | null
constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
this.val = (val === undefined ? 0 : val)
this.left = (left === undefined ? null : left)
... | dolphin |
Please explain the following problem in detail and provide code in Rust:
In a string composed of `'L'`, `'R'`, and `'X'` characters, like `"RXXLRXRXL "`, a move consists of either replacing one occurrence of `"XL "` with `"LX "`, or replacing one occurrence of `"RX "` with `"XR "`. Given the starting string `start` and... | dolphin |
Please explain the following problem in detail and provide code in C#:
You are given an integer array `nums`, and you can perform the following operation **any** number of times on `nums`:
* Swap the positions of two elements `nums[i]` and `nums[j]` if `gcd(nums[i], nums[j]) > 1` where `gcd(nums[i], nums[j])` is the... | dolphin |
Please write the following solution using Dart:
There are `n` buildings in a line. You are given an integer array `heights` of size `n` that represents the heights of the buildings in the line.
The ocean is to the right of the buildings. A building has an ocean view if the building can see the ocean without obstructio... | dolphin |
Please write the following solution using PHP:
You are given some lists of `regions` where the first region of each list includes all other regions in that list.
Naturally, if a region `x` contains another region `y` then `x` is bigger than `y`. Also, by definition, a region `x` contains itself.
Given two regions: `r... | dolphin |
translate this code to javascript:
```php
function find_max_consecutive($nums, $k) {
$left = $right = $zeros = $max_consec = 0;
while ($right < count($nums)) {
if ($nums[$right] == 0) {
$zeros++;
}
while ($zeros > $k) {
if ($nums[$left] == 0) {
$ze... | dolphin |
translate this code from Groovy to Fortran:
```groovy
def numDecodings(String s) {
int n = s.size()
int[] dp = new int[n + 1]
dp[0] = 1
dp[1] = s[0] != '0' ? 1 : 0
for (int i = 2; i <= n; i++) {
int oneDigit = Integer.parseInt(s.substring(i - 1, i))
int twoDigits = Integer.parseInt(... | dolphin |
convert this code to Lua:
```dart
int maxSumRangeQuery(List<int> nums, List<List<int>> requests) {
int n = nums.length;
List<int> count = List.filled(n, 0);
for (List<int> request in requests) {
count[request[0]] += 1;
if (request[1] + 1 < n) {
count[request[1] + 1] -= 1;
}
}
for (int i = 1;... | dolphin |
Please explain the reasoning behind the following solution and provide code in c++:
You are given a string `s` that contains digits `0-9`, addition symbols `'+'`, and multiplication symbols `'*'` **only**, representing a **valid** math expression of **single digit numbers** (e.g., `3+5*2`). This expression was given to... | dolphin |
Please explain the following problem in detail and provide code in Rust:
You are given two integer arrays of equal length `target` and `arr`. In one step, you can select any **non-empty subarray** of `arr` and reverse it. You are allowed to make any number of steps.
Return `true` _if you can make_ `arr` _equal to_ `ta... | dolphin |
Please explain the reasoning behind the following solution and provide code in Clojure:
Given an array of keywords `words` and a string `s`, make all appearances of all keywords `words[i]` in `s` bold. Any letters between **and** tags become bold.
Return `s` _after adding the bold tags_. The returned string should use... | dolphin |
Please explain the following problem in detail and provide code in Haskell:
You are given a **0-indexed** integer array `nums`. A pair of indices `(i, j)` is a **bad pair** if `i < j` and `j - i != nums[j] - nums[i]`.
Return _the total number of **bad pairs** in_ `nums`.
**Example 1:**
**Input:** nums = \[4,1,3,3\]
... | dolphin |
Please explain the following problem in detail and provide code in Swift:
You are given an integer array `nums` of size `n`. You are asked to solve `n` queries for each integer `i` in the range `0 <= i < n`.
To solve the `ith` query:
1. Find the **minimum value** in each possible subarray of size `i + 1` of the arra... | dolphin |
Please focus on the algorithm of this problem and provide code in Perl:
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 to... | dolphin |
Please explain the reasoning behind the following solution and provide code in Kotlin:
There is a special typewriter with lowercase English letters `'a'` to `'z'` arranged in a **circle** with a **pointer**. A character can **only** be typed if the pointer is pointing to that character. The pointer is **initially** poi... | dolphin |
translate this code from Object Pascal to Ruby:
```
uses Math;
function constructArray(target: array of Integer): Boolean;
var
n, totalSum, x, diff, i: Integer;
arr: array of Integer;
begin
n := Length(target);
totalSum := 0;
for i := 0 to n - 1 do
totalSum := totalSum + target[i];
if totalSum mod n <>... | dolphin |
Please explain the reasoning behind the following solution and provide code in python:
A peak element is an element that is strictly greater than its neighbors.
Given a **0-indexed** integer array `nums`, find a peak element, and return its index. If the array contains multiple peaks, return the index to **any of the ... | dolphin |
translate this code to javascript:
```scheme
(define (num-jewels-in-stones jewels stones)
(define count 0)
(define len-stones (string-length stones))
(define len-jewels (string-length jewels))
(do ((i 0 (+ i 1)))
((= i len-stones))
(do ((j 0 (+ j 1)))
((= j len-jewels))
(if (char=? (stri... | dolphin |
Please explain the following problem in detail and provide code in Swift:
Given an integer `num`, repeatedly add all its digits until the result has only one digit, and return it.
**Example 1:**
**Input:** num = 38
**Output:** 2
**Explanation:** The process is
38 --> 3 + 8 --> 11
11 --> 1 + 1 --> 2
Since 2 has only ... | dolphin |
Please explain the following problem in detail and provide code in Dart:
Given the `head` of a linked list, return _the node where the cycle begins. If there is no cycle, return_ `null`.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the `next` p... | dolphin |
Please explain the following problem in detail and provide code in Object Pascal:
Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (`push`, `peek`, `pop`, and `empty`).
Implement the `MyQueue` class:
* `void push(int x)` Push... | dolphin |
translate this code from ANSI C to R:
```c
int dfs(int* freq) {
int sum = 0;
for (int i = 0; i < 26; i++) {
if (freq[i] > 0) {
sum++;
freq[i]--;
sum += dfs(freq);
freq[i]++;
}
}
return sum;
}
int countPossibleSequences(char* tiles) {
i... | dolphin |
Please focus on the algorithm of this problem and provide code in Groovy:
You are given the `root` of a binary tree where each node has a value in the range `[0, 25]` representing the letters `'a'` to `'z'`.
Return _the **lexicographically smallest** string that starts at a leaf of this tree and ends at the root_.
As... | dolphin |
Please explain the reasoning behind the following solution and provide code in java:
In a row of dominoes, `tops[i]` and `bottoms[i]` represent the top and bottom halves of the `ith` domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.)
We may rotate the `ith` domino, so that `tops[... | dolphin |
Please focus on the algorithm of this problem and provide code in Ruby:
An array `A` is larger than some array `B` if for the first index `i` where `A[i] != B[i]`, `A[i] > B[i]`.
For example, consider `0`\-indexing:
* `[1,3,2,4] > [1,2,2,4]`, since at index `1`, `3 > 2`.
* `[1,4,4,4] < [2,1,1,1]`, since at index ... | dolphin |
Please explain the reasoning behind the following solution and provide code in python:
A sentence consists of lowercase letters (`'a'` to `'z'`), digits (`'0'` to `'9'`), hyphens (`'-'`), punctuation marks (`'!'`, `'.'`, and `','`), and spaces (`' '`) only. Each sentence can be broken down into **one or more tokens** s... | dolphin |
Please explain the reasoning behind the following solution and provide code in Rust:
You are given the `head` of a linked list. **Delete** the **middle node**, and return _the_ `head` _of the modified linked list_.
The **middle node** of a linked list of size `n` is the `⌊n / 2⌋th` node from the **start** using **0-ba... | dolphin |
Please explain the following problem in detail and provide code in Elixir:
Given the `head` of a linked list, remove the `nth` node from the end of the list and return its head.
**Example 1:**
**Input:** head = \[1,2,3,4,5\], n = 2
**Output:** \[1,2,3,5\]
**Example 2:**
**Input:** head = \[1\], n = 1
**Output:** \[... | dolphin |
convert this code to Go:
```java
public class TreeNode {
boolean isLeaf;
boolean val;
TreeNode topLeft;
TreeNode topRight;
TreeNode bottomLeft;
TreeNode bottomRight;
}
public TreeNode intersect(TreeNode quadTree1, TreeNode quadTree2) {
if (quadTree1.isLeaf) {
return quadTree1.val ? ... | dolphin |
Please focus on the efficiency of this problem and provide code in Perl:
Design an algorithm to encode an N-ary tree into a binary tree and decode the binary tree to get the original N-ary tree. An N-ary tree is a rooted tree in which each node has no more than N children. Similarly, a binary tree is a rooted tree in w... | dolphin |
Please explain the following problem in detail and provide code in Mojo:
You are given an integer array `nums`, and you can perform the following operation **any** number of times on `nums`:
* Swap the positions of two elements `nums[i]` and `nums[j]` if `gcd(nums[i], nums[j]) > 1` where `gcd(nums[i], nums[j])` is t... | dolphin |
Please explain the following problem in detail and provide code in python:
Given the array of integers `nums`, you will choose two different indices `i` and `j` of that array. _Return the maximum value of_ `(nums[i]-1)*(nums[j]-1)`.
**Example 1:**
**Input:** nums = \[3,4,5,2\]
**Output:** 12
**Explanation:** If you ... | dolphin |
Please explain the following problem in detail and provide code in Lisp:
Given a **0-indexed** integer array `nums`, find a **0-indexed** integer array `answer` where:
* `answer.length == nums.length`.
* `answer[i] = |leftSum[i] - rightSum[i]|`.
Where:
* `leftSum[i]` is the sum of elements to the left of the i... | dolphin |
port this code from Go to Julia:
```go
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func deleteNode(root *TreeNode, key int) *TreeNode {
if root == nil {
return nil
}
if key < root.Val {
root.Left = deleteNode(root.Left, key)
} else if key > root.Val {
... | dolphin |
port this code to TypeScript:
```javascript
function makeFancyString(s) {
let result = s[0];
let count = 1;
for (let i = 1; i < s.length; i++) {
if (s[i] === s[i - 1]) {
count++;
} else {
count = 1;
}
if (count < 3) {
result += s[i];
... | dolphin |
Please explain the reasoning behind the following solution and provide code in Fortran:
There is a special typewriter with lowercase English letters `'a'` to `'z'` arranged in a **circle** with a **pointer**. A character can **only** be typed if the pointer is pointing to that character. The pointer is **initially** po... | dolphin |
port this code to Kotlin:
```php
function searchInsert($nums, $target) {
$left = 0;
$right = count($nums) - 1;
while ($left <= $right) {
$mid = floor(($left + $right) / 2);
if ($nums[$mid] == $target) {
return $mid;
} elseif ($nums[$mid] < $target) {
$left = $... | dolphin |
Please explain the reasoning behind the following solution and provide code in Elixir:
You are given an integer array `height` of length `n`. There are `n` vertical lines drawn such that the two endpoints of the `ith` line are `(i, 0)` and `(i, height[i])`.
Find two lines that together with the x-axis form a container... | dolphin |
Please explain the reasoning behind the following solution and provide code in Scheme:
You are given a license key represented as a string `s` that consists of only alphanumeric characters and dashes. The string is separated into `n + 1` groups by `n` dashes. You are also given an integer `k`.
We want to reformat the ... | dolphin |
port this code from R to python:
```R
reverse_list <- function(head) {
prev <- NULL
current <- head
while (!is.null(current)) {
next <- current$next
current$next <- prev
prev <- current
current <- next
}
return(prev)
}
``` | dolphin |
Please write the following solution using TypeScript:
Given an `m x n` `board` of characters and a list of strings `words`, return _all words on the board_.
Each word must be constructed from letters of sequentially adjacent cells, where **adjacent cells** are horizontally or vertically neighboring. The same letter ce... | dolphin |
Please write the following solution using TypeScript:
Given an integer `n`, return _the least number of perfect square numbers that sum to_ `n`.
A **perfect square** is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, `1`, `4`, `9`, and `16` are p... | dolphin |
translate this code to C#:
```fortran
function partition_labels(s) result(partition_lengths)
character(len=*), intent(in) :: s
integer :: last(26), ans(500), j, anchor, i, c, n
n = len(s)
last = 0
do i = 1, n
c = ichar(s(i)) - ichar('a') + 1
last(c) = i
end do
j = 0
ancho... | dolphin |
translate this code to Haskell:
```lisp
(defun max-sum-under-k (nums k)
(let ((max-sum -1))
(loop for i below (length nums)
do (loop for j from (1+ i) below (length nums)
do (let ((sum (+ (elt nums i) (elt nums j))))
(when (and (< sum k) (> sum max-sum))
... | dolphin |
Please explain the reasoning behind the following solution and provide code in Object Pascal:
Given an array of strings `wordsDict` and two different strings that already exist in the array `word1` and `word2`, return _the shortest distance between these two words in the list_.
**Example 1:**
**Input:** wordsDict = \... | dolphin |
translate this code from Dart to Perl:
```dart
List<String> splitMessage(String message, int limit) {
int n = message.length;
int a = (limit - 3) * (n ~/ (limit - 3)) - n;
int b = n ~/ (limit - 3);
if ((n + b + a) % (limit - 2) != 0) {
return [];
}
int num_parts = (n + b + a) ~/ (limit - 2);
List<Stri... | dolphin |
Please explain the reasoning behind the following solution and provide code in Object Pascal:
Given an array of integers `arr`, and three integers `a`, `b` and `c`. You need to find the number of good triplets.
A triplet `(arr[i], arr[j], arr[k])` is **good** if the following conditions are true:
* `0 <= i < j < k ... | dolphin |
Please write the following solution using Dart:
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`.
* `numberOfUnitsPerBoxi` is the number of units ... | dolphin |
Please explain the following problem in detail and provide code in Julia:
You are given an `m x n` integer matrix `grid`, where you can move from a cell to any adjacent cell in all `4` directions.
Return _the number of **strictly** **increasing** paths in the grid such that you can start from **any** cell and end at *... | dolphin |
Please explain the following problem in detail and provide code in PHP:
You are given the `root` of a **binary search tree** and an array `queries` of size `n` consisting of positive integers.
Find a **2D** array `answer` of size `n` where `answer[i] = [mini, maxi]`:
* `mini` is the **largest** value in the tree th... | dolphin |
convert this code to TypeScript:
```php
function cherryPickup($grid) {
$rows = count($grid);
$cols = count($grid[0]);
$dp = array_fill(0, $rows, array_fill(0, $cols, array_fill(0, $cols, 0)));
for ($row = $rows - 1; $row >= 0; $row--) {
for ($col1 = 0; $col1 < $cols; $col1++) {
... | dolphin |
Please explain the following problem in detail and provide code in Object Pascal:
You are given an array of positive integers `arr`. Perform some operations (possibly none) on `arr` so that it satisfies these conditions:
* The value of the **first** element in `arr` must be `1`.
* The absolute difference between a... | dolphin |
Please focus on the functionality of this problem and provide code in Go:
You are given an integer array `target` and an integer `n`.
You have an empty stack with the two following operations:
* **`"Push "`**: pushes an integer to the top of the stack.
* **`"Pop "`**: removes the integer on the top of the stack.
... | dolphin |
Please explain the following problem in detail and provide code in javascript:
Roman numerals are represented by seven different symbols: `I`, `V`, `X`, `L`, `C`, `D` and `M`.
**Symbol** **Value**
I 1
V 5
X 10
L 50
C 100
D 500
M ... | dolphin |
Please focus on the functionality of this problem and provide code in PHP:
Design a Leaderboard class, which has 3 functions:
1. `addScore(playerId, score)`: Update the leaderboard by adding `score` to the given player's score. If there is no player with such id in the leaderboard, add him to the leaderboard with the... | dolphin |
Please focus on the algorithm of this problem and provide code in C#:
A **transformation sequence** from word `beginWord` to word `endWord` using a dictionary `wordList` is a sequence of words `beginWord -> s1 -> s2 -> ... -> sk` such that:
* Every adjacent pair of words differs by a single letter.
* Every `si` fo... | dolphin |
Please focus on the efficiency of this problem and provide code in TypeScript:
Given a `node` in a binary search tree, return _the in-order successor of that node in the BST_. If that node has no in-order successor, return `null`.
The successor of a `node` is the node with the smallest key greater than `node.val`.
Yo... | dolphin |
convert this code to Groovy:
```mojo
class TreeNode(val) {
var left = null
var right = null
}
sub printTree(root) {
if root == null {
return [[]]
}
// Calculate Depth
var depth = 0
var q = Queue.new()
q.enqueue(root)
while !q.isEmpty() {
depth += 1
for i... | dolphin |
Please explain the following problem in detail and provide code in Elixir:
You are given a **0-indexed** integer array `nums` and an integer `value`.
In one operation, you can add or subtract `value` from any element of `nums`.
* For example, if `nums = [1,2,3]` and `value = 2`, you can choose to subtract `value` f... | dolphin |
Please explain the reasoning behind the following solution and provide code in Rust:
Given a **directed acyclic graph**, with `n` vertices numbered from `0` to `n-1`, and an array `edges` where `edges[i] = [fromi, toi]` represents a directed edge from node `fromi` to node `toi`.
Find _the smallest set of vertices from... | dolphin |
Please focus on the algorithm of this problem and provide code in TypeScript:
A `k x k` **magic square** is a `k x k` grid filled with integers such that every row sum, every column sum, and both diagonal sums are **all equal**. The integers in the magic square **do not have to be distinct**. Every `1 x 1` grid is triv... | dolphin |
Please write the following solution using Object Pascal:
On an `n x n` chessboard, a knight starts at the cell `(row, column)` and attempts to make exactly `k` moves. The rows and columns are **0-indexed**, so the top-left cell is `(0, 0)`, and the bottom-right cell is `(n - 1, n - 1)`.
A chess knight has eight possib... | dolphin |
Please explain the following problem in detail and provide code in Dart:
Given the `head` of a singly linked list and two integers `left` and `right` where `left <= right`, reverse the nodes of the list from position `left` to position `right`, and return _the reversed list_.
**Example 1:**
**Input:** head = \[1,2,3,... | dolphin |
Please write the following solution using Erlang:
Given a positive integer `num`, split it into two non-negative integers `num1` and `num2` such that:
* The concatenation of `num1` and `num2` is a permutation of `num`.
* In other words, the sum of the number of occurrences of each digit in `num1` and `num2` is... | dolphin |
Please write the following solution using F#:
There are `n` kids with candies. You are given an integer array `candies`, where each `candies[i]` represents the number of candies the `ith` kid has, and an integer `extraCandies`, denoting the number of extra candies that you have.
Return _a boolean array_ `result` _of l... | dolphin |
Please focus on the functionality of this problem and provide code in Ruby:
Given a binary tree with the following rules:
1. `root.val == 0`
2. If `treeNode.val == x` and `treeNode.left != null`, then `treeNode.left.val == 2 * x + 1`
3. If `treeNode.val == x` and `treeNode.right != null`, then `treeNode.right.val =... | dolphin |
Please focus on the algorithm of this problem and provide code in javascript:
Write an efficient algorithm that searches for a value `target` in an `m x n` integer matrix `matrix`. This matrix has the following properties:
* Integers in each row are sorted in ascending from left to right.
* Integers in each column... | dolphin |
translate this code to Lua:
```ruby
def find_rotate_steps(ring, key)
n, m = ring.length, key.length
dp = Array.new(m+1) { Array.new(n, 0) }
(m-1).downto(0).each do |i|
(0...n).each do |j|
dp[i][j] = Float::INFINITY
(0...n).each do |k|
if ring[k] == key[i]
... | dolphin |
translate this code from Dart to Groovy:
```dart
class TreeNode {
int val;
TreeNode? left;
TreeNode? right;
TreeNode(this.val, [this.left, this.right]);
}
bool hasPathSum(TreeNode? root, int targetSum) {
if (root == null) {
return false;
}
if (root.left == null && root.right == null) {
return ta... | dolphin |
port this code to c++:
```elixir
defmodule Solution do
def minimum_cost_path(grid, moveCost) do
n = length(grid[0])
cost = grid[0]
for i <- 1..(length(grid)-1) do
new_cost = []
for j <- 0..(n-1) do
min_cost = :math.inf
for k <- 0..(n-1) do
min_cost = min(min_cost, co... | dolphin |
Please focus on the efficiency of this problem and provide code in Visual Basic .NET:
Given the radius and the position of the center of a circle, implement the function `randPoint` which generates a uniform random point inside the circle.
Implement the `Solution` class:
* `Solution(double radius, double x_center, ... | dolphin |
Please write the following solution using TypeScript:
Given the `head` of a singly linked list that is sorted in **non-decreasing** order using the **absolute values** of its nodes, return _the list sorted in **non-decreasing** order using the **actual values** of its nodes_.
**Example 1:**
**Input:** head = \[0,2,-5... | dolphin |
Please explain the following problem in detail and provide code in c++:
Given the `root` of a binary tree, invert the tree, and return _its root_.
**Example 1:**
**Input:** root = \[4,2,7,1,3,6,9\]
**Output:** \[4,7,2,9,6,3,1\]
**Example 2:**
**Input:** root = \[2,1,3\]
**Output:** \[2,3,1\]
**Example 3:**
**Inpu... | dolphin |
translate this code to Elixir:
```haskell
goodSubarrays :: [Int] -> Int -> Int
goodSubarrays nums k = count
where
count = length $ filter good $ subarrays nums
good lst = length (nub lst) == k
subarrays [] = []
subarrays (x:xs) = [x : ys | ys <- ([] : subarrays xs)] ++ subarrays xs
``` | dolphin |
Please explain the following problem in detail and provide code in F#:
Given a string `s`, partition the string into one or more **substrings** such that the characters in each substring are **unique**. That is, no letter appears in a single substring more than **once**.
Return _the **minimum** number of substrings in... | dolphin |
Please focus on the functionality of this problem and provide code in Fortran:
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 ... | dolphin |
Please write the following solution using Haskell:
You have `n` buckets each containing some gallons of water in it, represented by a **0-indexed** integer array `buckets`, where the `ith` bucket contains `buckets[i]` gallons of water. You are also given an integer `loss`.
You want to make the amount of water in each ... | dolphin |
Please focus on the efficiency of this problem and provide code in Kotlin:
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... | dolphin |
translate this code from Haskell to Elixir:
```haskell
simplifiedFractions :: Int -> [String]
simplifiedFractions n = [show x ++ "/" ++ show y | y <- [2..n], x <- [1..(y-1)], gcd x y == 1]
``` | dolphin |
Please explain the following problem in detail and provide code in PHP:
For a binary tree **T**, we can define a **flip operation** as follows: choose any node, and swap the left and right child subtrees.
A binary tree **X** is _flip equivalent_ to a binary tree **Y** if and only if we can make **X** equal to **Y** af... | dolphin |
Please explain the following problem in detail and provide code in PHP:
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** ... | dolphin |
port this code from Lua to python:
```lua
function firstDayBeenInAllRooms(nextVisit)
local n = #nextVisit
local MOD = 10^9 + 7
local dp = {}
dp[1] = 1
for i = 2, n do
dp[i] = (dp[i - 1] * 2 - dp[nextVisit[i - 1]] + 2) % MOD
end
return dp[n]
end
``` | dolphin |
Please explain the reasoning behind the following solution and provide code in Haskell:
[Run-length encoding](http://en.wikipedia.org/wiki/Run-length_encoding) is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and t... | dolphin |
Please focus on the functionality of this problem and provide code in ANSI C:
The thief has found himself a new place for his thievery again. There is only one entrance to this area, called `root`.
Besides the `root`, each house has one and only one parent house. After a tour, the smart thief realized that all houses ... | dolphin |
Please write the following solution using F#:
Given a collection of numbers, `nums`, that might contain duplicates, return _all possible unique permutations **in any order**._
**Example 1:**
**Input:** nums = \[1,1,2\]
**Output:**
\[\[1,1,2\],
\[1,2,1\],
\[2,1,1\]\]
**Example 2:**
**Input:** nums = \[1,2,3\]
**Ou... | dolphin |
Please explain the following problem in detail and provide code in Perl:
You are given integers `height` and `width` which specify the dimensions of a brick wall you are building. You are also given a **0-indexed** array of **unique** integers `bricks`, where the `ith` brick has a height of `1` and a width of `bricks[i... | dolphin |
translate this code from Rust to java:
```rust
fn min_operations(nums: &mut [i32]) -> i32 {
let n = nums.len();
let (mut inc, mut dec) = (0, 0);
for i in 1..n {
if nums[i] < nums[i-1] {
dec += nums[i-1] - nums[i];
} else if nums[i] > nums[i-1] {
inc += nums[i] - nums[... | dolphin |
convert this code to Rust:
```python
def words_typing(sentence, rows, cols):
total_chars = sum(len(word) + 1 for word in sentence)
result = 0
index = 0
for _ in range(rows):
remaining_cols = cols
while True:
word_len = len(sentence[index])
if remaining_cols >= wo... | dolphin |
translate this code from Fortran to Elixir:
```fortran
FUNCTION countHomeworkStudents(startTime, endTime, queryTime)
INTEGER, DIMENSION(:), INTENT(IN) :: startTime, endTime
INTEGER, INTENT(IN) :: queryTime
INTEGER :: count, i
count = 0
DO i = 1, SIZE(startTime)
IF (startTime(i) <= queryTime ... | dolphin |
Please explain the reasoning behind the following solution and provide code in Haskell:
There are several cards **arranged in a row**, and each card has an associated number of points. The points are given in the integer array `cardPoints`.
In one step, you can take one card from the beginning or from the end of the r... | dolphin |
Please explain the following problem in detail and provide code in Rust:
You are given a **0-indexed** integer array `nums`, where `nums[i]` represents the score of the `ith` student. You are also given an integer `k`.
Pick the scores of any `k` students from the array so that the **difference** between the **highest*... | dolphin |
translate this code from Lua to Kotlin:
```lua
function SORTracker()
local locations = {}
local queries = 0
function add(name, score)
local location = {name, score}
local insert_index = 1
while insert_index <= #locations and (locations[insert_index][2] > score or
... | dolphin |
convert this code to Scala:
```python
from collections import defaultdict
def dfs(s1, s2, graph):
if s1 not in graph or s2 not in graph:
return -1.0
if s1 == s2:
return 1.0
for neighbor, weight in graph[s1]:
if neighbor not in visited:
visited.add(neighbor)
... | dolphin |
Please explain the following problem in detail and provide code in Julia:
Given the `root` of a binary tree, return _the zigzag level order traversal of its nodes' values_. (i.e., from left to right, then right to left for the next level and alternate between).
**Example 1:**
**Input:** root = \[3,9,20,null,null,15,7... | dolphin |
Please focus on the efficiency of this problem and provide code in Clojure:
You are playing the following Nim Game with your friend:
* Initially, there is a heap of stones on the table.
* You and your friend will alternate taking turns, and **you go first**.
* On each turn, the person whose turn it is will remov... | dolphin |
Please explain the following problem in detail and provide code in javascript:
Given an integer array `arr`, return `true` if there are three consecutive odd numbers in the array. Otherwise, return `false`.
**Example 1:**
**Input:** arr = \[2,6,4,1\]
**Output:** false
**Explanation:** There are no three consecutive o... | dolphin |
Please focus on the algorithm of this problem and provide code in F#:
Given an integer array `arr`, return _the mean of the remaining integers after removing the smallest `5%` and the largest `5%` of the elements._
Answers within `10-5` of the **actual answer** will be considered accepted.
**Example 1:**
**Input:** ... | dolphin |
Please focus on the efficiency of this problem and provide code in Clojure:
You are given a string `s` and an integer `k`, a `k` **duplicate removal** consists of choosing `k` adjacent and equal letters from `s` and removing them, causing the left and the right side of the deleted substring to concatenate together.
We... | dolphin |
Please explain the following problem in detail and provide code in Fortran:
Design a data structure to store the strings' count with the ability to return the strings with minimum and maximum counts.
Implement the `AllOne` class:
* `AllOne()` Initializes the object of the data structure.
* `inc(String key)` Incre... | dolphin |
Please explain the reasoning behind the following solution and provide code in python:
You are given a string `s` and an integer `k`. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most `k` times.
Return _the length of the longest su... | dolphin |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.