instruction_seed stringlengths 29 40.5k | source stringclasses 6
values |
|---|---|
Please write the following solution using Fortran:
Given an input string `s` and a pattern `p`, implement regular expression matching with support for `'.'` and `'*'` where:
* `'.'` Matches any single character.
* `'*'` Matches zero or more of the preceding element.
The matching should cover the **entire** in... | dolphin |
Please explain the following problem in detail and provide code in Elixir:
The chess knight has a **unique movement**, it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an **L**). The possible movements of chess knight a... | dolphin |
translate this code from Haskell to c++:
```haskell
data TreeNode = TreeNode { val :: Int, left :: Maybe TreeNode, right :: Maybe TreeNode }
recentCounter :: IO ()
recentCounter = do
let rc = newRecentCounter
print $ ping rc 1 -- expected output: 1
print $ ping rc 100 -- expected output: 2
print $ ping... | dolphin |
Please explain the reasoning behind the following solution and provide code in Rust:
Given a string of English letters `s`, return _the **greatest** English letter which occurs as **both** a lowercase and uppercase letter in_ `s`. The returned letter should be in **uppercase**. If no such letter exists, return _an empt... | dolphin |
Please write the following solution using R:
An undirected graph of `n` nodes is defined by `edgeList`, where `edgeList[i] = [ui, vi, disi]` denotes an edge between nodes `ui` and `vi` with distance `disi`. Note that there may be **multiple** edges between two nodes, and the graph may not be connected.
Implement the `... | dolphin |
Please explain the following problem in detail and provide code in Scheme:
You are given an integer array `score` of size `n`, where `score[i]` is the score of the `ith` athlete in a competition. All the scores are guaranteed to be **unique**.
The athletes are **placed** based on their scores, where the `1st` place at... | dolphin |
Please focus on the functionality of this problem and provide code in Objective-C:
Given the availability time slots arrays `slots1` and `slots2` of two people and a meeting duration `duration`, return the **earliest time slot** that works for both of them and is of duration `duration`.
If there is no common time slot... | dolphin |
Please explain the reasoning behind the following solution and provide code in Mojo:
Given a `m * n` matrix `seats` that represent seats distributions in a classroom. If a seat is broken, it is denoted by `'#'` character otherwise it is denoted by a `'.'` character.
Students can see the answers of those sitting next t... | dolphin |
Please explain the reasoning behind the following solution and provide code in Ruby:
You are given **two identical** eggs and you have access to a building with `n` floors labeled from `1` to `n`.
You know that there exists a floor `f` where `0 <= f <= n` such that any egg dropped at a floor **higher** than `f` will *... | dolphin |
Please write the following solution using Scala:
You are given a **0-indexed** integer array `nums` of length `n`.
`nums` contains a **valid split** at index `i` if the following are true:
* The sum of the first `i + 1` elements is **greater than or equal to** the sum of the last `n - i - 1` elements.
* There is ... | dolphin |
Please focus on the functionality of this problem and provide code in R:
You are given a **0-indexed** integer array `nums` consisting of `3 * n` elements.
You are allowed to remove any **subsequence** of elements of size **exactly** `n` from `nums`. The remaining `2 * n` elements will be divided into two **equal** pa... | dolphin |
convert this code from Groovy to Object Pascal:
```groovy
def maximumGap(nums) {
if (nums.size() < 2) {
return 0
}
def min_val = nums.min()
def max_val = nums.max()
def length = nums.size()
def bucket_size = Math.max(1, (max_val - min_val) / (length - 1))
def bucket_num = (max_val -... | dolphin |
port this code to R:
```php
function min_keypresses(string $s): int {
$keypresses = array_map(function($i) { return ($i % 9) + 1; }, range(0, 25));
$result = 0;
for ($i = 0; $i < strlen($s); $i++) {
$result += $keypresses[ord($s[$i]) - ord('a')];
}
return $result;
}
``` | dolphin |
Please explain the following problem in detail and provide code in Haskell:
Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another ... | dolphin |
Please focus on the efficiency of this problem and provide code in Object Pascal:
Given an integer array `nums` of length `n`, return `true` if there is a triplet `(i, j, k)` which satisfies the following conditions:
* `0 < i, i + 1 < j, j + 1 < k < n - 1`
* The sum of subarrays `(0, i - 1)`, `(i + 1, j - 1)`, `(j... | dolphin |
Please write the following solution using java:
There is a function `signFunc(x)` that returns:
* `1` if `x` is positive.
* `-1` if `x` is negative.
* `0` if `x` is equal to `0`.
You are given an integer array `nums`. Let `product` be the product of all values in the array `nums`.
Return `signFunc(product)`.
... | dolphin |
Please focus on the algorithm of this problem and provide code in Scheme:
You are given a string `allowed` consisting of **distinct** characters and an array of strings `words`. A string is **consistent** if all characters in the string appear in the string `allowed`.
Return _the number of **consistent** strings in th... | dolphin |
convert this code to javascript:
```lisp
(defun prefix-score-sum (words)
(let ((result (make-list (length words) :initial-element 0))
(prefix-count (make-hash-table :test 'equal)))
(dolist (word words)
(let ((prefix ""))
(dolist (c (coerce word 'list))
(setf prefix (concatenate 'st... | dolphin |
Please focus on the functionality of this problem and provide code in Swift:
Given an integer `num`, return _the number of digits in `num` that divide_ `num`.
An integer `val` divides `nums` if `nums % val == 0`.
**Example 1:**
**Input:** num = 7
**Output:** 1
**Explanation:** 7 divides itself, hence the answer is 1... | dolphin |
Please explain the reasoning behind the following solution and provide code in Object Pascal:
Given an integer array `nums` where the elements are sorted in **ascending order**, convert _it to a_ **_height-balanced_** _binary search tree_.
**Example 1:**
**Input:** nums = \[-10,-3,0,5,9\]
**Output:** \[0,-3,9,-10,nul... | dolphin |
Please focus on the functionality of this problem and provide code in c++:
We will use a file-sharing system to share a very large file which consists of `m` small **chunks** with IDs from `1` to `m`.
When users join the system, the system should assign **a unique** ID to them. The unique ID should be used **once** fo... | dolphin |
convert this code to TypeScript:
```Swift
class FrontMiddleBackQueue {
var first: [Int]
var second: [Int]
init() {
first = []
second = []
}
func pushFront(_ val: Int) {
first.insert(val, at: 0)
if first.count > second.count + 1 {
second.insert(first.remo... | dolphin |
convert this code from Kotlin to Mojo:
```kotlin
fun minStopCosts(regular: IntArray, express: IntArray, expressCost: Int): IntArray {
val n = regular.size
val costs = IntArray(n)
var regularSum = 0
var expressSum = expressCost
for (i in 0 until n) {
regularSum += regular[i]
expressS... | dolphin |
Please explain the following problem in detail and provide code in python:
You are given an integer array `nums` and an integer `k`.
In one operation, you can pick two numbers from the array whose sum equals `k` and remove them from the array.
Return _the maximum number of operations you can perform on the array_.
*... | dolphin |
Please focus on the algorithm of this problem and provide code in c++:
You are given two **0-indexed** integer arrays `nums1` and `nums2` of equal length `n` and a positive integer `k`. You must choose a **subsequence** of indices from `nums1` of length `k`.
For chosen indices `i0`, `i1`, ..., `ik - 1`, your **score**... | dolphin |
Please explain the following problem in detail and provide code in ANSI C:
A `width x height` grid is on an XY-plane with the **bottom-left** cell at `(0, 0)` and the **top-right** cell at `(width - 1, height - 1)`. The grid is aligned with the four cardinal directions ( `"North "`, `"East "`, `"South "`, and `"West "`... | dolphin |
Please write the following solution using Fortran:
You are given a string `s` consisting **only** of letters `'a'` and `'b'`. In a single step you can remove one **palindromic subsequence** from `s`.
Return _the **minimum** number of steps to make the given string empty_.
A string is a **subsequence** of a given stri... | dolphin |
Please write the following solution using ANSI C:
You are given a string `s` consisting of the characters `'a'`, `'b'`, and `'c'` and a non-negative integer `k`. Each minute, you may take either the **leftmost** character of `s`, or the **rightmost** character of `s`.
Return _the **minimum** number of minutes needed f... | dolphin |
Please focus on the efficiency of this problem and provide code in javascript:
Given a binary array `nums` and an integer `k`, return _the maximum number of consecutive_ `1`_'s in the array if you can flip at most_ `k` `0`'s.
**Example 1:**
**Input:** nums = \[1,1,1,0,0,0,1,1,1,1,0\], k = 2
**Output:** 6
**Explanatio... | dolphin |
port this code to TypeScript:
```javascript
function replaceElements(arr) {
let n = arr.length;
let maxElement = -1;
for (let i = n - 1; i >= 0; i--) {
let temp = arr[i];
arr[i] = maxElement;
maxElement = Math.max(maxElement, temp);
}
return arr;
}
```
| dolphin |
Please write the following solution using Scala:
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 perfec... | dolphin |
Please explain the following problem in detail and provide code in TypeScript:
There is an **undirected** graph with `n` nodes numbered from `0` to `n - 1` (**inclusive**). You are given a **0-indexed** integer array `values` where `values[i]` is the **value** of the `ith` node. You are also given a **0-indexed** 2D in... | dolphin |
Please focus on the functionality of this problem and provide code in Scheme:
The **abbreviation** of a word is a concatenation of its first letter, the number of characters between the first and last letter, and its last letter. If a word has only two characters, then it is an **abbreviation** of itself.
For example:... | dolphin |
translate this code to Groovy:
```R
maxPoints <- function(grid, queries) {
m <- nrow(grid)
n <- ncol(grid)
dx <- c(-1, 0, 1, 0)
dy <- c(0, 1, 0, -1)
dfs <- function(x, y, q, visited) {
if (x >= 0 && x < m && y >= 0 && y < n && grid[x+1,y+1] < q && !(paste(x, y) %in% visited)) {
visited <- c(visited... | dolphin |
convert this code from TypeScript to Ruby:
```typescript
function letterCombinations(digits: string): string[] {
if (!digits) return [];
const phone: string[] = ["abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"];
let result: string[] = [""];
for (let i = 0; i < digits.length; i++) {
... | dolphin |
convert this code from Go to R:
```go
func validMountainArray(arr []int) bool {
if len(arr) < 3 {
return false
}
i := 1
for i < len(arr) && arr[i] > arr[i-1] {
i++
}
if i == 1 || i == len(arr) {
return false
}
for i < len(arr) && arr[i] < arr[i-1] {
i++... | dolphin |
Please explain the reasoning behind the following solution and provide code in Fortran:
You are given a string `s` consisting of digits from `1` to `9` and an integer `k`.
A partition of a string `s` is called **good** if:
* Each digit of `s` is part of **exactly** one substring.
* The value of each substring is ... | dolphin |
translate this code from Scala to javascript:
```scala
def floodFill(image: Array[Array[Int]], sr: Int, sc: Int, newColor: Int): Array[Array[Int]] = {
val startColor = image(sr)(sc)
def fill(sr: Int, sc: Int): Unit = {
if (sr < 0 || sr >= image.length || sc < 0 || sc >= image(0).length || image(sr)(sc) != start... | dolphin |
port this code from Julia to Haskell:
```julia
function countSmallerFrequencies(words::Array{String,1}, queries::Array{String,1})
freqWords = [count(word, min(word)) for word in words]
ans = []
for query in queries
freqQuery = count(query, min(query))
count = 0
for freqWord in f... | dolphin |
Please focus on the efficiency of this problem and provide code in javascript:
There are `buckets` buckets of liquid, where **exactly one** of the buckets is poisonous. To figure out which one is poisonous, you feed some number of (poor) pigs the liquid to see whether they will die or not. Unfortunately, you only have ... | dolphin |
Please explain the following problem in detail and provide code in python:
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 repres... | dolphin |
port this code to Dart:
```typescript
function makeBurgers(tomatoSlices: number, cheeseSlices: number): number[] {
const jumboBurgerTomatoes = 4;
const smallBurgerTomatoes = 2;
const jumboBurgerCheese = 1;
const smallBurgerCheese = 1;
const totalJumboBurgers = (tomatoSlices - (2 * cheeseSlices)) / ... | dolphin |
port this code to c++:
```mojo
sub read4($buf4 is rw --> Int) {
# implementation of read4 method
}
sub read($buf is rw, $n is Int --> Int) {
my $total_read = 0;
my @buf4 = ('') x 4;
while $total_read < $n {
my $read4_count = read4(@buf4);
for ^$read4_count -> $i {
if $total... | dolphin |
convert this code to Dart:
```mojo
sub longest_beautiful_substring(word) {
if len(word) < 5 {
return 0
}
var max_length = 1
var current_length = 1
var current_vowels = word[0]
for i in 1..len(word)-1 {
if word[i] >= current_vowels[-1] and word[i] not_in current_vowels {
... | dolphin |
port this code from Lisp to C#:
```lisp
(defun closest-distance (s c)
(let ((n (length s))
(answer (make-array n :initial-element most-positive-fixnum))
(last -most-positive-fixnum))
(dotimes (i n)
(when (char= (char s i) c)
(setf last i))
(setf (aref answer i) (min (aref answe... | dolphin |
Please explain the reasoning behind the following solution and provide code in c++:
Given a list `paths` of directory info, including the directory path, and all the files with contents in this directory, return _all the duplicate files in the file system in terms of their paths_. You may return the answer in **any ord... | dolphin |
Please write the following solution using Julia:
Given an array of integers, return the maximum sum for a **non-empty** subarray (contiguous elements) with at most one element deletion. In other words, you want to choose a subarray and optionally delete one element from it so that there is still at least one element le... | dolphin |
convert this code to Dart:
```fsharp
let missing_rolls rolls mean n =
let roll_sum = List.sum rolls
let total_sum = mean * (n + List.length rolls)
let missing_sum = total_sum - roll_sum
if missing_sum <= 0 || missing_sum > 6 * n || n > missing_sum then
[]
else
let missing_rolls, rema... | dolphin |
translate this code from TypeScript to Dart:
```typescript
function maxPrizes(prizePositions: number[], k: number): number {
const n = prizePositions.length;
let ans = 0;
for (let i = 0; i < n; i++) {
const leftSegmentEnd = prizePositions[i] + k;
const rightSegmentStart = bisectRight(prizePo... | dolphin |
port this code from javascript to F#:
```javascript
function longestObstacleCourse(obstacles) {
const ans = new Array(obstacles.length), active = [];
for (let i = 0; i < obstacles.length; i++) {
const idx = upperBound(active, obstacles[i]);
ans[i] = idx + 1;
if (idx === active.length) {
... | dolphin |
Please explain the reasoning behind the following solution and provide code in ANSI C:
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 a... | dolphin |
Please write the following solution using Object Pascal:
A game on an **undirected** graph is played by two players, Mouse and Cat, who alternate turns.
The graph is given as follows: `graph[a]` is a list of all nodes `b` such that `ab` is an edge of the graph.
The mouse starts at node `1` and goes first, the cat sta... | dolphin |
Please explain the reasoning behind the following solution and provide code in C#:
Given two strings `s` and `t`, return `true` if they are both one edit distance apart, otherwise return `false`.
A string `s` is said to be one distance apart from a string `t` if you can:
* Insert **exactly one** character into `s` ... | dolphin |
port this code from Elixir to Dart:
```elixir
defmodule Solution do
def leftBoundary(nil, _), do: []
def leftBoundary(%{left: left, right: right} = node, boundary) do
if left || right do
[node.val | leftBoundary(left || right, boundary)]
else
leftBoundary(left, boundary)
... | dolphin |
Please focus on the efficiency of this problem and provide code in Object Pascal:
In combinatorial mathematics, a **derangement** is a permutation of the elements of a set, such that no element appears in its original position.
You are given an integer `n`. There is originally an array consisting of `n` integers from ... | dolphin |
Please focus on the functionality of this problem and provide code in Visual Basic .NET:
Serialization is converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another co... | dolphin |
Please explain the following problem in detail and provide code in Go:
Given an array `nums` of size `n`, return _the majority element_.
The majority element is the element that appears more than `⌊n / 2⌋` times. You may assume that the majority element always exists in the array.
**Example 1:**
**Input:** nums = \[... | dolphin |
translate this code from Haskell to java:
```haskell
import Data.List (foldl')
import Data.Maybe (fromMaybe)
minSubarray :: [Int] -> Int -> Int
minSubarray nums p
| need == 0 = 0
| res == n = -1
| otherwise = res
where
n = length nums
need = sum nums `mod` p
lastSeen = foldl' (\... | dolphin |
Please explain the reasoning behind the following solution and provide code in ANSI C:
You are given three integers `n`, `m` and `k`. Consider the following algorithm to find the maximum element of an array of positive integers:
You should build the array arr which has the following properties:
* `arr` has exactly ... | dolphin |
Please focus on the algorithm of this problem and provide code in F#:
You are given an integer array `nums` and two integers `limit` and `goal`. The array `nums` has an interesting property that `abs(nums[i]) <= limit`.
Return _the minimum number of elements you need to add to make the sum of the array equal to_ `goal... | dolphin |
port this code from F# to javascript:
```fsharp
let shortestPathLength(graph: int[][]) =
let n = graph.Length
let q = Queue()
let mutable steps = -1
let visited = Dictionary([for i in 0..n-1 -> i, Set()])
for i in 0..n-1 do
q.Enqueue((i, 1 <<< i))
while q.Count > 0 do
s... | dolphin |
Please focus on the efficiency of this problem and provide code in Rust:
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 manager of th... | dolphin |
Please explain the following problem in detail and provide code in python:
Design a hit counter which counts the number of hits received in the past `5` minutes (i.e., the past `300` seconds).
Your system should accept a `timestamp` parameter (**in seconds** granularity), and you may assume that calls are being made t... | dolphin |
port this code from Visual Basic .NET to Lisp:
```vb.net
Public Class TreeNode
Public Property val As Integer
Public Property left As TreeNode
Public Property right As TreeNode
Public Sub New(val As Integer, Optional left As TreeNode = Nothing, Optional right As TreeNode = Nothing)
Me.val = val... | dolphin |
Please focus on the efficiency of this problem and provide code in c++:
There are `n` friends that are playing a game. The friends are sitting in a circle and are numbered from `1` to `n` in **clockwise order**. More formally, moving clockwise from the `ith` friend brings you to the `(i+1)th` friend for `1 <= i < n`, a... | dolphin |
Please explain the following problem in detail and provide code in Groovy:
A binary string is monotone increasing if it consists of some number of `0`'s (possibly none), followed by some number of `1`'s (also possibly none).
You are given a binary string `s`. You can flip `s[i]` changing it from `0` to `1` or from `1`... | dolphin |
convert this code from Julia to Scheme:
```julia
function numDecodings(s::AbstractString, k::Int)::Int
n = length(s)
dp = zeros(Int, n+1)
dp[n+1] = 1
MOD = 10^9 + 7
for i = n-1:-1:1
num = 0
for j = i:n
num = num * 10 + parse(Int, s[j:j])
if num >= 1 && nu... | dolphin |
Please explain the reasoning behind the following solution and provide code in Erlang:
Two players play a turn based game on a binary tree. We are given the `root` of this binary tree, and the number of nodes `n` in the tree. `n` is odd, and each node has a distinct value from `1` to `n`.
Initially, the first player n... | dolphin |
Please explain the reasoning behind the following solution and provide code in python:
You are given an undirected graph defined by an integer `n`, the number of nodes, and a 2D integer array `edges`, the edges in the graph, where `edges[i] = [ui, vi]` indicates that there is an **undirected** edge between `ui` and `vi... | dolphin |
Please explain the following problem in detail and provide code in Perl:
There are some prizes on the **X-axis**. You are given an integer array `prizePositions` that is **sorted in non-decreasing order**, where `prizePositions[i]` is the position of the `ith` prize. There could be different prizes at the same position... | dolphin |
Please explain the following problem in detail and provide code in Julia:
An array is **squareful** if the sum of every pair of adjacent elements is a **perfect square**.
Given an integer array nums, return _the number of permutations of_ `nums` _that are **squareful**_.
Two permutations `perm1` and `perm2` are diffe... | dolphin |
Please write the following solution using Objective-C:
In a binary tree, a **lonely** node is a node that is the only child of its parent node. The root of the tree is not lonely because it does not have a parent node.
Given the `root` of a binary tree, return _an array containing the values of all lonely nodes_ in th... | dolphin |
port this code to Mojo:
```haskell
isWhiteSquare :: String -> Bool
isWhiteSquare coordinates = even (column + row)
where
column = ord (head coordinates) - ord 'a' + 1
row = digitToInt (last coordinates)
``` | dolphin |
Please explain the following problem in detail and provide code in Go:
A maze consists of `n` rooms numbered from `1` to `n`, and some rooms are connected by corridors. You are given a 2D integer array `corridors` where `corridors[i] = [room1i, room2i]` indicates that there is a corridor connecting `room1i` and `room2i... | dolphin |
Please explain the reasoning behind the following solution and provide code in F#:
In a special ranking system, each voter gives a rank from highest to lowest to all teams participating in the competition.
The ordering of teams is decided by who received the most position-one votes. If two or more teams tie in the fir... | dolphin |
Please explain the following problem in detail and provide code in Fortran:
Given a **0-indexed** string `word` and a character `ch`, **reverse** the segment of `word` that starts at index `0` and ends at the index of the **first occurrence** of `ch` (**inclusive**). If the character `ch` does not exist in `word`, do n... | dolphin |
Please focus on the efficiency of this problem and provide code in Haskell:
Given an array of integers `temperatures` represents the daily temperatures, return _an array_ `answer` _such that_ `answer[i]` _is the number of days you have to wait after the_ `ith` _day to get a warmer temperature_. If there is no future da... | dolphin |
Please explain the reasoning behind the following solution and provide code in javascript:
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are **arranged in a circle.** That means the first house is the neighbor of the last ... | dolphin |
Please explain the reasoning behind the following solution and provide code in Go:
Given the `root` of a binary tree, return _the inorder traversal of its nodes' values_.
**Example 1:**
**Input:** root = \[1,null,2,3\]
**Output:** \[1,3,2\]
**Example 2:**
**Input:** root = \[\]
**Output:** \[\]
**Example 3:**
**I... | dolphin |
Please explain the following problem in detail and provide code in javascript:
You are given a **0-indexed** array of string `words` and two integers `left` and `right`.
A string is called a **vowel string** if it starts with a vowel character and ends with a vowel character where vowel characters are `'a'`, `'e'`, `'... | dolphin |
port this code to Objective-C:
```elixir
defmodule Solution do
def max_equal_freq(nums) do
count = %{}
freq = %{}
max_len = 0
max_freq = 0
for {i, num} <- Enum.with_index(nums) do
count[num] = count[num] || 0
count[num] = count[num] + 1
freq[count[num] - 1] = freq[count[nu... | dolphin |
Please explain the reasoning behind the following solution and provide code in Groovy:
We can scramble a string s to get a string t using the following algorithm:
1. If the length of the string is 1, stop.
2. If the length of the string is > 1, do the following:
* Split the string into two non-empty substrings... | dolphin |
Please write the following solution using F#:
You are given two positive integers `left` and `right` with `left <= right`. Calculate the **product** of all integers in the **inclusive** range `[left, right]`.
Since the product may be very large, you will **abbreviate** it following these steps:
1. Count all **traili... | dolphin |
convert this code to Lua:
```java
import java.util.ArrayList;
import java.util.List;
public class Solution {
public boolean possibleBipartition(int n, int[][] dislikes) {
int[] groups = new int[n + 1];
List<List<Integer>> dislikeList = new ArrayList<>();
for (int i = 0; i <= n; i++) {
... | dolphin |
port this code to Ruby:
```scheme
(define (max-books books)
(define (min a b) (if (< a b) a b))
(define (max a b) (if (> a b) a b))
(let ((n (length books))
(max-books 0))
(do ((l 0 (add1 l)))
((>= l n) max-books)
(let ((r (add1 l))
(books-taken (list-ref books l))
... | dolphin |
Please focus on the functionality of this problem and provide code in Ruby:
Given the `root` of a binary search tree and the lowest and highest boundaries as `low` and `high`, trim the tree so that all its elements lies in `[low, high]`. Trimming the tree should **not** change the relative structure of the elements tha... | dolphin |
Please write the following solution using Kotlin:
Given `n` points on a 2D plane, find if there is such a line parallel to the y-axis that reflects the given points symmetrically.
In other words, answer whether or not if there exists a line that after reflecting all points over the given line, the original points' set... | dolphin |
Please focus on the efficiency of this problem and provide code in F#:
You are given two integers `m` and `n`, which represent the dimensions of a matrix.
You are also given the `head` of a linked list of integers.
Generate an `m x n` matrix that contains the integers in the linked list presented in **spiral** order ... | dolphin |
translate this code to Scheme:
```rust
fn min_distance(word: &str) -> i32 {
let mut dp = vec![vec![0; 26]; 26];
for i in 0..26 {
for j in 0..26 {
if i != j {
dp[i][j] = std::i32::MAX;
}
}
}
for k in 0..26 {
for i in 0..26 {
for ... | dolphin |
Please focus on the efficiency of this problem and provide code in Elixir:
Given the `root` of a binary tree and two integers `val` and `depth`, add a row of nodes with value `val` at the given depth `depth`.
Note that the `root` node is at depth `1`.
The adding rule is:
* Given the integer `depth`, for each not n... | dolphin |
Please focus on the efficiency of this problem and provide code in Erlang:
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 considere... | dolphin |
Please explain the following problem in detail and provide code in python:
Given an integer array `arr` and an integer `k`, modify the array by repeating it `k` times.
For example, if `arr = [1, 2]` and `k = 3` then the modified array will be `[1, 2, 1, 2, 1, 2]`.
Return the maximum sub-array sum in the modified arra... | dolphin |
Please explain the following problem in detail and provide code in Julia:
You are given an `m x n` `grid`. Each cell of `grid` represents a street. The street of `grid[i][j]` can be:
* `1` which means a street connecting the left cell and the right cell.
* `2` which means a street connecting the upper cell and the... | dolphin |
Please explain the reasoning behind the following solution and provide code in Kotlin:
You are given an array of strings `names`, and an array `heights` that consists of **distinct** positive integers. Both arrays are of length `n`.
For each index `i`, `names[i]` and `heights[i]` denote the name and height of the `ith... | dolphin |
Please explain the reasoning behind the following solution and provide code in Perl:
There is a programming language with only **four** operations and **one** variable `X`:
* `++X` and `X++` **increments** the value of the variable `X` by `1`.
* `--X` and `X--` **decrements** the value of the variable `X` by `1`.
... | dolphin |
convert this code from Swift to F#:
```swift
func compress(_ chars: inout [Character]) -> Int {
var index = 0
var i = 0
while i < chars.count {
var count = 1
while i + count < chars.count && chars[i] == chars[i + count] {
count += 1
}
chars[index] = ... | dolphin |
Please write the following solution using Object Pascal:
A Binary Matrix is a matrix in which all the elements are either **0** or **1**.
Given `quadTree1` and `quadTree2`. `quadTree1` represents a `n * n` binary matrix and `quadTree2` represents another `n * n` binary matrix.
Return _a Quad-Tree_ representing the `n... | dolphin |
Please focus on the functionality of this problem and provide code in F#:
Given an integer array `nums` and two integers `left` and `right`, return _the number of contiguous non-empty **subarrays** such that the value of the maximum array element in that subarray is in the range_ `[left, right]`.
The test cases are ge... | dolphin |
Please write the following solution using C#:
Given an array `arr` of positive integers, consider all binary trees such that:
* Each node has either `0` or `2` children;
* The values of `arr` correspond to the values of each **leaf** in an in-order traversal of the tree.
* The value of each non-leaf node is equa... | dolphin |
port this code from Object Pascal to Scheme:
```pascal
type
SmallestInfiniteSet = class
private
available: set of 1..1000;
counter: Integer;
public
constructor Create;
function popSmallest: Integer;
procedure addBack(num: Integer);
end;
constructor SmallestInfiniteSet.Create;
var
i: Integ... | dolphin |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.