instruction_seed stringlengths 29 40.5k | source stringclasses 6
values |
|---|---|
Please write the following solution using java:
Design your implementation of the circular double-ended queue (deque).
Implement the `MyCircularDeque` class:
* `MyCircularDeque(int k)` Initializes the deque with a maximum size of `k`.
* `boolean insertFront()` Adds an item at the front of Deque. Returns `true` if... | dolphin |
convert this code to PHP:
```elixir
defmodule Solution do
def max_apples(apples, days) do
n = length(apples)
eaten = 0
heap = :gb_trees.empty()
for i <- 0..n-1 do
if apples[i] > 0 do
:gb_trees.insert(heap, {i + days[i], apples[i]})
end
while :gb_trees.size(heap) > 0 do
... | dolphin |
Please focus on the functionality of this problem and provide code in javascript:
Given a `n * n` matrix `grid` of `0's` and `1's` only. We want to represent `grid` with a Quad-Tree.
Return _the root of the Quad-Tree representing_ `grid`.
A Quad-Tree is a tree data structure in which each internal node has exactly fo... | dolphin |
convert this code from Scala to TypeScript:
```scala
def isPalindrome(s: String): Boolean = {
s == s.reverse
}
def closestPalindrome(n: String): Int = {
val num = n.toInt
var left = num - 1
var right = num + 1
while (true) {
if (isPalindrome(left.toString)) {
return left
... | dolphin |
Please write the following solution using Visual Basic .NET:
There is a long and thin painting that can be represented by a number line. The painting was painted with multiple overlapping segments where each segment was painted with a **unique** color. You are given a 2D integer array `segments`, where `segments[i] = [... | dolphin |
Please explain the reasoning behind the following solution and provide code in Haskell:
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 a... | dolphin |
convert this code to Ruby:
```typescript
function minSteps(n: number): number {
let result: number = 0;
let i: number = 2;
while (i <= n) {
while (n % i === 0) {
result += i;
n /= i;
}
i++;
}
return result;
}
``` | dolphin |
convert this code to Perl:
```c
#include <ctype.h>
#include <stdio.h>
#include <string.h>
char* reorderSpaces(char* text) {
int num_words = 0, spaces = 0, spaces_between_words, extra_spaces;
char *word, *result = NULL, *temp;
for (int i = 0; text[i] != '\0'; i++) {
if (isspace(text[i])) {
... | dolphin |
Please write the following solution using java:
Given an array of integers `arr` and an integer `k`. Find the _least number of unique integers_ after removing **exactly** `k` elements**.**
**Example 1:**
**Input:** arr = \[5,5,4\], k = 1
**Output:** 1
**Explanation**: Remove the single 4, only 5 is left.
**Example 2... | dolphin |
Please explain the reasoning behind the following solution and provide code in Kotlin:
A split of an integer array is **good** if:
* The array is split into three **non-empty** contiguous subarrays - named `left`, `mid`, `right` respectively from left to right.
* The sum of the elements in `left` is less than or e... | dolphin |
Please explain the reasoning behind the following solution and provide code in python:
You are entering a competition, and are given two **positive** integers `initialEnergy` and `initialExperience` denoting your initial energy and initial experience respectively.
You are also given two **0-indexed** integer arrays `e... | dolphin |
convert this code from Julia to Scala:
```julia
function next_greater_element(nums1::Vector{Int}, nums2::Vector{Int})
next_greater = Dict()
stack = []
for num in nums2
while !isempty(stack) && stack[end] < num
next_greater[pop!(stack)] = num
end
push!(stack, num)
end... | dolphin |
Please write the following solution using Ruby:
You are given the `root` of a **full binary tree** with the following properties:
* **Leaf nodes** have either the value `0` or `1`, where `0` represents `False` and `1` represents `True`.
* **Non-leaf nodes** have either the value `2` or `3`, where `2` represents th... | dolphin |
Please write the following solution using Mojo:
You are playing a video game where you are defending your city from a group of `n` monsters. You are given a **0-indexed** integer array `dist` of size `n`, where `dist[i]` is the **initial distance** in kilometers of the `ith` monster from the city.
The monsters walk to... | dolphin |
Please focus on the efficiency of this problem and provide code in Haskell:
There are several squares being dropped onto the X-axis of a 2D plane.
You are given a 2D integer array `positions` where `positions[i] = [lefti, sideLengthi]` represents the `ith` square with a side length of `sideLengthi` that is dropped wit... | dolphin |
translate this code to python:
```elixir
defmodule Solution do
defstruct url_map: %{}, alphabet: String.duplicate("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
def encode(long_url) do
key = generate_key()
%{url_map: map} = %__MODULE__{}
map = Map.put(map, key, long_url)
%{__MODU... | dolphin |
convert this code to TypeScript:
```clojure
(defn recover-tree [node val values]
(if-not node
nil
(do
(aset node 0 val)
(conj values val)
(recover-tree (.left node) (+ val 1) values)
(recover-tree (.right node) (+ val 2) values))))
(defn find-elements [root]
(let [values (atom #{})... | dolphin |
Please focus on the functionality of this problem and provide code in R:
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 + 2*2 + 3*3 + ... | dolphin |
Please explain the following problem in detail and provide code in C#:
You are playing a Flip Game with your friend.
You are given a string `currentState` that contains only `'+'` and `'-'`. You and your friend take turns to flip **two consecutive** `"++ "` into `"-- "`. The game ends when a person can no longer make ... | dolphin |
Please focus on the efficiency of this problem and provide code in R:
The **DNA sequence** is composed of a series of nucleotides abbreviated as `'A'`, `'C'`, `'G'`, and `'T'`.
* For example, `"ACGAATTCCG "` is a **DNA sequence**.
When studying **DNA**, it is useful to identify repeated sequences within the DNA.
G... | dolphin |
Please explain the following problem in detail and provide code in Erlang:
There is a special typewriter with lowercase English letters `'a'` to `'z'` arranged in a **circle** with a **pointer**. A character can **only** be typed if the pointer is pointing to that character. The pointer is **initially** pointing to the... | dolphin |
port this code from Groovy to Scheme:
```groovy
def REACHABLE_NODES(List<List<Integer>> edges, int maxMoves, int n) {
def adjacency_list = create_adjacency_list(edges, n)
def nodes_reachable_from_0 = BFS(adjacency_list, 0, maxMoves)
return nodes_reachable_from_0.size()
}
def BFS(List<List<Integer>> adjacen... | dolphin |
Please focus on the efficiency of this problem and provide code in Julia:
Convert a **Binary Search Tree** to a sorted **Circular Doubly-Linked List** in place.
You can think of the left and right pointers as synonymous to the predecessor and successor pointers in a doubly-linked list. For a circular doubly linked lis... | dolphin |
port this code to TypeScript:
```python
def minSpaceWastedKResizing(nums, k):
n = len(nums)
dp = [[float('inf')] * (k + 1) for _ in range(n + 1)]
sum_nums = [0] * (n + 1)
dp[0][0] = 0
for i in range(1, n + 1):
sum_nums[i] = sum_nums[i - 1] + nums[i - 1]
max_val = nums[i - 1]
... | dolphin |
Please explain the following problem in detail and provide code in TypeScript:
Given an array of strings `words`, return _the first **palindromic** string in the array_. If there is no such string, return _an **empty string**_ `" "`.
A string is **palindromic** if it reads the same forward and backward.
**Example 1:*... | dolphin |
port this code to Objective-C:
```elixir
def is_isomorphic(s, t) do
map1 = %{}
map2 = %{}
for <<char_s::utf8, char_t::utf8>> <- <<s::utf8, t::utf8>> do
case {Map.has_key?(map1, char_s), Map.has_key?(map2, char_t)} do
{false, false} ->
map1 = Map.put(map1, char_s, char_t)
map2 = Map.put(m... | dolphin |
Please focus on the functionality of this problem and provide code in Scheme:
Given an `m x n` matrix `mat`, return _an array of all the elements of the array in a diagonal order_.
**Example 1:**
**Input:** mat = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\]
**Output:** \[1,2,4,7,5,3,6,8,9\]
**Example 2:**
**Input:** mat = \[\... | dolphin |
Please focus on the efficiency of this problem and provide code in F#:
The **median** is the middle value in an ordered integer list. If the size of the list is even, there is no middle value, and the median is the mean of the two middle values.
* For example, for `arr = [2,3,4]`, the median is `3`.
* For example,... | dolphin |
Please explain the reasoning behind the following solution and provide code in TypeScript:
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** o... | dolphin |
Please focus on the efficiency of this problem and provide code in R:
Given a positive integer num, return _the smallest positive integer_ `x` _whose multiplication of each digit equals_ `num`. If there is no answer or the answer is not fit in **32-bit** signed integer, return `0`.
**Example 1:**
**Input:** num = 48
... | dolphin |
Please explain the reasoning behind the following solution and provide code in Dart:
You are given two string arrays, `queries` and `dictionary`. All words in each array comprise of lowercase English letters and have the same length.
In one **edit** you can take a word from `queries`, and change any letter in it to an... | dolphin |
translate this code to Lua:
```elixir
defmodule Solution do
def maximum_value(events) do
n = length(events)
events =
Enum.flat_map(events, fn [start_time, end_time, value] ->
[
{start_time, value},
{end_time + 1, -value}
]
end)
Enum.sort(events, fn {time1, _... | dolphin |
Please explain the following problem in detail and provide code in Rust:
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 com... | dolphin |
Please focus on the efficiency of this problem and provide code in Lua:
A **boolean expression** is an expression that evaluates to either `true` or `false`. It can be in one of the following shapes:
* `'t'` that evaluates to `true`.
* `'f'` that evaluates to `false`.
* `'!(subExpr)'` that evaluates to **the log... | dolphin |
Please write the following solution using Rust:
We have an integer array `arr`, where all the integers in `arr` are equal except for one integer which is **larger** than the rest of the integers. You will not be given direct access to the array, instead, you will have an **API** `ArrayReader` which have the following f... | dolphin |
convert this code from Haskell to Swift:
```haskell
cherryPickup :: [[Int]] -> Int
cherryPickup grid =
let n = length grid
memo = replicate n (replicate n (replicate n (minBound :: Int)))
dp r1 c1 c2 =
let r2 = r1 + c1 - c2
in if r1 == n || r2 == n || c1 == n || c2 == n || gr... | dolphin |
Please explain the reasoning behind the following solution and provide code in c++:
A farmer has a **rectangular grid** of land with `m` rows and `n` columns that can be divided into unit cells. Each cell is either **fertile** (represented by a `1`) or **barren** (represented by a `0`). All cells outside the grid are c... | dolphin |
Please explain the reasoning behind the following solution and provide code in c++:
Given a 2D integer array `circles` where `circles[i] = [xi, yi, ri]` represents the center `(xi, yi)` and radius `ri` of the `ith` circle drawn on a grid, return _the **number of lattice points**_ _that are present inside **at least one... | dolphin |
Please write the following solution using Ruby:
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 _the **minimum** number of operations... | dolphin |
Please focus on the efficiency of this problem and provide code in Mojo:
There is a tree (i.e., a connected, undirected graph that has no cycles) consisting of `n` nodes numbered from `0` to `n - 1` and exactly `n - 1` edges. Each node has a value associated with it, and the **root** of the tree is node `0`.
To repres... | dolphin |
translate this code to Go:
```ruby
class TreeNode
attr_accessor :val, :left, :right
def initialize(val)
@val = val
@left, @right = nil, nil
end
end
def find_nodes_at_distance_k(root, target_val, k)
return [] if k < 0
parent_map = Hash.new(nil)
visited = Set.new
target_node ... | dolphin |
Please focus on the algorithm of this problem and provide code in Julia:
You are given a 2D integer array `intervals` where `intervals[i] = [starti, endi]` represents all the integers from `starti` to `endi` inclusively.
A **containing set** is an array `nums` where each interval from `intervals` has **at least two** ... | dolphin |
Please write the following solution using Mojo:
Your car starts at position `0` and speed `+1` on an infinite number line. Your car can go into negative positions. Your car drives automatically according to a sequence of instructions `'A'` (accelerate) and `'R'` (reverse):
* When you get an instruction `'A'`, your c... | dolphin |
Please explain the reasoning behind the following solution and provide code in Rust:
You are keeping the scores for a baseball game with strange rules. At the beginning of the game, you start with an empty record.
You are given a list of strings `operations`, where `operations[i]` is the `ith` operation you must apply... | dolphin |
translate this code to c++:
```erlang
-module(garden).
-export([maximum_possible_beauty/1]).
maximum_possible_beauty(Flowers) ->
N = length(Flowers),
Sums = [{Flowers[I] + Flowers[J], I, J} || I <- lists:seq(1,N-1), J <- lists:seq(I+1,N)],
SortedSums = lists:sort(Sums, fun({A,_,_}, {B,_,_}) -> A > B end),... | dolphin |
translate this code from Groovy to F#:
```groovy
import java.util.*
List<String> getWatchedVideosByFriends(List<List<String>> watchedVideos, List<List<Integer>> friends, int id, int level) {
def queue = new LinkedList<>()
queue.offer([id, 0])
def visited = [id] as Set<Integer>
def friend_level = [:].wi... | dolphin |
Please focus on the functionality of this problem and provide code in Scheme:
You are given the `root` of a binary tree with **unique** values, and an integer `start`. At minute `0`, an **infection** starts from the node with value `start`.
Each minute, a node becomes infected if:
* The node is currently uninfected... | dolphin |
Please focus on the efficiency of this problem and provide code in Fortran:
Given a string `s` consisting of lowercase English letters, return _the first letter to appear **twice**_.
**Note**:
* A letter `a` appears twice before another letter `b` if the **second** occurrence of `a` is before the **second** occurre... | dolphin |
Please focus on the efficiency of this problem and provide code in Lua:
You are given an integer `n` and an integer `start`.
Define an array `nums` where `nums[i] = start + 2 * i` (**0-indexed**) and `n == nums.length`.
Return _the bitwise XOR of all elements of_ `nums`.
**Example 1:**
**Input:** n = 5, start = 0
*... | dolphin |
Please focus on the functionality of this problem and provide code in Ruby:
You are given a string `text` of words that are placed among some number of spaces. Each word consists of one or more lowercase English letters and are separated by at least one space. It's guaranteed that `text` **contains at least one word**.... | dolphin |
Please explain the reasoning behind the following solution and provide code in Rust:
You are given an array of strings `strs`. You could concatenate these strings together into a loop, where for each string, you could choose to reverse it or not. Among all the possible loops
Return _the lexicographically largest strin... | dolphin |
Please focus on the efficiency of this problem and provide code in Haskell:
Given an integer array `nums`, return _the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle_.
**Example 1:**
**Input:** nums = \[2,2,3,4\]
**Output:** 3
**Explanation:** Valid comb... | dolphin |
translate this code from PHP to Scheme:
```php
function best_poker_hand($ranks, $suits) {
$rank_count = array();
$suit_count = array();
for ($i = 0; $i < 5; $i++) {
$rank_count[$ranks[$i]] = isset($rank_count[$ranks[$i]]) ? $rank_count[$ranks[$i]] + 1 : 1;
$suit_count[$suits[$i]] = isset($su... | dolphin |
Please write the following solution using Mojo:
Given a weighted undirected connected graph with `n` vertices numbered from `0` to `n - 1`, and an array `edges` where `edges[i] = [ai, bi, weighti]` represents a bidirectional and weighted edge between nodes `ai` and `bi`. A minimum spanning tree (MST) is a subset of the... | dolphin |
convert this code to python:
```
function find_min_speed(piles, h)
function can_eat_all(piles, h, k)
local total_hours = 0
for i = 1, #piles do
total_hours = total_hours + math.ceil(piles[i] / k)
end
return total_hours <= h
end
local left = 1
local right ... | dolphin |
Please explain the following problem in detail and provide code in Groovy:
You are given an `n x n` 2D `matrix` representing an image, rotate the image by **90** degrees (clockwise).
You have to rotate the image [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm), which means you have to modify the input ... | dolphin |
convert this code from javascript to R:
```javascript
class TreeNode {
constructor(val, left = null, right = null){
this.val = val;
this.left = left;
this.right = right;
}
}
function inorderTraversalHelper(root, result) {
if (!root) return;
inorderTraversalHelper(root.left, resu... | dolphin |
port this code to Perl:
```csharp
public class Solution {
public int CountValidCombos(string[] pieces, int[][] positions, int index = 0) {
if (index == pieces.Length) {
return 1;
}
int r = positions[index][0];
int c = positions[index][1];
int[] dr = new i... | dolphin |
port this code from R to Erlang:
```R
distinct_rows_from <- function(nums) {
rows <- list()
for (num in nums) {
inserted <- FALSE
for (i in 1:length(rows)) {
if (!(num %in% rows[[i]])) {
rows[[i]] <- c(rows[[i]], num)
inserted <- TRUE
break
}
}
if (!insert... | dolphin |
port this code from Perl to Ruby:
```perl
sub longest_substring {
my ($s) = @_;
my %vowels = ('a' => 0, 'e' => 1, 'i' => 2, 'o' => 3, 'u' => 4);
my @counts = (0, 0, 0, 0, 0);
my %index = (0 => -1);
my $max_len = 0;
for (my $i = 0; $i < length($s); $i++) {
my $ch = substr($s, $i, 1);
... | dolphin |
Please write the following solution using c++:
We want to split a group of `n` people (labeled from `1` to `n`) into two groups of **any size**. Each person may dislike some other people, and they should not go into the same group.
Given the integer `n` and the array `dislikes` where `dislikes[i] = [ai, bi]` indicates... | dolphin |
Please focus on the efficiency of this problem and provide code in Julia:
Given the `root` of a Binary Search Tree (BST), return _the minimum absolute 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 = ... | dolphin |
Please explain the following problem in detail and provide code in Scheme:
In English, we have a concept called **root**, which can be followed by some other word to form another longer word - let's call this word **successor**. For example, when the **root** `"an "` is followed by the **successor** word `"other "`, we... | dolphin |
Please explain the following problem in detail and provide code in Dart:
Given an `m x n` `matrix`, return _`true` if the matrix is Toeplitz. Otherwise, return `false`._
A matrix is **Toeplitz** if every diagonal from top-left to bottom-right has the same elements.
**Example 1:**
**Input:** matrix = \[\[1,2,3,4\],\[... | dolphin |
Please explain the reasoning behind the following solution and provide code in TypeScript:
You are given two **0-indexed** arrays of strings `startWords` and `targetWords`. Each string consists of **lowercase English letters** only.
For each string in `targetWords`, check if it is possible to choose a string from `sta... | dolphin |
Please focus on the functionality of this problem and provide code in Ruby:
There is a new alien language that uses the English alphabet. However, the order among the letters is unknown to you.
You are given a list of strings `words` from the alien language's dictionary, where the strings in `words` are **sorted lexic... | dolphin |
Please focus on the algorithm of this problem and provide code in Perl:
Given an `n x n` binary matrix `grid`, return _the length of the shortest **clear path** in the matrix_. If there is no clear path, return `-1`.
A **clear path** in a binary matrix is a path from the **top-left** cell (i.e., `(0, 0)`) to the **bot... | dolphin |
translate this code to Scheme:
```R
cheapestJump <- function(coins, maxJump){
n <- length(coins)
dp <- rep(Inf, n)
parent <- rep(-1, n)
dp[1] <- coins[1]
for (i in 1:n){
if (coins[i] == -1){
next
}
for (j in 1:maxJump){
if (i + j > n){
next
}
next <- i + j
cos... | dolphin |
convert this code to Erlang:
```php
function removeStones($stones) {
$row_groups = array();
$col_groups = array();
$group_count = 0;
$groups = array();
foreach ($stones as $stone) {
list($x, $y) = $stone;
if (!isset($row_groups[$x])) {
$row_groups[$x] = $group_count;
... | dolphin |
Please focus on the algorithm of this problem and provide code in java:
You are given four integers `row`, `cols`, `rCenter`, and `cCenter`. There is a `rows x cols` matrix and you are on the cell with the coordinates `(rCenter, cCenter)`.
Return _the coordinates of all cells in the matrix, sorted by their **distance*... | dolphin |
port this code to Elixir:
```julia
function maxOperations(nums::Vector{Int}, k::Int)::Int
count = Dict()
operations = 0
for num in nums
if get(count, k - num, 0) > 0
count[k - num] -= 1
operations += 1
else
count[num] = get(count, num, 0) + 1
end
... | dolphin |
convert this code from javascript to Lua:
```javascript
class UnionFind {
constructor(size) {
this.parent = Array.from({length: size}, (_, i) => i);
this.components = size;
}
find(x) {
if (x !== this.parent[x]) {
this.parent[x] = this.find(this.parent[x]);
}
... | dolphin |
Please focus on the efficiency of this problem and provide code in Elixir:
You are given an undirected graph defined by an integer `n`, the number of nodes, and a 2D integer array `edges`, the edges in the graph, where `edges[i] = [ui, vi]` indicates that there is an **undirected** edge between `ui` and `vi`. You are a... | dolphin |
Please write the following solution using Scheme:
Given a non-negative integer `num`, Return its _encoding_ string.
The encoding is done by converting the integer to a string using a secret function that you should deduce from the following table:
**Example 1:**
**Input:** num = 23
**Output:** "1000 "
**Example 2:... | dolphin |
convert this code to F#:
```rust
fn max_sum_of_three_subarrays(nums: &Vec<i32>, k: i32) -> Vec<i32> {
let n = nums.len();
let mut sums = vec![0; n - k as usize + 1];
let mut left = vec![0; n];
let mut right = vec![0; n];
let mut acc_sum = 0;
for i in 0..n {
acc_sum += nums[i];
... | dolphin |
Please explain the following problem in detail and provide code in Scheme:
Design an algorithm that accepts a stream of characters and checks if a suffix of these characters is a string of a given array of strings `words`.
For example, if `words = [ "abc ", "xyz "]` and the stream added the four characters (one by one... | dolphin |
Please focus on the algorithm of this problem and provide code in F#:
Given the `root` of a binary tree, return _the postorder traversal of its nodes' values_.
**Example 1:**
**Input:** root = \[1,null,2,3\]
**Output:** \[3,2,1\]
**Example 2:**
**Input:** root = \[\]
**Output:** \[\]
**Example 3:**
**Input:** roo... | dolphin |
translate this code from Dart to C#:
```dart
List<String> words = ["time", "me", "bell"];
int shortestValidEncoding(List<String> words) {
Trie trie = Trie();
for (String word in words) {
trie.insert(word);
}
return computeShortestReferenceString(trie.root);
}
int computeShortestReferenceString(TrieNode no... | dolphin |
Please explain the reasoning behind the following solution and provide code in Elixir:
Given an integer array `nums` and two integers `lower` and `upper`, return _the number of range sums that lie in_ `[lower, upper]` _inclusive_.
Range sum `S(i, j)` is defined as the sum of the elements in `nums` between indices `i` ... | dolphin |
Please focus on the functionality of this problem and provide code in Groovy:
An attendance record for a student can be represented as a string where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters:
* `'A'`: Absent.
* `'... | dolphin |
Please explain the reasoning behind the following solution and provide code in ANSI C:
You are given an array of `k` linked-lists `lists`, each linked-list is sorted in ascending order.
_Merge all the linked-lists into one sorted linked-list and return it._
**Example 1:**
**Input:** lists = \[\[1,4,5\],\[1,3,4\],\[2... | dolphin |
convert this code from Erlang to ANSI C:
```erlang
subsets(Nums) ->
N = length(Nums),
NumSubsets = 1 bsl N,
Subsets = [],
subsets_loop(0, NumSubsets, N, Nums, Subsets),
Subsets.
subsets_loop(I, NumSubsets, N, Nums, Subsets) when I < NumSubsets ->
Subset = [],
subsets_bits_loop(0, N, I, Nu... | dolphin |
Please explain the following problem in detail and provide code in java:
Given a positive integer `num`, return _the number of positive integers **less than or equal to**_ `num` _whose digit sums are **even**_.
The **digit sum** of a positive integer is the sum of all its digits.
**Example 1:**
**Input:** num = 4
**... | dolphin |
Please write the following solution using java:
There are `8` prison cells in a row and each cell is either occupied or vacant.
Each day, whether the cell is occupied or vacant changes according to the following rules:
* If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becom... | dolphin |
Please explain the following problem in detail and provide code in Clojure:
Given an integer array `nums` of length `n` and an integer `target`, find three integers in `nums` such that the sum is closest to `target`.
Return _the sum of the three integers_.
You may assume that each input would have exactly one solutio... | dolphin |
Please focus on the functionality of this problem and provide code in Julia:
Given two arrays of **unique** digits `nums1` and `nums2`, return _the **smallest** number that contains **at least** one digit from each array_.
**Example 1:**
**Input:** nums1 = \[4,1,3\], nums2 = \[5,7\]
**Output:** 15
**Explanation:** Th... | dolphin |
convert this code from Go to Scheme:
```
package main
import (
"fmt"
"strconv"
)
func findLargest(arr []int) int {
n := len(arr)
l, r := 0, n-1
for l < r {
mid := (l + r) / 2
if (r-l+1)%2 == 0 {
i := compareSub(l, mid, l+1, mid+1)
if i == 1 {
... | dolphin |
Please write the following solution using Object Pascal:
Given an input string `s` and a pattern `p`, implement regular expression matching with support for `'.'` and `'*'` where:
* `'.'` Matches any single character.
* `'*'` Matches zero or more of the preceding element.
The matching should cover the **entir... | dolphin |
Please explain the reasoning behind the following solution and provide code in Rust:
Design the basic function of **Excel** and implement the function of the sum formula.
Implement the `Excel` class:
* `Excel(int height, char width)` Initializes the object with the `height` and the `width` of the sheet. The sheet i... | dolphin |
Please explain the following problem in detail and provide code in Lua:
You are playing a variation of the game Zuma.
In this variation of Zuma, there is a **single row** of colored balls on a board, where each ball can be colored red `'R'`, yellow `'Y'`, blue `'B'`, green `'G'`, or white `'W'`. You also have several ... | dolphin |
translate this code from Scheme to Visual Basic .NET:
```scheme
(define (find-smallest-reachable-set n edges)
(let ((in-degrees (make-vector n 0))
(queue '())
(reachable '()))
(for-each (lambda (edge)
(vector-set! in-degrees (vector-ref edge 1)
(+ (vecto... | dolphin |
port this code to Visual Basic .NET:
```groovy
def mask_information(String s) {
if (s.contains('@')) {
s = s.toLowerCase()
return s[0] + "*****" + s[s.indexOf('@') - 1..-1]
} else {
def digits = s.findAll(/\d+/).join()
if (digits.size() == 10) {
return "***-***-" + di... | dolphin |
Please explain the reasoning behind the following solution and provide code in Scala:
A gene string can be represented by an 8-character long string, with choices from `'A'`, `'C'`, `'G'`, and `'T'`.
Suppose we need to investigate a mutation from a gene string `startGene` to a gene string `endGene` where one mutation ... | dolphin |
Please focus on the efficiency of this problem and provide code in python:
Consider all the leaves of a binary tree, from left to right order, the values of those leaves form a **leaf value sequence**_._
For example, in the given tree above, the leaf value sequence is `(6, 7, 4, 9, 8)`.
Two binary trees are considere... | dolphin |
Please write the following solution using java:
You are given a **0-indexed** integer array `nums` of length `n`.
The **average difference** of the index `i` is the **absolute** **difference** between the average of the **first** `i + 1` elements of `nums` and the average of the **last** `n - i - 1` elements. Both ave... | dolphin |
Please focus on the functionality of this problem and provide code in TypeScript:
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` has... | dolphin |
Please explain the reasoning behind the following solution and provide code in Dart:
Given the `root` of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST.
As a reminder, a _binar... | dolphin |
Please explain the reasoning behind the following solution and provide code in F#:
Given two positive integers `a` and `b`, return _the number of **common** factors of_ `a` _and_ `b`.
An integer `x` is a **common factor** of `a` and `b` if `x` divides both `a` and `b`.
**Example 1:**
**Input:** a = 12, b = 6
**Outpu... | dolphin |
Please explain the reasoning behind the following solution and provide code in Elixir:
Given the `root` of a binary tree, return _the preorder traversal of its nodes' values_.
**Example 1:**
**Input:** root = \[1,null,2,3\]
**Output:** \[1,2,3\]
**Example 2:**
**Input:** root = \[\]
**Output:** \[\]
**Example 3:**... | dolphin |
Please focus on the functionality of this problem and provide code in PHP:
You are given an integer array `nums`. In one operation, you can replace **any** element in `nums` with **any** integer.
`nums` is considered **continuous** if both of the following conditions are fulfilled:
* All elements in `nums` are **un... | dolphin |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.