instruction_seed stringlengths 29 40.5k | source stringclasses 6
values |
|---|---|
Please write the following solution using Scala:
Given an `m x n` matrix `matrix` and an integer `k`, return _the max sum of a rectangle in the matrix such that its sum is no larger than_ `k`.
It is **guaranteed** that there will be a rectangle with a sum no larger than `k`.
**Example 1:**
**Input:** matrix = \[\[1,... | dolphin |
translate this code from PHP to Groovy:
```php
class TreeNode {
public $val;
public $left;
public $right;
function __construct($val = 0, $left = null, $right = null) {
$this->val = $val;
$this->left = $left;
$this->right = $right;
}
}
class Solution {
function dfs($root,... | dolphin |
Please explain the following problem in detail and provide code in c++:
You are given a positive integer `n` representing the number of nodes in an **undirected** graph. The nodes are labeled from `1` to `n`.
You are also given a 2D integer array `edges`, where `edges[i] = [ai, bi]` indicates that there is a **bidirec... | dolphin |
Please explain the reasoning behind the following solution and provide code in Clojure:
Given an array of strings `words` and an integer `k`, return _the_ `k` _most frequent strings_.
Return the answer **sorted** by **the frequency** from highest to lowest. Sort the words with the same frequency by their **lexicograph... | dolphin |
Please explain the reasoning behind the following solution and provide code in ANSI C:
Given an array of integers `arr`, return `true` if we can partition the array into three **non-empty** parts with equal sums.
Formally, we can partition the array if we can find indexes `i + 1 < j` with `(arr[0] + arr[1] + ... + arr... | dolphin |
convert this code from Scala to Ruby:
```scala
def removeDuplicates(nums: Array[Int]): Int = {
if (nums.isEmpty) return 0
var i = 0
for (j <- 1 until nums.length) {
if (nums(j) != nums(i)) {
i += 1
nums(i) = nums(j)
}
}
i + 1
}
``` | dolphin |
Please write the following solution using PHP:
Given an array of integers `nums` and an integer `k`, return _the total number of subarrays whose sum equals to_ `k`.
A subarray is a contiguous **non-empty** sequence of elements within an array.
**Example 1:**
**Input:** nums = \[1,1,1\], k = 2
**Output:** 2
**Exampl... | dolphin |
Please write the following solution using Scala:
Given two positive integers `n` and `k`, the binary string `Sn` is formed as follows:
* `S1 = "0 "`
* `Si = Si - 1 + "1 " + reverse(invert(Si - 1))` for `i > 1`
Where `+` denotes the concatenation operation, `reverse(x)` returns the reversed string `x`, and `invert... | dolphin |
Please focus on the algorithm of this problem and provide code in Mojo:
A **[binary expression tree](https://en.wikipedia.org/wiki/Binary_expression_tree)** is a kind of binary tree used to represent arithmetic expressions. Each node of a binary expression tree has either zero or two children. Leaf nodes (nodes with 0 ... | dolphin |
Please write the following solution using Haskell:
You are given a string `s` and an array of strings `words`. All the strings of `words` are of **the same length**.
A **concatenated substring** in `s` is a substring that contains all the strings of any permutation of `words` concatenated.
* For example, if `words ... | dolphin |
Please write the following solution using Scala:
Given two **sorted 0-indexed** integer arrays `nums1` and `nums2` as well as an integer `k`, return _the_ `kth` _(**1-based**) smallest product of_ `nums1[i] * nums2[j]` _where_ `0 <= i < nums1.length` _and_ `0 <= j < nums2.length`.
**Example 1:**
**Input:** nums1 = \[... | dolphin |
Please explain the following problem in detail and provide code in Object Pascal:
The demons had captured the princess and imprisoned her in **the bottom-right corner** of a `dungeon`. The `dungeon` consists of `m x n` rooms laid out in a 2D grid. Our valiant knight was initially positioned in **the top-left room** and... | dolphin |
Please focus on the algorithm of this problem and provide code in Swift:
You are given an integer array `banned` and two integers `n` and `maxSum`. You are choosing some number of integers following the below rules:
* The chosen integers have to be in the range `[1, n]`.
* Each integer can be chosen **at most once... | dolphin |
Please explain the reasoning behind the following solution and provide code in Ruby:
Design a stack that supports increment operations on its elements.
Implement the `CustomStack` class:
* `CustomStack(int maxSize)` Initializes the object with `maxSize` which is the maximum number of elements in the stack.
* `voi... | dolphin |
Please write the following solution using F#:
You are given a 2D integer array `ranges` where `ranges[i] = [starti, endi]` denotes that all integers between `starti` and `endi` (both **inclusive**) are contained in the `ith` range.
You are to split `ranges` into **two** (possibly empty) groups such that:
* Each ran... | dolphin |
Please focus on the efficiency of this problem and provide code in Kotlin:
A tree rooted at node 0 is given as follows:
* The number of nodes is `nodes`;
* The value of the `ith` node is `value[i]`;
* The parent of the `ith` node is `parent[i]`.
Remove every subtree whose sum of values of nodes is zero.
Return... | dolphin |
Please write the following solution using Elixir:
You are given two integer arrays `nums1` and `nums2`. We write the integers of `nums1` and `nums2` (in the order they are given) on two separate horizontal lines.
We may draw connecting lines: a straight line connecting two numbers `nums1[i]` and `nums2[j]` such that:
... | dolphin |
Please explain the reasoning behind the following solution and provide code in Elixir:
You are given two **2D** integer arrays `nums1` and `nums2.`
* `nums1[i] = [idi, vali]` indicate that the number with the id `idi` has a value equal to `vali`.
* `nums2[i] = [idi, vali]` indicate that the number with the id `idi... | dolphin |
port this code to Elixir:
```
fun maxSumUnderK(nums: IntArray, k: Int): Int {
var maxSum = -1
for (i in nums.indices) {
for (j in i + 1 until nums.size) {
val sum = nums[i] + nums[j]
if (sum < k && sum > maxSum) {
maxSum = sum
}
}
}
ret... | dolphin |
Please focus on the algorithm of this problem and provide code in ANSI C:
Implement the `RandomizedSet` class:
* `RandomizedSet()` Initializes the `RandomizedSet` object.
* `bool insert(int val)` Inserts an item `val` into the set if not present. Returns `true` if the item was not present, `false` otherwise.
* `... | dolphin |
Please write the following solution using Object Pascal:
You are given a string `s`, which contains stars `*`.
In one operation, you can:
* Choose a star in `s`.
* Remove the closest **non-star** character to its **left**, as well as remove the star itself.
Return _the string after **all** stars have been remove... | dolphin |
port this code to Scheme:
```julia
function equal_sum_subarrays(nums)
sums = Set()
for i in 2:length(nums)
current_sum = nums[i] + nums[i-1]
if current_sum in sums
return true
end
push!(sums, current_sum)
end
return false
end
``` | dolphin |
Please explain the following problem in detail and provide code in Scala:
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` person.
Re... | dolphin |
Please explain the reasoning behind the following solution and provide code in Swift:
You are given an integer `total` indicating the amount of money you have. You are also given two integers `cost1` and `cost2` indicating the price of a pen and pencil respectively. You can spend **part or all** of your money to buy mu... | dolphin |
Please explain the reasoning behind the following solution and provide code in Fortran:
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 a... | dolphin |
Please explain the following problem in detail and provide code in Groovy:
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 computer environ... | dolphin |
Please focus on the algorithm of this problem and provide code in C#:
You are given an array of integers `arr` and an integer `target`.
You have to find **two non-overlapping sub-arrays** of `arr` each with a sum equal `target`. There can be multiple answers so you have to find an answer where the sum of the lengths o... | dolphin |
port this code to Lua:
```go
func countSubarraysWithMedian(nums []int, k int) int {
ans := 0
for left := 0; left < len(nums); left++ {
count := 0
subarray := []int{}
for right := left; right < len(nums); right++ {
if nums[right] == k {
count++
}
... | dolphin |
Please explain the reasoning behind the following solution and provide code in TypeScript:
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... | dolphin |
Please explain the reasoning behind the following solution and provide code in Lua:
There is a garden of `n` flowers, and each flower has an integer beauty value. The flowers are arranged in a line. You are given an integer array `flowers` of size `n` and each `flowers[i]` represents the beauty of the `ith` flower.
A ... | dolphin |
Please focus on the algorithm of this problem and provide code in Dart:
You are given a **0-indexed** array `nums` consisting of positive integers, representing targets on a number line. You are also given an integer `space`.
You have a machine which can destroy targets. **Seeding** the machine with some `nums[i]` all... | dolphin |
convert this code to Visual Basic .NET:
```mojo
class TreeNode(val, left = null, right = null)
var val: Int = val
var left: TreeNode? = left
var right: TreeNode? = right
fun searchBST(root: TreeNode?, val: Int): TreeNode? {
if (root == null || root.val == val) {
return root
}
return if (root.... | dolphin |
Please explain the reasoning behind the following solution and provide code in Julia:
You are given a string `s` that consists of only digits.
Check if we can split `s` into **two or more non-empty substrings** such that the **numerical values** of the substrings are in **descending order** and the **difference** betw... | dolphin |
Please explain the reasoning behind the following solution and provide code in Ruby:
Given a binary tree where each path going from the root to any leaf form a **valid sequence**, check if a given string is a **valid sequence** in such binary tree.
We get the given string from the concatenation of an array of integers... | dolphin |
Please explain the reasoning behind the following solution and provide code in Object Pascal:
Given a valid (IPv4) IP `address`, return a defanged version of that IP address.
A _defanged IP address_ replaces every period `". "` with `"[.] "`.
**Example 1:**
**Input:** address = "1.1.1.1"
**Output:** "1\[.\]1\[.\]1\[... | dolphin |
Please focus on the functionality of this problem and provide code in Objective-C:
Given a fixed-length integer array `arr`, duplicate each occurrence of zero, shifting the remaining elements to the right.
**Note** that elements beyond the length of the original array are not written. Do the above modifications to the... | dolphin |
Please write the following solution using Perl:
A website domain `"discuss.leetcode.com "` consists of various subdomains. At the top level, we have `"com "`, at the next level, we have `"leetcode.com "` and at the lowest level, `"discuss.leetcode.com "`. When we visit a domain like `"discuss.leetcode.com "`, we will a... | dolphin |
convert this code to Go:
```lisp
(defun is-valid-path (grid row col zeros ones)
(cond ((< row 0) nil)
((< col 0) nil)
((>= row (length grid)) nil)
((>= col (length (nth row grid))) nil)
((= (nth row (nth grid row)) 1) (is-valid-path grid (+ row 1) col zeros (+ ones 1)))
(t (is-... | dolphin |
convert this code to Dart:
```swift
class Solution {
func numberToWords(_ num: Int) -> String {
if num == 0 {
return "Zero"
}
let LESS_THAN_20 = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fiftee... | dolphin |
Please focus on the efficiency of this problem and provide code in Haskell:
Given a string `s`, reverse the string according to the following rules:
* All the characters that are not English letters remain in the same position.
* All the English letters (lowercase or uppercase) should be reversed.
Return `s` _aft... | dolphin |
convert this code to Julia:
```ruby
def is_subpath(head, root)
return false if root.nil?
return true if head.nil?
return dfs(head, root) || is_subpath(head, root.left) || is_subpath(head, root.right)
end
def dfs(node, root)
return false if root.nil?
return false if node.nil?
return (node.val == root.val)... | dolphin |
convert this code from R to Lua:
```R
lonely_numbers <- function(nums) {
num_set <- unique(nums)
lonely <- numeric()
for (num in nums) {
if (!(num - 1) %in% num_set && !(num + 1) %in% num_set) {
lonely <- c(lonely, num)
}
}
return(lonely)
}
``` | dolphin |
convert this code to ANSI C:
```scheme
(define (max-size-subsequence-sum-queries nums queries)
(define (binary-search arr q)
(let loop ((low 0) (high (length arr)))
(cond ((>= low high) high)
(else (let ((mid (quotient (+ low high) 2)))
(cond ((> q (list-ref arr mid)) (loop (... | dolphin |
Please explain the reasoning behind the following solution and provide code in Julia:
There is an undirected weighted connected graph. You are given a positive integer `n` which denotes that the graph has `n` nodes labeled from `1` to `n`, and an array `edges` where each `edges[i] = [ui, vi, weighti]` denotes that ther... | dolphin |
Please explain the following problem in detail and provide code in Objective-C:
Given a `file` and assume that you can only read the file using a given method `read4`, implement a method `read` to read `n` characters. Your method `read` may be **called multiple times**.
**Method read4:**
The API `read4` reads **four ... | dolphin |
Please explain the reasoning behind the following solution and provide code in Object Pascal:
There are n people in a social group labeled from `0` to `n - 1`. You are given an array `logs` where `logs[i] = [timestampi, xi, yi]` indicates that `xi` and `yi` will be friends at the time `timestampi`.
Friendship is **sym... | dolphin |
Please explain the following problem in detail and provide code in PHP:
You have `n` robots. You are given two **0-indexed** integer arrays, `chargeTimes` and `runningCosts`, both of length `n`. The `ith` robot costs `chargeTimes[i]` units to charge and costs `runningCosts[i]` units to run. You are also given an intege... | dolphin |
port this code to Clojure:
```typescript
function suggestedProducts(products: string[], searchWord: string): string[][] {
const result: string[][] = [];
products.sort();
for (let i = 0; i < searchWord.length; i++) {
const suggestions: string[] = [];
for (const product of products) {
... | dolphin |
Please write the following solution using ANSI C:
There is a pizza with `3n` slices of varying size, you and your friends will take slices of pizza as follows:
* You will pick **any** pizza slice.
* Your friend Alice will pick the next slice in the anti-clockwise direction of your pick.
* Your friend Bob will pi... | dolphin |
convert this code to ANSI C:
```scala
import scala.collection.mutable
def findDuplicate(paths: Array[String]): List[List[String]] = {
val contentMap = mutable.Map[String, mutable.ListBuffer[String]]()
paths.foreach(path => {
val parts = path.split(" ")
val directory = parts(0)
for (i <- 1 until parts.l... | dolphin |
port this code to C#:
```pascal
function MinAddition(s: string; t: string): Integer;
var
s_len, t_len, i, j: Integer;
begin
s_len := Length(s);
t_len := Length(t);
i := 1;
j := 1;
while (i <= s_len) and (j <= t_len) do
begin
if s[i] = t[j] then
j := j + 1;
i := i + 1;
end;
Result := t_le... | dolphin |
convert this code to python:
```fortran
type TreeNode
integer :: val
type(TreeNode), pointer :: left => null(), right => null()
end type TreeNode
recursive function find_leaves(node, result, level) result (int)
class(TreeNode), pointer :: node
integer, dimension(:), pointer :: result
integer :: lev... | dolphin |
Please explain the following problem in detail and provide code in javascript:
You are given two strings `s` and `sub`. You are also given a 2D character array `mappings` where `mappings[i] = [oldi, newi]` indicates that you may perform the following operation **any** number of times:
* **Replace** a character `oldi... | dolphin |
Please explain the following problem in detail and provide code in ANSI C:
Given the `head` of a linked list, reverse the nodes of the list `k` at a time, and return _the modified list_.
`k` is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of `k... | dolphin |
Please explain the following problem in detail and provide code in Scala:
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 `1` to `... | dolphin |
port this code from Scheme to Swift:
```scheme
(define (is-valid-binary-tree n leftChild rightChild)
(define visited-nodes (make-hash))
(define (helper node)
(cond ((hash-has-key? visited-nodes node) #f)
(else
(hash-set! visited-nodes node #t)
(let ([current-set (list node)])
... | dolphin |
Please explain the following problem in detail and provide code in Elixir:
You are given a **(0-indexed)** array of positive integers `candiesCount` where `candiesCount[i]` represents the number of candies of the `ith` type you have. You are also given a 2D array `queries` where `queries[i] = [favoriteTypei, favoriteDa... | dolphin |
Please explain the reasoning behind the following solution and provide code in Lua:
Given a **(0-indexed)** integer array `nums` and two integers `low` and `high`, return _the number of **nice pairs**_.
A **nice pair** is a pair `(i, j)` where `0 <= i < j < nums.length` and `low <= (nums[i] XOR nums[j]) <= high`.
**E... | dolphin |
Please explain the reasoning behind the following solution and provide code in Haskell:
There is an **undirected** connected tree with `n` nodes labeled from `1` to `n` and `n - 1` edges. You are given the integer `n`. The parent node of a node with a label `v` is the node with the label `floor (v / 2)`. The root of th... | dolphin |
Please write the following solution using Dart:
A polynomial linked list is a special type of linked list where every node represents a term in a polynomial expression.
Each node has three attributes:
* `coefficient`: an integer representing the number multiplier of the term. The coefficient of the term `**9**x4` i... | dolphin |
convert this code to Go:
```kotlin
fun minMoves(nums: IntArray, k: Int): Int {
val n = nums.size
val ones = mutableListOf<Int>()
for (i in nums.indices) {
if (nums[i] == 1) ones.add(i - ones.size)
}
var moves = ones.take(k).sumBy { it - ones[k / 2] }
var minMoves = moves
for (i in k ... | dolphin |
Please write the following solution using Elixir:
We have `n` chips, where the position of the `ith` chip is `position[i]`.
We need to move all the chips to **the same position**. In one step, we can change the position of the `ith` chip from `position[i]` to:
* `position[i] + 2` or `position[i] - 2` with `cost = 0... | dolphin |
Please focus on the algorithm of this problem and provide code in Lisp:
You are playing a game that has `n` levels numbered from `0` to `n - 1`. You are given a **0-indexed** integer array `damage` where `damage[i]` is the amount of health you will lose to complete the `ith` level.
You are also given an integer `armor... | dolphin |
Please write the following solution using PHP:
Given a list of `dominoes`, `dominoes[i] = [a, b]` is **equivalent to** `dominoes[j] = [c, d]` if and only if either (`a == c` and `b == d`), or (`a == d` and `b == c`) - that is, one domino can be rotated to be equal to another domino.
Return _the number of pairs_ `(i, j... | dolphin |
Please explain the following problem in detail and provide code in Scala:
Given an array of integers `arr`, sort the array by performing a series of **pancake flips**.
In one pancake flip we do the following steps:
* Choose an integer `k` where `1 <= k <= arr.length`.
* Reverse the sub-array `arr[0...k-1]` (**0-i... | dolphin |
Please focus on the efficiency of this problem and provide code in F#:
This is an **interactive problem**.
There is a robot in a hidden grid, and you are trying to get it from its starting cell to the target cell in this grid. The grid is of size `m x n`, and each cell in the grid is either empty or blocked. It is **g... | dolphin |
Please explain the reasoning behind the following solution and provide code in Lua:
You are given an `m x n` binary matrix `grid`, where `0` represents a sea cell and `1` represents a land cell.
A **move** consists of walking from one land cell to another adjacent (**4-directionally**) land cell or walking off the bou... | dolphin |
Please explain the following problem in detail and provide code in Elixir:
You are given a binary array `nums` (**0-indexed**).
We define `xi` as the number whose binary representation is the subarray `nums[0..i]` (from most-significant-bit to least-significant-bit).
* For example, if `nums = [1,0,1]`, then `x0 = 1... | dolphin |
Please write the following solution using F#:
You are given four integers `minLength`, `maxLength`, `oneGroup` and `zeroGroup`.
A binary string is **good** if it satisfies the following conditions:
* The length of the string is in the range `[minLength, maxLength]`.
* The size of each block of consecutive `1`'s i... | dolphin |
Please write the following solution using C#:
You are given a **perfect binary tree** where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:
struct Node {
int val;
Node \*left;
Node \*right;
Node \*next;
}
Populate each next pointer to point to... | dolphin |
Please explain the reasoning behind the following solution and provide code in c++:
A **Bitset** is a data structure that compactly stores bits.
Implement the `Bitset` class:
* `Bitset(int size)` Initializes the Bitset with `size` bits, all of which are `0`.
* `void fix(int idx)` Updates the value of the bit at t... | dolphin |
translate this code to Scheme:
```c
#include <stdbool.h>
bool isToeplitzMatrix(int** matrix, int matrixSize, int* matrixColSize){
int rows = matrixSize;
int cols = *matrixColSize;
for(int i=0; i<rows-1; i++){
for(int j=0; j<cols-1; j++){
if(matrix[i][j] != matrix[i+1][j+1]){
... | dolphin |
Please write the following solution using Mojo:
Given a `m x n` matrix `grid` which is sorted in non-increasing order both row-wise and column-wise, return _the number of **negative** numbers in_ `grid`.
**Example 1:**
**Input:** grid = \[\[4,3,2,-1\],\[3,2,1,-1\],\[1,1,-1,-2\],\[-1,-1,-2,-3\]\]
**Output:** 8
**Expla... | dolphin |
Please focus on the algorithm of this problem and provide code in Ruby:
Given a string `s` and a character `c` that occurs in `s`, return _an array of integers_ `answer` _where_ `answer.length == s.length` _and_ `answer[i]` _is the **distance** from index_ `i` _to the **closest** occurrence of character_ `c` _in_ `s`.
... | dolphin |
Please explain the reasoning behind the following solution and provide code in Julia:
Given an integer `n`, return all the **strobogrammatic numbers** that are of length `n`. You may return the answer in **any order**.
A **strobogrammatic number** is a number that looks the same when rotated `180` degrees (looked at u... | dolphin |
translate this code to Groovy:
```ruby
class MyHashMap
def initialize()
@size = 10007
@data = Array.new(@size) { [] }
end
def put(key, value)
bucket = @data[key % @size]
bucket.each do |pair|
if pair[0] == key
pair[1] = value
retur... | dolphin |
port this code to c++:
```go
import "container/list"
type LRUCache struct {
cache map[int]*list.Element
list *list.List
cap int
}
type entry struct {
key int
value int
}
func Constructor(capacity int) LRUCache {
return LRUCache{
cache: make(map[int]*list.Element),
list: ... | dolphin |
Please explain the reasoning behind the following solution and provide code in Object Pascal:
You are given an array of integers `nums`, there is a sliding window of size `k` which is moving from the very left of the array to the very right. You can only see the `k` numbers in the window. Each time the sliding window m... | dolphin |
Please write the following solution using Dart:
Given an integer n, return _the smallest **prime palindrome** greater than or equal to_ `n`.
An integer is **prime** if it has exactly two divisors: `1` and itself. Note that `1` is not a prime number.
* For example, `2`, `3`, `5`, `7`, `11`, and `13` are all primes.
... | dolphin |
Please explain the reasoning behind the following solution and provide code in F#:
You are given a **0-indexed** integer array `nums` of length `n`. You are initially standing at index `0`. You can jump from index `i` to index `j` where `i < j` if:
* `nums[i] <= nums[j]` and `nums[k] < nums[i]` for all indexes `k` i... | dolphin |
Please explain the reasoning behind the following solution and provide code in TypeScript:
You are given an array of `n` integers, `nums`, where there are at most `50` unique values in the array. You are also given an array of `m` customer order quantities, `quantity`, where `quantity[i]` is the amount of integers the ... | dolphin |
Please explain the following problem in detail and provide code in Elixir:
You are given a series of video clips from a sporting event that lasted `time` seconds. These video clips can be overlapping with each other and have varying lengths.
Each video clip is described by an array `clips` where `clips[i] = [starti, e... | dolphin |
convert this code to Erlang:
```go
package main
import (
"fmt"
"sort"
)
func maxPrices(items [][]int, queries []int) []int {
answer := make([]int, len(queries))
sortedItems := make([]int, len(items))
for i := range items {
sortedItems[i] = items[i][0]
}
sort.Ints(sortedItems)
maxBeauty := 0
for i, price :... | dolphin |
Please explain the reasoning behind the following solution and provide code in Erlang:
You are given the `head` of a linked list, and an integer `k`.
Return _the head of the linked list after **swapping** the values of the_ `kth` _node from the beginning and the_ `kth` _node from the end (the list is **1-indexed**)._
... | dolphin |
Please explain the reasoning behind the following solution and provide code in ANSI C:
You are given two arrays of strings that represent two inclusive events that happened **on the same day**, `event1` and `event2`, where:
* `event1 = [startTime1, endTime1]` and
* `event2 = [startTime2, endTime2]`.
Event times a... | dolphin |
port this code to Haskell:
```clojure
(defn TwoSum []
(let [nums (atom {})]
{:add (fn [number] (swap! nums update number (fnil inc 0)))
:find (fn [value]
(some #(let [target (- value %)]
(when (contains? @nums target)
(and (not= target %) true)))
... | dolphin |
Please explain the reasoning behind the following solution and provide code in Dart:
You are given an array `nums` of positive integers. In one operation, you can choose **any** number from `nums` and reduce it to **exactly** half the number. (Note that you may choose this reduced number in future operations.)
Return ... | dolphin |
Please focus on the efficiency of this problem and provide code in Scala:
Given the `root` of a Binary Search Tree (BST), return _the minimum difference between the values of any two different nodes in the tree_.
**Example 1:**
**Input:** root = \[4,2,6,1,3\]
**Output:** 1
**Example 2:**
**Input:** root = \[1,0,48,... | dolphin |
convert this code to Dart:
```groovy
def lenLongestFibSubseq(arr) {
def index = [:]
arr.eachWithIndex { x, i ->
index[x] = i
}
def longest = [:]
def ans = 0
arr.eachWithIndex { z, k ->
arr[0..k-1].eachWithIndex { y, j ->
def i = index.get(z - y, null)
if... | dolphin |
translate this code from Rust to Haskell:
```rust
fn is_tree(n: i32, edges: Vec<Vec<i32>>) -> bool {
let mut neighbors: Vec<Vec<i32>> = vec![vec![]; n as usize];
for edge in edges.iter() {
neighbors[edge[0] as usize].push(edge[1]);
neighbors[edge[1] as usize].push(edge[0]);
}
let mut vis... | dolphin |
convert this code from Julia to Perl:
```julia
mutable struct TreeNode
val::Int
left::Union{TreeNode, Nothing}
right::Union{TreeNode, Nothing}
TreeNode(val) = new(val)
end
function build_binary_tree(descriptions::Array{Array{Int, 1}, 1})::Union{TreeNode, Nothing}
if isempty(descriptions)
re... | dolphin |
Please explain the reasoning behind the following solution and provide code in Kotlin:
The **product sum** of two equal-length arrays `a` and `b` is equal to the sum of `a[i] * b[i]` for all `0 <= i < a.length` (**0-indexed**).
* For example, if `a = [1,2,3,4]` and `b = [5,2,3,1]`, the **product sum** would be `1*5 ... | dolphin |
Please explain the following problem in detail and provide code in Fortran:
Given an integer array `nums` and an integer `k`, return _the number of pairs_ `(i, j)` _where_ `i < j` _such that_ `|nums[i] - nums[j]| == k`.
The value of `|x|` is defined as:
* `x` if `x >= 0`.
* `-x` if `x < 0`.
**Example 1:**
**Inp... | dolphin |
Please write the following solution using Lisp:
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 second mouse eats it.
You are g... | dolphin |
Please explain the reasoning behind the following solution and provide code in Dart:
There are `m` boys and `n` girls in a class attending an upcoming party.
You are given an `m x n` integer matrix `grid`, where `grid[i][j]` equals `0` or `1`. If `grid[i][j] == 1`, then that means the `ith` boy can invite the `jth` gi... | dolphin |
Please explain the following problem in detail and provide code in Scheme:
You are given a 2D integer array `intervals`, where `intervals[i] = [lefti, righti]` describes the `ith` interval starting at `lefti` and ending at `righti` **(inclusive)**. The **size** of an interval is defined as the number of integers it con... | dolphin |
Please focus on the algorithm of this problem and provide code in R:
Given a string `s` and a dictionary of strings `wordDict`, return `true` if `s` can be segmented into a space-separated sequence of one or more dictionary words.
**Note** that the same word in the dictionary may be reused multiple times in the segmen... | dolphin |
convert this code from Haskell to TypeScript:
```
import Data.List
largestWordSender :: [String] -> [String] -> String
largestWordSender messages senders = largestWordSenderHelper (zip messages senders) "" 0
largestWordSenderHelper :: [(String, String)] -> String -> Int -> String
largestWordSenderHelper [] sender cou... | dolphin |
translate this code from C# to Erlang:
```csharp
using System;
using System.Collections.Generic;
using System.Linq;
public class Solution {
public int NextGreaterElement(int n) {
char[] numArray = n.ToString().ToCharArray();
int length = numArray.Length, i = length - 2;
while (i >= 0 && num... | dolphin |
Please explain the following problem in detail and provide code in java:
You want to water `n` plants in your garden with a watering can. The plants are arranged in a row and are labeled from `0` to `n - 1` from left to right where the `ith` plant is located at `x = i`. There is a river at `x = -1` that you can refill ... | dolphin |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.