instruction_seed stringlengths 29 40.5k | source stringclasses 6
values |
|---|---|
translate this code from Clojure to Perl:
```clojure
(defn find-chair [times target-friend]
(let [n (count times)
events (sort-by first (flatten (map-indexed (fn [i [arrival leaving]]
(list (list arrival i)
... | dolphin |
Please explain the reasoning behind the following solution and provide code in Object Pascal:
You are given an `m x n` integer matrix `grid`.
We define an **hourglass** as a part of the matrix with the following form:
Return _the **maximum** sum of the elements of an hourglass_.
**Note** that an hourglass cannot be ... | dolphin |
convert this code to Ruby:
```
-module(malware_minimization).
-export([malware_minimization/2, bfs/2]).
malware_minimization(Graph, Initial) ->
MinInfected = infinity,
MinNode = -1,
lists:foreach(fun(Node) ->
Infected = bfs(Graph, lists:delete(Node, Initial)),
if
Infected < MinI... | dolphin |
Please write the following solution using c++:
You are given an `m x n` matrix `maze` (**0-indexed**) with empty cells (represented as `'.'`) and walls (represented as `'+'`). You are also given the `entrance` of the maze, where `entrance = [entrancerow, entrancecol]` denotes the row and column of the cell you are init... | dolphin |
Please explain the following problem in detail and provide code in C#:
Given an array of integers `citations` where `citations[i]` is the number of citations a researcher received for their `ith` paper and `citations` is sorted in **ascending order**, return _the researcher's h-index_.
According to the [definition of ... | dolphin |
Please explain the reasoning behind the following solution and provide code in Elixir:
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 `... | dolphin |
Please explain the following problem in detail and provide code in Groovy:
Design a [Snake game](https://en.wikipedia.org/wiki/Snake_(video_game)) that is played on a device with screen size `height x width`. [Play the game online](http://patorjk.com/games/snake/) if you are not familiar with the game.
The snake is in... | dolphin |
Please write the following solution using R:
Given three integers `x`, `y`, and `bound`, return _a list of all the **powerful integers** that have a value less than or equal to_ `bound`.
An integer is **powerful** if it can be represented as `xi + yj` for some integers `i >= 0` and `j >= 0`.
You may return the answer... | dolphin |
Please write the following solution using c++:
Design a food rating system that can do the following:
* **Modify** the rating of a food item listed in the system.
* Return the highest-rated food item for a type of cuisine in the system.
Implement the `FoodRatings` class:
* `FoodRatings(String[] foods, String[]... | dolphin |
Please focus on the efficiency of this problem and provide code in F#:
You are given an integer array `nums` with the following properties:
* `nums.length == 2 * n`.
* `nums` contains `n + 1` **unique** elements.
* Exactly one element of `nums` is repeated `n` times.
Return _the element that is repeated_ `n` _t... | dolphin |
translate this code to Ruby:
```python
def maxWidthOfVerticalArea(points):
xs = sorted([point[0] for point in points])
max_width = 0
for i in range(1, len(xs)):
max_width = max(max_width, xs[i] - xs[i - 1])
return max_width
```
| dolphin |
convert this code to Objective-C:
```perl
sub performOps {
my @nums = @_;
my $n = scalar(@nums);
for (my $i = 0; $i < $n - 1; $i++) {
if ($nums[$i] == $nums[$i + 1]) {
$nums[$i] *= 2;
$nums[$i + 1] = 0;
}
}
my $nonZeroIndex = 0;
for (my $i = 0; $i < $n; $i... | dolphin |
translate this code from Scheme to Scala:
```scheme
(define (max-money nums)
(define (rob start end)
(let ((prev 0)
(curr 0))
(do ((i start (+ i 1)))
((= i end))
(let ((temp (max curr (+ prev (list-ref nums i)))))
(set! prev curr)
(set! curr temp)))
curr... | dolphin |
port this code to PHP:
```erlang
count_digit_one(N) ->
Count = 0,
I = 1,
count_digit_one(N, I, Count).
count_digit_one(N, I, Count) when I > N ->
Count;
count_digit_one(N, I, Count) ->
Divider = I * 10,
Count1 = (N div Divider) * I,
Count2 = min(max(N rem Divider - I + 1, 0), I),
Total... | dolphin |
Please explain the following problem in detail and provide code in Scheme:
Given two strings `text1` and `text2`, return _the length of their longest **common subsequence**._ If there is no **common subsequence**, return `0`.
A **subsequence** of a string is a new string generated from the original string with some ch... | dolphin |
Please focus on the functionality of this problem and provide code in Scheme:
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.
Ret... | dolphin |
convert this code to Scala:
```go
func max(a, b int) int {
if a > b {
return a
}
return b
}
func longestAwesomeSubstring(s string) int {
n := len(s)
maxLen := 0
for i := 0; i < n; i++ {
for j := i + 1; j <= n; j++ {
substr := s[i:j]
if isAwesome(substr) {... | dolphin |
convert this code to Lisp:
```cpp
#include <vector>
#include <algorithm>
int minScoreAfterChange(std::vector<int>& nums) {
int n = nums.size();
int first_min = nums[0], second_min = nums[1], last_max = nums[n - 1], second_last_max = nums[n - 2];
for (int i = 1; i < n - 1; i++) {
first_min = st... | dolphin |
translate this code from Ruby to javascript:
```ruby
class UndergroundSystem
def initialize()
@check_in_info = {}
@journey_data = {}
end
def check_in(id, station_name, t)
@check_in_info[id] = [station_name, t]
end
def check_out(id, station_name, t)
start_station, start_time = @check... | dolphin |
Please explain the following problem in detail and provide code in Object Pascal:
In a linked list of size `n`, where `n` is **even**, the `ith` node (**0-indexed**) of the linked list is known as the **twin** of the `(n-1-i)th` node, if `0 <= i <= (n / 2) - 1`.
* For example, if `n = 4`, then node `0` is the twin o... | dolphin |
translate this code from R to c++:
```R
find_longest_repeating_substring <- function(s) {
n <- nchar(s)
max_substr_length <- 0
for (length in 1:(n %/% 2 + 1)) {
max_repeat_count <- repeat_count <- 0
for (i in 1:(n - length)) {
if (substr(s, i, i + length - 1) == substr(s, i + len... | dolphin |
translate this code from c++ to Mojo:
```cpp
#include <vector>
using namespace std;
void moveEvenOdd(vector<int>& nums) {
int evenIndex = 0;
int oddIndex = nums.size() - 1;
while (evenIndex < oddIndex) {
if (nums[evenIndex] % 2 == 0) {
evenIndex++;
} else {
swap(num... | dolphin |
Please explain the reasoning behind the following solution and provide code in TypeScript:
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 ... | dolphin |
port this code from Go to Ruby:
```go
func maxPoints(reward1 []int, reward2 []int, k int) int {
gap := make([][2]int, len(reward1))
for i := range reward1 {
gap[i] = [2]int{reward2[i] - reward1[i], i}
}
sort.Slice(gap, func(i, j int) bool {
return gap[i][0] > gap[j][0]
})
firstMo... | dolphin |
Please focus on the efficiency of this problem and provide code in Perl:
Given the `root` of a binary search tree, return _a **balanced** binary search tree with the same node values_. If there is more than one answer, return **any of them**.
A binary search tree is **balanced** if the depth of the two subtrees of eve... | dolphin |
Please write the following solution using python:
Given an array of `digits` which is sorted in **non-decreasing** order. You can write numbers using each `digits[i]` as many times as we want. For example, if `digits = ['1','3','5']`, we may write numbers such as `'13'`, `'551'`, and `'1351315'`.
Return _the number of... | dolphin |
Please explain the reasoning behind the following solution and provide code in Go:
Design a **Skiplist** without using any built-in libraries.
A **skiplist** is a data structure that takes `O(log(n))` time to add, erase and search. Comparing with treap and red-black tree which has the same function and performance, th... | dolphin |
port this code from Visual Basic .NET to R:
```vb.net
Module Module1
Const MOD As Integer = 1000000007
Function NumDivisions(ByVal corridor As String) As Integer
Dim n As Integer = corridor.Length
Dim count As Integer = 0
For i As Integer = 1 To n - 2
If corridor(i - 1) = "... | dolphin |
Please focus on the functionality of this problem and provide code in ANSI C:
There are `n` computers numbered from `0` to `n - 1` connected by ethernet cables `connections` forming a network where `connections[i] = [ai, bi]` represents a connection between computers `ai` and `bi`. Any computer can reach any other comp... | dolphin |
port this code to Rust:
```fsharp
let fizzBuzz n =
let result = List.empty<string>
for i in 1..n do
if i % 15 = 0 then
result = result @ ["FizzBuzz"]
elif i % 3 = 0 then
result = result @ ["Fizz"]
elif i % 5 = 0 then
result = result @ ["Buzz"]
... | dolphin |
translate this code to Ruby:
```mojo
sub strictlyIncreasingArray(nums) {
for my $i (0..@nums-2) {
$nums[$i] -= $i;
if ($nums[$i] >= $nums[$i+1]) {
return False;
}
}
return True;
}
``` | dolphin |
Please focus on the algorithm of this problem and provide code in Rust:
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 **an... | dolphin |
translate this code from F# to Objective-C:
```fsharp
let numUniqueEmails (emails : string []) =
let uniqueEmails = System.Collections.Generic.HashSet<string>()
for email in emails do
let localName, domainName = email.Split('@')
let newLocalName = localName.Split('+').[0].Replace(".", "")
... | dolphin |
Please write the following solution using Groovy:
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,1,4\], root2 = \[1,0,3\... | dolphin |
translate this code from Fortran to Scheme:
```fortran
program escape_pacman
implicit none
integer, parameter :: max_n = 100
integer :: n, i, x_target, y_target
integer :: ghosts(max_n, 2)
logical :: can_escape
read(*,*) n
do i = 1, n
read(*,*) ghosts(i, 1), ghosts(i, 2)
... | dolphin |
Please explain the following problem in detail and provide code in Swift:
A transaction is possibly invalid if:
* the amount exceeds `$1000`, or;
* if it occurs within (and including) `60` minutes of another transaction with the **same name** in a **different city**.
You are given an array of strings `transaction... | dolphin |
translate this code to C#:
```fortran
function date_to_days(date)
character(len=*), intent(in) :: date
integer :: month, day, days_in_month(13)
days_in_month = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
read(date, *) month, day
date_to_days = sum(days_in_month(1:month)) + day
end function
... | dolphin |
Please write the following solution using Groovy:
You are given an immutable linked list, print out all values of each node in reverse with the help of the following interface:
* `ImmutableListNode`: An interface of immutable linked list, you are given the head of the list.
You need to use the following functions t... | dolphin |
port this code from TypeScript to python:
```typescript
class SORTracker {
private locations: [string, number][] = [];
private queries = 0;
add(name: string, score: number): void {
const location: [string, number] = [name, score];
let insertIndex = 0;
while (insertIndex < this.l... | dolphin |
translate this code from Rust to Elixir:
```rust
fn find_majority_element(nums: &Vec<i32>) -> i32 {
let n = nums.len();
let mut zeros = 0;
let mut ones = 0;
for i in 0..n {
let query_result = query(i, i, i+1, i+1);
if query_result == 4 {
zeros += 2;
ones += 2;
... | dolphin |
translate this code to Elixir:
```erlang
% Definition of a linked list node
-record(node, {val, next}).
add_linked_lists(L1, L2) ->
Result = #node{val=0},
Current = Result,
Carry = 0,
add_linked_lists(L1, L2, Current, Carry),
Result#node.next.
add_linked_lists(L1, L2, Current, Carry) ->
{Val1,... | dolphin |
convert this code from Mojo to javascript:
```
sub MAX_MEX(nums, value) {
my %st = ();
for (my $i = 0; $i <= 100000; $i++) {
if (!exists $st{$i}) {
$st{$i + $value} = 1;
}
}
my $mex = 0;
while (exists $st{$mex}) {
$mex++;
}
return $mex;
}
``` | dolphin |
Please focus on the efficiency of this problem and provide code in Lisp:
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 `ith` customer ord... | dolphin |
Please write the following solution using Scala:
Given an array of non-negative integers `arr`, you are initially positioned at `start` index of the array. When you are at index `i`, you can jump to `i + arr[i]` or `i - arr[i]`, check if you can reach to **any** index with value 0.
Notice that you can not jump outside... | dolphin |
Please explain the following problem in detail and provide code in Perl:
There is a **directed graph** of `n` colored nodes and `m` edges. The nodes are numbered from `0` to `n - 1`.
You are given a string `colors` where `colors[i]` is a lowercase English letter representing the **color** of the `ith` node in this gra... | dolphin |
translate this code to Scala:
```ruby
def min_days_to_disconnect(grid)
def dfs(grid)
islands = 0
m, n = grid.length, grid[0].length
(0...m).each do |i|
(0...n).each do |j|
if grid[i][j] == 1
islands += 1
stack = [[i,j]]
... | dolphin |
convert this code to Erlang:
```groovy
def maxScore(nums, k) {
def n = nums.size()
def left = new int[n]
def right = new int[n]
def stack = []
for (i in 0..<n) {
while (stack && nums[stack[-1]] > nums[i]) {
stack.pop()
}
if (stack) {
left[i] = stack[-... | dolphin |
Please write the following solution using Object Pascal:
You are given an array of strings `ideas` that represents a list of names to be used in the process of naming a company. The process of naming a company is as follows:
1. Choose 2 **distinct** names from `ideas`, call them `ideaA` and `ideaB`.
2. Swap the firs... | dolphin |
Please focus on the efficiency of this problem and provide code in Scheme:
You are given a string `s` consisting of lowercase letters and an integer `k`. We call a string `t` **ideal** if the following conditions are satisfied:
* `t` is a **subsequence** of the string `s`.
* The absolute difference in the alphabet... | dolphin |
translate this code to Fortran:
```javascript
function networkDelayTime(times, n, k) {
const graph = new Map();
for (const [u, v, w] of times) {
if (!graph.has(u)) graph.set(u, []);
graph.get(u).push([v, w]);
}
const dist = new Array(n + 1).fill(Infinity);
dist[k] = 0;
cons... | dolphin |
port this code from Scheme to java:
```scheme
(define (longest-line mat)
(let ((rows (length mat))
(cols (length (car mat)))
(dp (make-vector rows (make-vector cols (make-vector 4 0))))
(max-length 0))
(do ((r 0 (+ r 1)))
((= r rows))
(do ((c 0 (+ c 1)))
((= c cols)... | dolphin |
Please explain the following problem in detail and provide code in Dart:
Given an integer array `nums`, rotate the array to the right by `k` steps, where `k` is non-negative.
**Example 1:**
**Input:** nums = \[1,2,3,4,5,6,7\], k = 3
**Output:** \[5,6,7,1,2,3,4\]
**Explanation:**
rotate 1 steps to the right: \[7,1,2,3... | dolphin |
Please focus on the efficiency of this problem and provide code in javascript:
You are given a tree with `n` nodes numbered from `0` to `n - 1` in the form of a parent array `parent` where `parent[i]` is the parent of `ith` node. The root of the tree is node `0`. Find the `kth` ancestor of a given node.
The `kth` ance... | dolphin |
Please explain the following problem in detail and provide code in Elixir:
Given an integer array `arr`, return _the number of distinct bitwise ORs of all the non-empty subarrays of_ `arr`.
The bitwise OR of a subarray is the bitwise OR of each integer in the subarray. The bitwise OR of a subarray of one integer is th... | dolphin |
Please focus on the functionality of this problem and provide code in Julia:
You have a water dispenser that can dispense cold, warm, and hot water. Every second, you can either fill up `2` cups with **different** types of water, or `1` cup of any type of water.
You are given a **0-indexed** integer array `amount` of ... | dolphin |
Please focus on the efficiency of this problem and provide code in Julia:
On an infinite plane, a robot initially stands at `(0, 0)` and faces north. Note that:
* The **north direction** is the positive direction of the y-axis.
* The **south direction** is the negative direction of the y-axis.
* The **east direc... | dolphin |
Please explain the following problem in detail and provide code in Scala:
Alice and Bob take turns playing a game, with **Alice starting first**.
There are `n` stones arranged in a row. On each player's turn, while the number of stones is **more than one**, they will do the following:
1. Choose an integer `x > 1`, a... | dolphin |
Please explain the reasoning behind the following solution and provide code in Kotlin:
Given an integer array `nums`, find the subarray with the largest sum, and return _its sum_.
**Example 1:**
**Input:** nums = \[-2,1,-3,4,-1,2,1,-5,4\]
**Output:** 6
**Explanation:** The subarray \[4,-1,2,1\] has the largest sum 6.... | dolphin |
Please focus on the functionality of this problem and provide code in Elixir:
Given the `root` of a binary tree, return _its maximum depth_.
A binary tree's **maximum depth** is the number of nodes along the longest path from the root node down to the farthest leaf node.
**Example 1:**
**Input:** root = \[3,9,20,nul... | dolphin |
Please focus on the algorithm of this problem and provide code in TypeScript:
Given a string `s`, remove the vowels `'a'`, `'e'`, `'i'`, `'o'`, and `'u'` from it, and return the new string.
**Example 1:**
**Input:** s = "leetcodeisacommunityforcoders "
**Output:** "ltcdscmmntyfrcdrs "
**Example 2:**
**Input:** s ... | dolphin |
Please focus on the functionality of this problem and provide code in Go:
Given an integer array `arr` of **distinct** integers and an integer `k`.
A game will be played between the first two elements of the array (i.e. `arr[0]` and `arr[1]`). In each round of the game, we compare `arr[0]` with `arr[1]`, the larger in... | dolphin |
Please explain the reasoning behind the following solution and provide code in Perl:
Given a binary string `s`, return _the number of substrings with all characters_ `1`_'s_. Since the answer may be too large, return it modulo `109 + 7`.
**Example 1:**
**Input:** s = "0110111 "
**Output:** 9
**Explanation:** There a... | dolphin |
Please explain the reasoning behind the following solution and provide code in Elixir:
Given an integer array `nums`, return _an integer array_ `counts` _where_ `counts[i]` _is the number of smaller elements to the right of_ `nums[i]`.
**Example 1:**
**Input:** nums = \[5,2,6,1\]
**Output:** \[2,1,1,0\]
**Explanation... | dolphin |
Please focus on the functionality of this problem and provide code in Lisp:
You are given a **directed** graph of `n` nodes numbered from `0` to `n - 1`, where each node has **at most one** outgoing edge.
The graph is represented with a given **0-indexed** array `edges` of size `n`, indicating that there is a directed... | dolphin |
Please explain the reasoning behind the following solution and provide code in Rust:
Given an integer array `nums`, return _the number of **subarrays** filled with_ `0`.
A **subarray** is a contiguous non-empty sequence of elements within an array.
**Example 1:**
**Input:** nums = \[1,3,0,0,2,0,0,4\]
**Output:** 6
*... | dolphin |
Please focus on the efficiency of this problem and provide code in Go:
You are given two **0-indexed** integer arrays `fronts` and `backs` of length `n`, where the `ith` card has the positive integer `fronts[i]` printed on the front and `backs[i]` printed on the back. Initially, each card is placed on a table such that... | dolphin |
Please write the following solution using R:
You are given an integer array, `nums`, and an integer `k`. `nums` comprises of only `0`'s and `1`'s. In one move, you can choose two **adjacent** indices and swap their values.
Return _the **minimum** number of moves required so that_ `nums` _has_ `k` _**consecutive**_ `1`... | dolphin |
Please write the following solution using Lua:
You are given a **0-indexed** integer array `nums`. The array `nums` is **beautiful** if:
* `nums.length` is even.
* `nums[i] != nums[i + 1]` for all `i % 2 == 0`.
Note that an empty array is considered beautiful.
You can delete any number of elements from `nums`. W... | dolphin |
Please write the following solution using F#:
A **pangram** is a sentence where every letter of the English alphabet appears at least once.
Given a string `sentence` containing only lowercase English letters, return `true` _if_ `sentence` _is a **pangram**, or_ `false` _otherwise._
**Example 1:**
**Input:** sentence... | dolphin |
Please focus on the algorithm of this problem and provide code in Ruby:
You are controlling a robot that is located somewhere in a room. The room is modeled as an `m x n` binary grid where `0` represents a wall and `1` represents an empty slot.
The robot starts at an unknown location in the room that is guaranteed to ... | dolphin |
Please write the following solution using Clojure:
Given the `root` of a binary tree and an integer `targetSum`, return _the number of paths where the sum of the values along the path equals_ `targetSum`.
The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from ... | dolphin |
convert this code from TypeScript to Erlang:
```typescript
function find(parent: number[], x: number): number {
if (parent[x] !== x) {
parent[x] = find(parent, parent[x]);
}
return parent[x];
}
function minimumCost(n: number, connections: number[][]): number {
connections.sort((a, b) => a[2] - b[2]);
con... | dolphin |
Please focus on the algorithm of this problem and provide code in Swift:
Given a non-empty array of non-negative integers `nums`, the **degree** of this array is defined as the maximum frequency of any one of its elements.
Your task is to find the smallest possible length of a (contiguous) subarray of `nums`, that has... | dolphin |
Please explain the reasoning behind the following solution and provide code in Julia:
An experiment is being conducted in a lab. To ensure accuracy, there are **two** sensors collecting data simultaneously. You are given two arrays `sensor1` and `sensor2`, where `sensor1[i]` and `sensor2[i]` are the `ith` data points c... | dolphin |
Please explain the following problem in detail and provide code in javascript:
You want to build some obstacle courses. You are given a **0-indexed** integer array `obstacles` of length `n`, where `obstacles[i]` describes the height of the `ith` obstacle.
For every index `i` between `0` and `n - 1` (**inclusive**), fi... | dolphin |
convert this code to R:
```
sub countDistinctSubsequences {
my ($s) = @_;
my $n = length($s);
my $mod = 1e9 + 7;
my @dp = (0) x ($n + 1);
my @last = (-1) x 26;
$dp[0] = 1;
for my $i (0..$n-1) {
$dp[$i + 1] = ($dp[$i] * 2) % $mod;
if ($last[ord(substr($s, $i, 1)) - 97] != -1) ... | dolphin |
Please explain the reasoning behind the following solution and provide code in ANSI C:
There are two types of persons:
* The **good person**: The person who always tells the truth.
* The **bad person**: The person who might tell the truth and might lie.
You are given a **0-indexed** 2D integer array `statements` ... | dolphin |
Please write the following solution using javascript:
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 computer environment.
... | dolphin |
convert this code from Swift to PHP:
```swift
func canIWin(_ maxChoosableInteger: Int, _ desiredTotal: Int) -> Bool {
if maxChoosableInteger >= desiredTotal { return true }
if (maxChoosableInteger * (maxChoosableInteger + 1)) / 2 < desiredTotal { return false }
var memo: [Int: Bool] = [:]
func... | dolphin |
Please focus on the functionality of this problem and provide code in Rust:
You are given an array `nums` consisting of **positive** integers and an integer `k`.
**Partition** the array into two ordered **groups** such that each element is in exactly **one** group. A partition is called great if the **sum** of element... | dolphin |
Please focus on the efficiency of this problem and provide code in Fortran:
There are `n` bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb.
On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the `ith` round, you togg... | dolphin |
port this code to Fortran:
```java
public class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(0);
ListNode current = dummy;
int carry = 0;
while (l1 != null || l2 != null || carry !=... | dolphin |
Please explain the reasoning behind the following solution and provide code in Mojo:
You want to build some obstacle courses. You are given a **0-indexed** integer array `obstacles` of length `n`, where `obstacles[i]` describes the height of the `ith` obstacle.
For every index `i` between `0` and `n - 1` (**inclusive*... | dolphin |
Please focus on the efficiency of this problem and provide code in Objective-C:
You are given a string s of length `n` containing only four kinds of characters: `'Q'`, `'W'`, `'E'`, and `'R'`.
A string is said to be **balanced** if each of its characters appears `n / 4` times where `n` is the length of the string.
Re... | dolphin |
port this code from ANSI C to Go:
```c
int arrayNesting(int* nums, int numsSize){
int max_len = 0;
for(int i = 0; i < numsSize; i++) {
if(nums[i] != -1) {
int start = nums[i];
int count = 0;
while(nums[start] != -1) {
int temp = start;
... | dolphin |
Please explain the following problem in detail and provide code in Haskell:
Given an `m x n` matrix `mat` where every row is sorted in **strictly** **increasing** order, return _the **smallest common element** in all rows_.
If there is no common element, return `-1`.
**Example 1:**
**Input:** mat = \[\[1,2,3,4,5\],\... | dolphin |
Please explain the reasoning behind the following solution and provide code in F#:
There is a hotel with `n` rooms. The rooms are represented by a 2D integer array `rooms` where `rooms[i] = [roomIdi, sizei]` denotes that there is a room with room number `roomIdi` and size equal to `sizei`. Each `roomIdi` is guaranteed ... | dolphin |
port this code to Lua:
```julia
function tallestBillboard(rods::Array{Int, 1})
n = length(rods)
totalLength = sum(rods)
dp = fill(-1, (n+1, totalLength+1))
dp[1, 1] = 0
for i in 2:n+1
for j in 1:totalLength+1
dp[i, j] = dp[i-1, j]
if rods[i-1] <= j
... | dolphin |
Please explain the reasoning behind the following solution and provide code in Ruby:
You are given an integer array `nums`. The adjacent integers in `nums` will perform the float division.
* For example, for `nums = [2,3,4]`, we will evaluate the expression `"2/3/4 "`.
However, you can add any number of parenthesis... | dolphin |
Please focus on the functionality of this problem and provide code in c++:
There exists an infinitely large two-dimensional grid of uncolored unit cells. You are given a positive integer `n`, indicating that you must do the following routine for `n` minutes:
* At the first minute, color **any** arbitrary unit cell b... | dolphin |
port this code to Fortran:
```swift
func maxValueAfterOperations(_ grid: [[Int]]) -> Int {
var ans = 0
var grid = grid
while !grid.isEmpty {
var maxVal = 0
var maxRow = -1
for i in 0..<grid.count {
let rowMax = grid[i].max()!
if rowMax > maxVal {... | dolphin |
Please explain the following problem in detail and provide code in c++:
Given two integers `n` and `k`, return _the_ `kth` _lexicographically smallest integer in the range_ `[1, n]`.
**Example 1:**
**Input:** n = 13, k = 2
**Output:** 10
**Explanation:** The lexicographical order is \[1, 10, 11, 12, 13, 2, 3, 4, 5, 6... | dolphin |
Please write the following solution using ANSI C:
You are given an integer array `cost` where `cost[i]` is the cost of `ith` step on a staircase. Once you pay the cost, you can either climb one or two steps.
You can either start from the step with index `0`, or the step with index `1`.
Return _the minimum cost to rea... | dolphin |
translate this code from Mojo to R:
```
sub min_training_hours(initial_energy, initial_experience, energy, experience) {
my $n = scalar @energy;
my $ans = INF;
for my $exp_gain (0 .. ($initial_energy + $initial_experience)) {
my $training_hours = $exp_gain;
my $energy_left = $initial_energy ... | dolphin |
Please explain the reasoning behind the following solution and provide code in Clojure:
You are given an array `points` where `points[i] = [xi, yi]` represents a point on an **X-Y** plane.
**Straight lines** are going to be added to the **X-Y** plane, such that every point is covered by at **least** one line.
Return ... | dolphin |
Please explain the following problem in detail and provide code in Perl:
Given an integer array `nums` and an integer `k`, return `true` if it is possible to divide this array into `k` non-empty subsets whose sums are all equal.
**Example 1:**
**Input:** nums = \[4,3,2,3,5,2,1\], k = 4
**Output:** true
**Explanation:... | dolphin |
Please write the following solution using Clojure:
You are given a positive integer array `nums`.
* The **element sum** is the sum of all the elements in `nums`.
* The **digit sum** is the sum of all the digits (not necessarily distinct) that appear in `nums`.
Return _the **absolute** difference between the **ele... | dolphin |
convert this code from Groovy to PHP:
```groovy
def maxValueInStack(nums, k) {
def n = nums.size()
if (k >= n) {
return -1
}
def max_val = Integer.MIN_VALUE
for (def i = 0; i <= k; i++) {
max_val = Math.max(max_val, nums[i])
}
return max_val
}
``` | dolphin |
Please focus on the functionality of this problem and provide code in C#:
You are given a string `s` and an integer `repeatLimit`. Construct a new string `repeatLimitedString` using the characters of `s` such that no letter appears **more than** `repeatLimit` times **in a row**. You do **not** have to use all character... | dolphin |
Please focus on the functionality of this problem and provide code in python:
You are given a **0-indexed** `m x n` integer matrix `grid` consisting of **distinct** integers from `0` to `m * n - 1`. You can move in this matrix from a cell to any other cell in the **next** row. That is, if you are in cell `(x, y)` such ... | dolphin |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.