instruction_seed stringlengths 29 40.5k | source stringclasses 6
values |
|---|---|
translate this code from R to Go:
```R
numTrees <- function(n) {
dp <- rep(0, n+1)
dp[0] <- 1
dp[1] <- 1
for (i in 2:n) {
for (j in 0:(i-1)) {
dp[i] <- (dp[i] + dp[j] * dp[i-1-j]) %% (10^9 + 7)
}
}
return(dp[n])
}
``` | dolphin |
Please focus on the algorithm of this problem and provide code in Erlang:
We stack glasses in a pyramid, where the **first** row has `1` glass, the **second** row has `2` glasses, and so on until the 100th row. Each glass holds one cup of champagne.
Then, some champagne is poured into the first glass at the top. When ... | dolphin |
Please focus on the functionality of this problem and provide code in Lua:
There are two mice and `n` different types of cheese, each type of cheese should be eaten by exactly one mouse.
A point of the cheese with index `i` (**0-indexed**) is:
* `reward1[i]` if the first mouse eats it.
* `reward2[i]` if the secon... | dolphin |
convert this code from Erlang to Elixir:
```erlang
-module(array_form).
-export([array_form/2]).
array_form(Nums, K) ->
Primes = fun(N) -> primes(N) end,
Dfs = fun(Node, Visited, Graph) ->
case lists:member(Node, Visited) of
true -> 0;
false ->
... | dolphin |
Please focus on the algorithm of this problem and provide code in Scheme:
Given a string `s`, rearrange the characters of `s` so that any two adjacent characters are not the same.
Return _any possible rearrangement of_ `s` _or return_ `" "` _if not possible_.
**Example 1:**
**Input:** s = "aab"
**Output:** "aba"
**... | dolphin |
port this code to Lua:
```cpp
#include <vector>
#include <queue>
using namespace std;
const int MODULO = 1000000007;
int countPaths(int n, vector<vector<int>>& roads) {
vector<vector<pair<int, int>>> adj_list(n);
for (auto& road : roads) {
adj_list[road[0]].emplace_back(road[1], road[2]);
... | dolphin |
convert this code to Fortran:
```clojure
(defn find-node [root value]
(if (or (nil? root) (= (:val root) value))
root
(let [left (find-node (:left root) value)
right (find-node (:right root) value)]
(if left left right))))
(defn shortest-path [root start-value dest-value]
(let [dest (find-n... | dolphin |
Please focus on the functionality of this problem and provide code in ANSI C:
Given an integer array nums, return _the number of **AND triples**_.
An **AND triple** is a triple of indices `(i, j, k)` such that:
* `0 <= i < nums.length`
* `0 <= j < nums.length`
* `0 <= k < nums.length`
* `nums[i] & nums[j] & n... | dolphin |
Please explain the following problem in detail and provide code in Go:
You are given a string `time` in the form of `hh:mm`, where some of the digits in the string are hidden (represented by `?`).
The valid times are those inclusively between `00:00` and `23:59`.
Return _the latest valid time you can get from_ `time`... | dolphin |
Please explain the following problem in detail and provide code in F#:
Given two integers representing the `numerator` and `denominator` of a fraction, return _the fraction in string format_.
If the fractional part is repeating, enclose the repeating part in parentheses.
If multiple answers are possible, return **any... | dolphin |
Please write the following solution using TypeScript:
Given the `root` of a binary tree, calculate the **vertical order traversal** of the binary tree.
For each node at position `(row, col)`, its left and right children will be at positions `(row + 1, col - 1)` and `(row + 1, col + 1)` respectively. The root of the tr... | dolphin |
Please focus on the functionality of this problem and provide code in ANSI C:
A city's **skyline** is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Given the locations and heights of all the buildings, return _the **skyline** formed by these buildings collecti... | dolphin |
translate this code to PHP:
```scala
object Solution {
def isScramble(s1: String, s2: String): Boolean = {
if (s1 == s2) return true
if (s1.length != s2.length || s1.sorted != s2.sorted) return false
for (i <- 1 until s1.length) {
if ((isScramble(s1.substring(0, i), s2.substring... | dolphin |
Please explain the following problem in detail and provide code in Perl:
For two strings `s` and `t`, we say "`t` divides `s` " if and only if `s = t + ... + t` (i.e., `t` is concatenated with itself one or more times).
Given two strings `str1` and `str2`, return _the largest string_ `x` _such that_ `x` _divides both_... | dolphin |
Please write the following solution using Object Pascal:
An **n-bit gray code sequence** is a sequence of `2n` integers where:
* Every integer is in the **inclusive** range `[0, 2n - 1]`,
* The first integer is `0`,
* An integer appears **no more than once** in the sequence,
* The binary representation of ever... | dolphin |
translate this code to C#:
```scala
def canEqualFrequency(word: String): Boolean = {
val freq = word.groupBy(identity).mapValues(_.length)
val countFreq = freq.groupBy(_._2).mapValues(_.size)
countFreq.size == 2 && {
val (a, acount) = countFreq.head
val (b, bcount) = countFreq.last
(acount == 1 && (a ... | dolphin |
translate this code from Rust to Clojure:
```rust
struct MyCalendar {
calendar: Vec<i32>,
}
impl MyCalendar {
fn new() -> Self {
MyCalendar { calendar: vec![] }
}
fn book(&mut self, start: i32, end: i32) -> bool {
let i = self
.calendar
.binary_search(&start)
... | dolphin |
Please explain the following problem in detail and provide code in Clojure:
You are given an array of non-overlapping axis-aligned rectangles `rects` where `rects[i] = [ai, bi, xi, yi]` indicates that `(ai, bi)` is the bottom-left corner point of the `ith` rectangle and `(xi, yi)` is the top-right corner point of the `... | dolphin |
translate this code from javascript to Ruby:
```javascript
function reformat(s) {
const letters = [], digits = [];
for (const c of s) {
if (c.charCodeAt(0) > 57) letters.push(c);
else digits.push(c);
}
if (Math.abs(letters.length - digits.length) > 1) return "";
let result = "";
... | dolphin |
Please explain the reasoning behind the following solution and provide code in Ruby:
You are given an integer array `nums`. You can choose **exactly one** index (**0-indexed**) and remove the element. Notice that the index of the elements may change after the removal.
For example, if `nums = [6,1,7,4,1]`:
* Choosin... | dolphin |
translate this code to TypeScript:
```scala
def splitMessage(message: String, limit: Int): Array[String] = {
val n = message.length
val a = (limit - 3) * (n / (limit - 3)) - n
val b = n / (limit - 3)
if ((n + b + a) % (limit - 2) != 0) return Array[String]()
val num_parts = (n + b + a) / (limit - 2)
var res... | dolphin |
Please explain the following problem in detail and provide code in Elixir:
You are in a city that consists of `n` intersections numbered from `0` to `n - 1` with **bi-directional** roads between some intersections. The inputs are generated such that you can reach any intersection from any other intersection and that th... | dolphin |
Please explain the reasoning behind the following solution and provide code in Rust:
Given an integer `n`, return `true` _if_ `n` _has **exactly three positive divisors**. Otherwise, return_ `false`.
An integer `m` is a **divisor** of `n` if there exists an integer `k` such that `n = k * m`.
**Example 1:**
**Input:*... | dolphin |
Please focus on the efficiency of this problem and provide code in C#:
You are given a directed graph with `n` nodes labeled from `0` to `n - 1`, where each node has **exactly one** outgoing edge.
The graph is represented by a given **0-indexed** integer array `edges` of length `n`, where `edges[i]` indicates that the... | dolphin |
Please focus on the algorithm of this problem and provide code in Groovy:
Given an `m x n` `picture` consisting of black `'B'` and white `'W'` pixels, return _the number of **black** lonely pixels_.
A black lonely pixel is a character `'B'` that located at a specific position where the same row and same column don't h... | dolphin |
Please explain the following problem in detail and provide code in Scala:
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 **scor... | dolphin |
Please explain the reasoning behind the following solution and provide code in PHP:
You are given an array `nums` consisting of positive integers.
You are also given an integer array `queries` of size `m`. For the `ith` query, you want to make all of the elements of `nums` equal to `queries[i]`. You can perform the fo... | dolphin |
convert this code to Mojo:
```php
function fourSumCount($nums1, $nums2, $nums3, $nums4) {
$hashMap = array();
$count = 0;
foreach ($nums1 as $i) {
foreach ($nums2 as $j) {
$hashMap[$i + $j] = isset($hashMap[$i + $j]) ? $hashMap[$i + $j] + 1 : 1;
}
}
foreach ($nums3 as $... | dolphin |
Please write the following solution using Erlang:
You are given an integer array `nums` and an integer `x`. In one operation, you can either remove the leftmost or the rightmost element from the array `nums` and subtract its value from `x`. Note that this **modifies** the array for future operations.
Return _the **min... | dolphin |
translate this code from Elixir to Lisp:
```elixir
defmodule Solution do
def add_to_array_form(num, k) do
for i <- :lists.reverse(num), into: {[], _carry} do
{k, new_i} = divrem(i + k, 10)
{new_i, k}
end
|> Enum.reverse()
|> Enum.drop_while(fn i -> i == 0 end)
|> (fn [] -> [0] end).()
... | dolphin |
Please explain the following problem in detail and provide code in Swift:
You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day, and an integer `fee` representing a transaction fee.
Find the maximum profit you can achieve. You may complete as many transactions as you like, bu... | dolphin |
Please explain the reasoning behind the following solution and provide code in python:
Given two [sparse matrices](https://en.wikipedia.org/wiki/Sparse_matrix) `mat1` of size `m x k` and `mat2` of size `k x n`, return the result of `mat1 x mat2`. You may assume that multiplication is always possible.
**Example 1:**
*... | dolphin |
Please explain the reasoning behind the following solution and provide code in Go:
Given a **0-indexed** `n x n` integer matrix `grid`, _return the number of pairs_ `(ri, cj)` _such that row_ `ri` _and column_ `cj` _are equal_.
A row and column pair is considered equal if they contain the same elements in the same ord... | dolphin |
Please explain the reasoning behind the following solution and provide code in Haskell:
There are `n` different online courses numbered from `1` to `n`. You are given an array `courses` where `courses[i] = [durationi, lastDayi]` indicate that the `ith` course should be taken **continuously** for `durationi` days and mu... | dolphin |
Please write the following solution using Object Pascal:
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 names a value `x` with `1 <= x ... | dolphin |
Please focus on the algorithm of this problem and provide code in Dart:
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 focus on the efficiency of this problem and provide code in c++:
Given a string `s`, return _the number of **unique palindromes of length three** that are a **subsequence** of_ `s`.
Note that even if there are multiple ways to obtain the same subsequence, it is still only counted **once**.
A **palindrome** is ... | dolphin |
Please write the following solution using Erlang:
Given an integer `num`, return _the number of steps to reduce it to zero_.
In one step, if the current number is even, you have to divide it by `2`, otherwise, you have to subtract `1` from it.
**Example 1:**
**Input:** num = 14
**Output:** 6
**Explanation:**
Step 1... | dolphin |
Please explain the reasoning behind the following solution and provide code in Dart:
You are given an integer `n` denoting the number of cities in a country. The cities are numbered from `0` to `n - 1`.
You are also given a 2D integer array `roads` where `roads[i] = [ai, bi]` denotes that there exists a **bidirectiona... | dolphin |
Please explain the following problem in detail and provide code in Rust:
Given the roots of two binary search trees, `root1` and `root2`, return `true` if and only if there is a node in the first tree and a node in the second tree whose values sum up to a given integer `target`.
**Example 1:**
**Input:** root1 = \[2,... | dolphin |
Please explain the following problem in detail and provide code in Visual Basic .NET:
Given `n` non-negative integers representing an elevation map where the width of each bar is `1`, compute how much water it can trap after raining.
**Example 1:**
**Input:** height = \[0,1,0,2,1,0,1,3,2,1,2,1\]
**Output:** 6
**Expla... | dolphin |
Please explain the reasoning behind the following solution and provide code in F#:
You are given the `root` of a binary tree and an integer `distance`. A pair of two different **leaf** nodes of a binary tree is said to be good if the length of **the shortest path** between them is less than or equal to `distance`.
Ret... | dolphin |
Please focus on the algorithm of this problem and provide code in Scheme:
You are given a **0-indexed** binary matrix `grid`. In one operation, you can flip any `1` in `grid` to be `0`.
A binary matrix is **well-isolated** if there is no `1` in the matrix that is **4-directionally connected** (i.e., horizontal and ver... | dolphin |
port this code to Scala:
```erlang
-module(pattern).
-export([find_pattern/3]).
find_pattern(Arr, M, K) ->
n = length(Arr),
PatternRepeats = n - M*K + 1,
check_pattern(Arr, M, K, PatternRepeats).
check_pattern(Arr, M, K, PatternRepeats) ->
check_pattern(Arr, M, K, PatternRepeats, 1, 1).
check_patter... | dolphin |
translate this code to c++:
```java
public int[] findClosestDivisors(int num) {
for (int i = (int)Math.sqrt(num + 2); i >= 1; i--) {
if ((num + 1) % i == 0) return new int[]{i, (num + 1) / i};
if ((num + 2) % i == 0) return new int[]{i, (num + 2) / i};
}
return new int[0];
}
```
| dolphin |
translate this code from F# to C#:
```fsharp
let findRedundantDirectedConnection(edges: int[][]) =
let n = edges.Length
let mutable parent = Array.zeroCreate (n + 1)
let mutable candidateA = null
let mutable candidateB = null
for i = 0 to n - 1 do
let u = edges.[i].[0]
let v = edges... | dolphin |
Please explain the following problem in detail and provide code in Perl:
You are given a string `s` and a robot that currently holds an empty string `t`. Apply one of the following operations until `s` and `t` **are both empty**:
* Remove the **first** character of a string `s` and give it to the robot. The robot wi... | dolphin |
Please explain the following problem in detail and provide code in python:
You are given an array of strings `words` (**0-indexed**).
In one operation, pick two **distinct** indices `i` and `j`, where `words[i]` is a non-empty string, and move **any** character from `words[i]` to **any** position in `words[j]`.
Retur... | dolphin |
translate this code from Scala to ANSI C:
```scala
import scala.collection.mutable
object Solution {
def allPathsSourceTarget(graph: Array[Array[Int]]): List[List[Int]] = {
val n = graph.length
val visited = Array.fill[Boolean](n)(false)
val result = mutable.ListBuffer.empty[List[Int]]
val path = mut... | dolphin |
convert this code from TypeScript to Go:
```typescript
function commonChars(words: string[]): string[] {
let charSet = new Set(words[0].split(""));
for (let i = 1; i < words.length; i++) {
let currCharSet = new Set(words[i].split(""));
charSet = new Set([...charSet].filter(char => currCharSet.ha... | dolphin |
Please write the following solution using Elixir:
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`, and moving clockwise fr... | dolphin |
Please focus on the functionality of this problem and provide code in Rust:
You are given an integer `mass`, which represents the original mass of a planet. You are further given an integer array `asteroids`, where `asteroids[i]` is the mass of the `ith` asteroid.
You can arrange for the planet to collide with the ast... | dolphin |
Please explain the reasoning behind the following solution and provide code in Rust:
Given an integer array `nums`, you need to find one **continuous subarray** that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order.
Return _the shortest such subarray and output ... | dolphin |
translate this code to Objective-C:
```elixir
defmodule Solution do
def find_rle_product(encoded1, encoded2) do
result = []
i, j, count1, count2 = 0, 0, 0, 0
while i < length(encoded1) and j < length(encoded2) do
product = encoded1[i][0] * encoded2[j][0]
count = min(encoded1[i][1] - count1, e... | dolphin |
translate this code from Rust to R:
```rust
fn length_of_longest_substring_k_distinct(s: &str, k: i32) -> i32 {
let mut char_count: std::collections::HashMap<char, i32> = std::collections::HashMap::new();
let mut left: usize = 0;
let mut max_length: i32 = 0;
for (right, char) in s.chars().enumerate() {... | dolphin |
port this code from Visual Basic .NET to Lisp:
```vb.net
Function CountArrangement(ByVal n As Integer) As Integer
Dim visited(n) As Boolean
Dim result As Integer = 0
Function Helper(ByVal idx As Integer, ByVal visited() As Boolean) As Integer
If idx > n Then
Return 1
End If
... | dolphin |
Please write the following solution using C#:
Design a queue that supports `push` and `pop` operations in the front, middle, and back.
Implement the `FrontMiddleBack` class:
* `FrontMiddleBack()` Initializes the queue.
* `void pushFront(int val)` Adds `val` to the **front** of the queue.
* `void pushMiddle(int ... | dolphin |
port this code to ANSI C:
```rust
pub fn remove_comments(source: Vec<String>) -> Vec<String> {
let mut result = Vec::new();
let mut buffer = String::new();
let mut in_block_comment = false;
for line in source {
let mut chars = line.chars().peekable();
while let Some(c) = chars.next() {
... | dolphin |
Please explain the following problem in detail and provide code in ANSI C:
You are given a positive integer `n`.
Continuously replace `n` with the sum of its **prime factors**.
* Note that if a prime factor divides `n` multiple times, it should be included in the sum as many times as it divides `n`.
Return _the sm... | dolphin |
Please explain the following problem in detail and provide code in Haskell:
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 th... | dolphin |
Please explain the reasoning behind the following solution and provide code in C#:
Given a string `word`, return _the **sum of the number of vowels** (_`'a'`, `'e'`_,_ `'i'`_,_ `'o'`_, and_ `'u'`_)_ _in every substring of_ `word`.
A **substring** is a contiguous (non-empty) sequence of characters within a string.
**N... | dolphin |
convert this code to Lua:
```fsharp
let isLetterLog (words: string array) : bool =
let firstChar = words.[1].[0]
firstChar >= 'a' && firstChar <= 'z'
let insertIntoLetterLogs (words: string array) (letterLogs: List<string>) : unit =
let index =
letterLogs
|> Seq.findIndex (fun log -> words... | dolphin |
Please write the following solution using C#:
You are given two integer arrays of the same length `nums1` and `nums2`. In one operation, you are allowed to swap `nums1[i]` with `nums2[i]`.
* For example, if `nums1 = [1,2,3,8]`, and `nums2 = [5,6,7,4]`, you can swap the element at `i = 3` to obtain `nums1 = [1,2,3,4]... | dolphin |
convert this code to javascript:
```php
function getPermutation($n, $k) {
$factorials = [1];
$nums = range(1, $n);
$result = [];
for ($i = 1; $i < $n; $i++) {
$factorials[] = $factorials[$i - 1] * $i;
}
$k -= 1;
for ($i = $n; $i > 0; $i--) {
$index = (int)($k / $factorials... | dolphin |
Please explain the following problem in detail and provide code in python:
Given a **positive** integer `n`, return _the smallest positive integer that is a multiple of **both**_ `2` _and_ `n`.
**Example 1:**
**Input:** n = 5
**Output:** 10
**Explanation:** The smallest multiple of both 5 and 2 is 10.
**Example 2:**... | dolphin |
Please explain the reasoning behind the following solution and provide code in Lisp:
You are given a **0-indexed** integer array `costs` where `costs[i]` is the cost of hiring the `ith` worker.
You are also given two integers `k` and `candidates`. We want to hire exactly `k` workers according to the following rules:
... | dolphin |
translate this code to Visual Basic .NET:
```ruby
class PeekingIterator
def initialize(iterator)
@iterator = iterator
@next_val = @iterator.next rescue nil
end
def peek()
@next_val
end
def next()
current_val = @next_val
@next_val = @iterator.next rescue nil
... | dolphin |
convert this code from Scala to TypeScript:
```scala
def maxEqualFreq(nums: Array[Int]): Int = {
var count = Map.empty[Int, Int]
var freq = Map.empty[Int, Int]
var maxLen = 0
var maxFreq = 0
for (i <- nums.indices) {
val num = nums(i)
count += (num -> (count.getOrElse(num, 0) + 1))
freq += ((count... | dolphin |
Please focus on the functionality of this problem and provide code in Clojure:
You are given an integer array `nums` and an integer `threshold`.
Find any subarray of `nums` of length `k` such that **every** element in the subarray is **greater** than `threshold / k`.
Return _the **size** of **any** such subarray_. If... | dolphin |
port this code from javascript to Haskell:
```javascript
function consecutiveNumbersSum(n) {
let count = 0;
for (let i = 1; i * (i - 1) / 2 < n; i++) {
if ((n - i * (i - 1) / 2) % i === 0) {
count++;
}
}
return count;
}
```
| dolphin |
Please explain the reasoning behind the following solution and provide code in Clojure:
Given an array of integers `nums`, return _the number of **good pairs**_.
A pair `(i, j)` is called _good_ if `nums[i] == nums[j]` and `i` < `j`.
**Example 1:**
**Input:** nums = \[1,2,3,1,1,3\]
**Output:** 4
**Explanation:** The... | dolphin |
Please explain the reasoning behind the following solution and provide code in Lisp:
Given a string `s`. Return all the words vertically in the same order in which they appear in `s`.
Words are returned as a list of strings, complete with spaces when is necessary. (Trailing spaces are not allowed).
Each word would ... | dolphin |
Please write the following solution using Lua:
Given an `m x n` binary matrix `mat`, _return the number of **submatrices** that have all ones_.
**Example 1:**
**Input:** mat = \[\[1,0,1\],\[1,1,0\],\[1,1,0\]\]
**Output:** 13
**Explanation:**
There are 6 rectangles of side 1x1.
There are 2 rectangles of side 1x2.
The... | dolphin |
port this code from C# to Scheme:
```csharp
public int MaxLengthPalindrome(string word1, string word2) {
int n1 = word1.Length;
int n2 = word2.Length;
int[,] dp = new int[n1 + 1, n2 + 1];
for (int i = 1; i <= n1; i++) {
for (int j = 1; j <= n2; j++) {
if (word1[i - 1] == word2[j... | dolphin |
Please write the following solution using Erlang:
You are given an integer array `nums` of size `n` containing **each** element from `0` to `n - 1` (**inclusive**). Each of the elements from `1` to `n - 1` represents an item, and the element `0` represents an empty space.
In one operation, you can move **any** item to... | dolphin |
port this code to R:
```java
public int minMoves(int[] nums) {
int min_element = nums[0];
for (int num : nums) {
min_element = Math.min(min_element, num);
}
int moves = 0;
for (int num : nums) {
moves += (num - min_element);
}
return moves;
}
```
| dolphin |
Please explain the reasoning behind the following solution and provide code in Clojure:
You are given an array of `events` where `events[i] = [startDayi, endDayi]`. Every event `i` starts at `startDayi` and ends at `endDayi`.
You can attend an event `i` at any day `d` where `startTimei <= d <= endTimei`. You can only ... | dolphin |
Please write the following solution using Scheme:
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 stones have weights `x` and `y` ... | dolphin |
Please explain the following problem in detail and provide code in Kotlin:
A newly designed keypad was tested, where a tester pressed a sequence of `n` keys, one at a time.
You are given a string `keysPressed` of length `n`, where `keysPressed[i]` was the `ith` key pressed in the testing sequence, and a sorted list `r... | dolphin |
Please explain the following problem in detail and provide code in Scheme:
On a campus represented on the X-Y plane, there are `n` workers and `m` bikes, with `n <= m`.
You are given an array `workers` of length `n` where `workers[i] = [xi, yi]` is the position of the `ith` worker. You are also given an array `bikes` ... | dolphin |
Please explain the following problem in detail and provide code in R:
An **image smoother** is a filter of the size `3 x 3` that can be applied to each cell of an image by rounding down the average of the cell and the eight surrounding cells (i.e., the average of the nine cells in the blue smoother). If one or more of ... | dolphin |
Please explain the following problem in detail and provide code in Ruby:
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 |
translate this code to Clojure:
```elixir
defmodule Solution do
def k_smallest_pairs(nums1, nums2, k) do
if length(nums1) == 0 or length(nums2) == 0 do
[]
else
heap = for i <- 0..min(k, length(nums1))-1, do: {nums1[i] + hd(nums2), i, 0}
:heapq.heapify(heap, fn {sum1, _, _}, {sum2, _, _} -> s... | dolphin |
Please explain the reasoning behind the following solution and provide code in Object Pascal:
You are given an integer array `arr` of length `n` that represents a permutation of the integers in the range `[0, n - 1]`.
We split `arr` into some number of **chunks** (i.e., partitions), and individually sort each chunk. A... | dolphin |
convert this code from Dart to Ruby:
```dart
import 'dart:collection';
List<List<int>> updateMatrix(List<List<int>> mat) {
final int m = mat.length, n = mat[0].length;
final distance = List.generate(m, (i) => List.generate(n, (j) => mat[i][j] == 0 ? 0 : double.infinity));
final queue = Queue<List<int>>.from(
... | dolphin |
Please focus on the efficiency of this problem and provide code in python:
Given a 2D integer array `nums` where `nums[i]` is a non-empty array of **distinct** positive integers, return _the list of integers that are present in **each array** of_ `nums` _sorted in **ascending order**_.
**Example 1:**
**Input:** nums ... | dolphin |
Please explain the following problem in detail and provide code in Scheme:
You are given an array of **distinct** integers `arr` and an array of integer arrays `pieces`, where the integers in `pieces` are **distinct**. Your goal is to form `arr` by concatenating the arrays in `pieces` **in any order**. However, you are... | dolphin |
Please explain the reasoning behind the following solution and provide code in Swift:
You have `n` super washing machines on a line. Initially, each washing machine has some dresses or is empty.
For each move, you could choose any `m` (`1 <= m <= n`) washing machines, and pass one dress of each washing machine to one ... | dolphin |
translate this code to Lua:
```go
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func findFrequentTreeSum(root *TreeNode) []int {
counts := make(map[int]int)
helper(root, counts)
maxCount := 0
for _, c := range counts {
if c > maxCount {
maxCount = c
... | dolphin |
port this code from Elixir to Erlang:
```elixir
defmodule Solution do
def numSubarrayProductLessThanK(nums, k) do
if k <= 1 do
0
else
prod = 1
count = 0
left = 0
for right <- 0..(length(nums) - 1) do
prod *= Enum.at(nums, right)
while prod >= k do
prod =... | dolphin |
translate this code from Ruby to ANSI C:
```ruby
def count_even_digit_sum(num)
count = 0
(1..num).each do |i|
digit_sum = i.to_s.chars.map(&:to_i).sum
count += 1 if digit_sum.even?
end
count
end
``` | dolphin |
Please write the following solution using C#:
There are `n` uniquely-sized sticks whose lengths are integers from `1` to `n`. You want to arrange the sticks such that **exactly** `k` sticks are **visible** from the left. A stick is **visible** from the left if there are no **longer** sticks to the **left** of it.
* ... | dolphin |
convert this code to Visual Basic .NET:
```csharp
public int MaxScoreSightseeingPair(int[] values) {
int maxScore = 0;
int maxI = 0;
for (int j = 1; j < values.Length; j++) {
maxScore = Math.Max(maxScore, values[maxI] + values[j] + maxI - j);
if (values[maxI] + maxI < values[j] + j) {
... | dolphin |
Please write the following solution using Clojure:
You are **building** a string `s` of length `n` **one** character at a time, **prepending** each new character to the **front** of the string. The strings are labeled from `1` to `n`, where the string with length `i` is labeled `si`.
* For example, for `s = "abaca "... | dolphin |
Please focus on the efficiency of this problem and provide code in Scala:
You are given two **0-indexed** strings `word1` and `word2`.
A **move** consists of choosing two indices `i` and `j` such that `0 <= i < word1.length` and `0 <= j < word2.length` and swapping `word1[i]` with `word2[j]`.
Return `true` _if it is ... | dolphin |
Please explain the following problem in detail and provide code in Groovy:
You have `n` flower seeds. Every seed must be planted first before it can begin to grow, then bloom. Planting a seed takes time and so does the growth of a seed. You are given two **0-indexed** integer arrays `plantTime` and `growTime`, of lengt... | dolphin |
Please explain the reasoning behind the following solution and provide code in PHP:
Given the `root` of a binary tree, collect a tree's nodes as if you were doing this:
* Collect all the leaf nodes.
* Remove all the leaf nodes.
* Repeat until the tree is empty.
**Example 1:**
**Input:** root = \[1,2,3,4,5\]
**... | dolphin |
Please explain the following problem in detail and provide code in Scheme:
Given two integer arrays `nums1` and `nums2`, return _an array of their intersection_. Each element in the result must be **unique** and you may return the result in **any order**.
**Example 1:**
**Input:** nums1 = \[1,2,2,1\], nums2 = \[2,2\]... | dolphin |
Please explain the reasoning behind the following solution and provide code in Erlang:
You are given the `head` of a linked list, which contains a series of integers **separated** by `0`'s. The **beginning** and **end** of the linked list will have `Node.val == 0`.
For **every** two consecutive `0`'s, **merge** all th... | dolphin |
Please explain the following problem in detail and provide code in Haskell:
There are `n` pieces arranged in a line, and each piece is colored either by `'A'` or by `'B'`. You are given a string `colors` of length `n` where `colors[i]` is the color of the `ith` piece.
Alice and Bob are playing a game where they take *... | dolphin |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.