instruction_seed stringlengths 29 40.5k | source stringclasses 6
values |
|---|---|
Please focus on the functionality of this problem and provide code in Object Pascal:
You are given a string `s` of length `n`, and an integer `k`. You are tasked to find the **longest subsequence repeated** `k` times in string `s`.
A **subsequence** is a string that can be derived from another string by deleting some ... | dolphin |
Please explain the reasoning behind the following solution and provide code in Scheme:
You are given a **positive** integer `n`.
Let `even` denote the number of even indices in the binary representation of `n` (**0-indexed**) with value `1`.
Let `odd` denote the number of odd indices in the binary representation of `... | dolphin |
Please write the following solution using Lua:
Alice and Bob take turns playing a game, with Alice starting first.
Initially, there is a number `n` on the chalkboard. On each player's turn, that player makes a move consisting of:
* Choosing any `x` with `0 < x < n` and `n % x == 0`.
* Replacing the number `n` on ... | dolphin |
Please write the following solution using Clojure:
You are given a **0-indexed** binary string `s` and two integers `minJump` and `maxJump`. In the beginning, you are standing at index `0`, which is equal to `'0'`. You can move from index `i` to index `j` if the following conditions are fulfilled:
* `i + minJump <= ... | dolphin |
Please explain the following problem in detail and provide code in Dart:
You are given an integer `finalSum`. Split it into a sum of a **maximum** number of **unique** positive even integers.
* For example, given `finalSum = 12`, the following splits are **valid** (unique positive even integers summing up to `finalS... | dolphin |
translate this code from C# to ANSI C:
```csharp
public class Node {
public int val;
public Node next;
public Node random;
public Node(int val = 0, Node next = null, Node random = null) {
this.val = val;
this.next = next;
this.random = random;
}
}
public class Solution {
... | dolphin |
Please explain the reasoning behind the following solution and provide code in Objective-C:
You are given a **0-indexed** string `s` consisting of only lowercase English letters, where each letter in `s` appears **exactly** **twice**. You are also given a **0-indexed** integer array `distance` of length `26`.
Each let... | dolphin |
port this code to Objective-C:
```smalltalk
numDecodings: s
| n dp one_digit two_digits |
n := s size.
dp := Array new: n + 1.
dp at: 1 put: (s at: 1) = $0 ifTrue: [0] ifFalse: [1].
dp at: 0 put: 1.
2 to: n + 1 do: [ :i |
one_digit := (s copyFrom: i to: i) asNumber.
two_digi... | dolphin |
convert this code from Lisp to C#:
```lisp
(defun smallest-range (nums)
(let ((min-heap (make-array 0 :adjustable t))
(max-val -1e9)
(list-indices (make-array (length nums) :initial-element 0))
(min-range 1e9)
(start -1)
(end -1))
(dotimes (i (length nums))
(push (lis... | dolphin |
Please write the following solution using java:
You are given two positive integers `n` and `k`. A factor of an integer `n` is defined as an integer `i` where `n % i == 0`.
Consider a list of all factors of `n` sorted in **ascending order**, return _the_ `kth` _factor_ in this list or return `-1` if `n` has less than ... | dolphin |
Please write the following solution using javascript:
There are a total of `numCourses` courses you have to take, labeled from `0` to `numCourses - 1`. You are given an array `prerequisites` where `prerequisites[i] = [ai, bi]` indicates that you **must** take course `bi` first if you want to take course `ai`.
* For ... | dolphin |
translate this code to R:
```typescript
function minDifference(nums: number[]): number {
const n = nums.length / 3;
nums.sort((a, b) => a - b);
let minDiff = Infinity;
for (let i = 0; i <= n; i++) {
const diff = nums[nums.length - i - 1] - nums[i + n - 1];
minDiff = Math.min(minDiff, dif... | dolphin |
Please focus on the efficiency of this problem and provide code in Julia:
A parentheses string is valid if and only if:
* It is the empty string,
* It can be written as `AB` (`A` concatenated with `B`), where `A` and `B` are valid strings, or
* It can be written as `(A)`, where `A` is a valid string.
You are gi... | dolphin |
Please write the following solution using Kotlin:
Given an array of integers `arr` and two integers `k` and `threshold`, return _the number of sub-arrays of size_ `k` _and average greater than or equal to_ `threshold`.
**Example 1:**
**Input:** arr = \[2,2,2,2,5,5,5,8\], k = 3, threshold = 4
**Output:** 3
**Explanati... | dolphin |
Please explain the reasoning behind the following solution and provide code in Groovy:
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... | dolphin |
Please write the following solution using PHP:
Given an array of strings `wordsDict` and two different strings that already exist in the array `word1` and `word2`, return _the shortest distance between these two words in the list_.
**Example 1:**
**Input:** wordsDict = \[ "practice ", "makes ", "perfect ", "coding... | dolphin |
Please explain the following problem in detail and provide code in Groovy:
A positive integer is _magical_ if it is divisible by either `a` or `b`.
Given the three integers `n`, `a`, and `b`, return the `nth` magical number. Since the answer may be very large, **return it modulo** `109 + 7`.
**Example 1:**
**Input:*... | dolphin |
Please explain the reasoning behind the following solution and provide code in R:
You are given a **0-indexed** string `word` of length `n` consisting of digits, and a positive integer `m`.
The **divisibility array** `div` of `word` is an integer array of length `n` such that:
* `div[i] = 1` if the **numeric value*... | dolphin |
convert this code from javascript to Objective-C:
```javascript
class ListNode {
constructor(val, next = null) {
this.val = val;
this.next = next;
}
}
function getIntersectionNode(headA, headB) {
let pA = headA, pB = headB;
while (pA !== pB) {
pA = pA !== null ? pA.next : headB;... | dolphin |
convert this code from Swift to Go:
```swift
func countDays(date1: String, date2: String) -> Int {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
guard let d1 = dateFormatter.date(from: date1),
let d2 = dateFormatter.date(from: date2) else {
return -1 // invali... | dolphin |
translate this code from Swift to Haskell:
```swift
func minMinutes(_ s: String, _ k: Int) -> Int {
let n = s.count
var leftCounts = [Int](repeating: 0, count: 3)
var rightCounts = [Int](repeating: 0, count: 3)
for c in s {
rightCounts[Int(c.asciiValue! - Character("a").asciiValue!)] += 1
}
... | dolphin |
Please focus on the algorithm of this problem and provide code in java:
You are given a list of airline `tickets` where `tickets[i] = [fromi, toi]` represent the departure and the arrival airports of one flight. Reconstruct the itinerary in order and return it.
All of the tickets belong to a man who departs from `"JFK... | dolphin |
translate this code to java:
```haskell
data Node = Node
{ val :: Int
, prev :: Maybe Node
, next :: Maybe Node
, child :: Maybe Node
}
flatten :: Maybe Node -> Maybe Node
flatten Nothing = Nothing
flatten (Just head) =
let go cur prev nextNode =
case cur of
Nothing ... | dolphin |
port this code from Lisp to Mojo:
```lisp
(defun find-root (nodes)
(let ((value-sum 0))
(dolist (node nodes)
(incf value-sum (car node))
(dolist (child (cdr node))
(decf value-sum (car child))))
(dolist (node nodes)
(when (= (car node) value-sum)
(return node)))))
;; Example... | dolphin |
port this code from Lua to F#:
```lua
local MyCircularDeque = {}
MyCircularDeque.__index = MyCircularDeque
function MyCircularDeque.new(k)
local self = setmetatable({}, MyCircularDeque)
self.buffer = {}
for i = 1, k do
self.buffer[i] = 0
end
self.front = -1
self.rear = 0
self.capaci... | dolphin |
Please explain the following problem in detail and provide code in Mojo:
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` ... | dolphin |
Please write the following solution using Visual Basic .NET:
You are given an integer `n`. There is a **complete binary tree** with `2n - 1` nodes. The root of that tree is the node with the value `1`, and every node with a value `val` in the range `[1, 2n - 1 - 1]` has two children where:
* The left node has the va... | dolphin |
translate this code to Object Pascal:
```rust
use std::collections::HashMap;
fn min_absolute_diff(nums: &Vec<i32>, queries: &Vec<Vec<i32>>) -> Vec<i32> {
let n = nums.len();
let mut dp: HashMap<(usize, usize), i32> = HashMap::new();
let dfs = |i: usize, j: usize| -> i32 {
if i > n {
r... | dolphin |
convert this code from python to Go:
```python
class TreeNode:
def __init__(self, left=None, right=None):
self.left = left
self.right = right
def count_nodes(root):
if not root:
return 0
ld = rd = 0
l = r = root
while l:
l = l.left
ld += 1
while r:
... | dolphin |
Please write the following solution using Clojure:
There is a biker going on a road trip. The road trip consists of `n + 1` points at different altitudes. The biker starts his trip on point `0` with altitude equal `0`.
You are given an integer array `gain` of length `n` where `gain[i]` is the **net gain in altitude** ... | dolphin |
Please explain the following problem in detail and provide code in PHP:
Given an integer array `nums`, your goal is to make all elements in `nums` equal. To complete one operation, follow these steps:
1. Find the **largest** value in `nums`. Let its index be `i` (**0-indexed**) and its value be `largest`. If there ar... | dolphin |
port this code from Groovy to javascript:
```groovy
def numberOfGoodSubsequences(String s) {
int[] count = new int[26]
int ans = 0
int MOD = 1000000007
s.each { c ->
count[c - 'a']++
}
count.each { val ->
ans = (ans + (1 << val) - 1) % MOD
}
return ans
}
``... | dolphin |
Please write the following solution using Visual Basic .NET:
You are given a 2D array of axis-aligned `rectangles`. Each `rectangle[i] = [xi1, yi1, xi2, yi2]` denotes the `ith` rectangle where `(xi1, yi1)` are the coordinates of the **bottom-left corner**, and `(xi2, yi2)` are the coordinates of the **top-right corner*... | dolphin |
Please explain the following problem in detail and provide code in Ruby:
You are given an array `nums` of `n` positive integers.
You can perform two types of operations on any element of the array any number of times:
* If the element is **even**, **divide** it by `2`.
* For example, if the array is `[1,2,3,4... | dolphin |
convert this code from R to Erlang:
```R
find_words <- function(words) {
rows <- list(
set("qwertyuiopQWERTYUIOP"),
set("asdfghjklASDFGHJKL"),
set("zxcvbnmZXCVBNM")
)
res <- c()
for (word in words) {
row <- -1
for (i in 1:3) {
if (substring(word, 1, 1) %in% rows[[i]]) {
row <-... | dolphin |
Please write the following solution using c++:
Given an binary array `nums` and an integer `k`, return `true` _if all_ `1`_'s are at least_ `k` _places away from each other, otherwise return_ `false`.
**Example 1:**
**Input:** nums = \[1,0,0,0,1,0,0,1\], k = 2
**Output:** true
**Explanation:** Each of the 1s are at l... | dolphin |
translate this code from c++ to Haskell:
```cpp
int mostFrequentEven(vector<int>& nums) {
unordered_map<int, int> count;
for (int num : nums) {
if (num % 2 == 0) {
count[num]++;
}
}
int max_count = INT_MIN;
int most_frequent = -1;
for (auto& [num, freq] : count) {
... | dolphin |
Please explain the following problem in detail and provide code in Lua:
A positive integer is _magical_ if it is divisible by either `a` or `b`.
Given the three integers `n`, `a`, and `b`, return the `nth` magical number. Since the answer may be very large, **return it modulo** `109 + 7`.
**Example 1:**
**Input:** n... | dolphin |
Please focus on the efficiency of this problem and provide code in javascript:
Given two strings low and high that represent two integers `low` and `high` where `low <= high`, return _the number of **strobogrammatic numbers** in the range_ `[low, high]`.
A **strobogrammatic number** is a number that looks the same whe... | dolphin |
Please focus on the functionality of this problem and provide code in Haskell:
You are given a string `s`, a string `chars` of **distinct** characters and an integer array `vals` of the same length as `chars`.
The **cost of the substring** is the sum of the values of each character in the substring. The cost of an emp... | dolphin |
Please write the following solution using ANSI C:
You are given two positive integer arrays `nums` and `target`, of the same length.
In one operation, you can choose any two **distinct** indices `i` and `j` where `0 <= i, j < nums.length` and:
* set `nums[i] = nums[i] + 2` and
* set `nums[j] = nums[j] - 2`.
Two ... | dolphin |
Please focus on the efficiency of this problem and provide code in Haskell:
A **triplet** is an array of three integers. You are given a 2D integer array `triplets`, where `triplets[i] = [ai, bi, ci]` describes the `ith` **triplet**. You are also given an integer array `target = [x, y, z]` that describes the **triplet*... | dolphin |
Please write the following solution using Visual Basic .NET:
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 your waterin... | dolphin |
Please write the following solution using Fortran:
A message containing letters from `A-Z` can be **encoded** into numbers using the following mapping:
'A' -> "1 "
'B' -> "2 "
...
'Z' -> "26 "
To **decode** an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the ma... | dolphin |
port this code to Lisp:
```perl
sub SubarrayOddSumCount {
my ($arr) = @_;
my $n = scalar(@$arr);
my $count = 0;
my $prefixSum = 0;
my @freq = (0, 0);
$freq[0] = 1;
for (my $i = 0; $i < $n; $i++) {
$prefixSum += $arr->[$i];
my $odd = $prefixSum % 2;
$count += $freq[$od... | dolphin |
Please write the following solution using Perl:
You start at the cell `(rStart, cStart)` of an `rows x cols` grid facing east. The northwest corner is at the first row and column in the grid, and the southeast corner is at the last row and column.
You will walk in a clockwise spiral shape to visit every position in th... | dolphin |
translate this code from TypeScript to python:
```typescript
function canTransform(s: string, t: string): boolean {
if (s.length !== t.length) {
return false;
}
const sArr = s.split('');
const tArr = t.split('');
sArr.sort();
tArr.sort();
return sArr.join('') === tArr.join('');
}
``` | dolphin |
Please focus on the functionality of this problem and provide code in c++:
You are given an integer array `cards` of length `4`. You have four cards, each containing a number in the range `[1, 9]`. You should arrange the numbers on these cards in a mathematical expression using the operators `['+', '-', '*', '/']` and ... | dolphin |
convert this code to Object Pascal:
```perl
use strict;
use warnings;
use List::Util qw(max);
use Data::Dumper;
sub helper {
my ($node, $counts) = @_;
return 0 unless $node;
my $val = $node->{val} + helper($node->{left}, $counts) + helper($node->{right}, $counts);
$counts->{$val}++;
return $val;
}
... | dolphin |
Please explain the reasoning behind the following solution and provide code in Lua:
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:*... | dolphin |
Please write the following solution using TypeScript:
You are given an `m x n` grid `rooms` initialized with these three possible values.
* `-1` A wall or an obstacle.
* `0` A gate.
* `INF` Infinity means an empty room. We use the value `231 - 1 = 2147483647` to represent `INF` as you may assume that the distanc... | dolphin |
Please explain the reasoning behind the following solution and provide code in Haskell:
Given the `root` of a binary tree, return _the same tree where every subtree (of the given tree) not containing a_ `1` _has been removed_.
A subtree of a node `node` is `node` plus every node that is a descendant of `node`.
**Exam... | dolphin |
port this code to C#:
```python
def inorder(node, nodes):
if not node: return
inorder(node.left, nodes)
if nodes[1] and nodes[1].val > node.val:
if not nodes[0]: nodes[0] = nodes[1]
nodes[2] = node
nodes[1] = node
inorder(node.right, nodes)
def recoverTree(root):
nodes = [None, ... | dolphin |
Please explain the following problem in detail and provide code in c++:
You are given an array `rectangles` where `rectangles[i] = [li, wi]` represents the `ith` rectangle of length `li` and width `wi`.
You can cut the `ith` rectangle to form a square with a side length of `k` if both `k <= li` and `k <= wi`. For exam... | dolphin |
translate this code from javascript to Erlang:
```javascript
class TreeNode {
constructor(val) {
this.val = val;
this.left = this.right = null;
}
}
function maxLevelSum(root) {
if (!root) return 0;
let q = [root];
let level = 0, max_sum = -Infinity, result_level = 0;
while (q.... | dolphin |
Please explain the reasoning behind the following solution and provide code in Clojure:
A **critical point** in a linked list is defined as **either** a **local maxima** or a **local minima**.
A node is a **local maxima** if the current node has a value **strictly greater** than the previous node and the next node.
A... | dolphin |
Please write the following solution using Lua:
Given the `root` of a binary tree, return `true` _if you can partition the tree into two trees with equal sums of values after removing exactly one edge on the original tree_.
**Example 1:**
**Input:** root = \[5,10,10,null,null,2,3\]
**Output:** true
**Example 2:**
**... | dolphin |
Please write the following solution using Objective-C:
You are given a **0-indexed** integer array `nums`. In one step, **remove** all elements `nums[i]` where `nums[i - 1] > nums[i]` for all `0 < i < nums.length`.
Return _the number of steps performed until_ `nums` _becomes a **non-decreasing** array_.
**Example 1:*... | dolphin |
translate this code from Julia to R:
```julia
function optimal_division(nums::Vector{Int})
n = length(nums)
if n == 1
return string(nums[1])
elseif n == 2
return string(nums[1]) * "/" * string(nums[2])
else
res = string(nums[1]) * "/("
for i in 2:n-1
res *= st... | dolphin |
Please write the following solution using ANSI C:
Given an array of positive integers `arr`, find a pattern of length `m` that is repeated `k` or more times.
A **pattern** is a subarray (consecutive sub-sequence) that consists of one or more values, repeated multiple times **consecutively** without overlapping. A patt... | dolphin |
Please write the following solution using Clojure:
A city is represented as a **bi-directional connected** graph with `n` vertices where each vertex is labeled from `1` to `n` (**inclusive**). The edges in the graph are represented as a 2D integer array `edges`, where each `edges[i] = [ui, vi]` denotes a bi-directional... | dolphin |
port this code to Julia:
```haskell
productExceptSelf :: [Int] -> [Int]
productExceptSelf nums =
let n = length nums
answer = replicate n 1
lefts = scanl (*) 1 nums
rights = scanr (*) 1 nums
in zipWith (*) lefts (reverse rights)
``` | dolphin |
Please explain the following problem in detail and provide code in Dart:
We are given a list `schedule` of employees, which represents the working time for each employee.
Each employee has a list of non-overlapping `Intervals`, and these intervals are in sorted order.
Return the list of finite intervals representing ... | dolphin |
Please write the following solution using Julia:
There is a robot starting at the position `(0, 0)`, the origin, on a 2D plane. Given a sequence of its moves, judge if this robot **ends up at** `(0, 0)` after it completes its moves.
You are given a string `moves` that represents the move sequence of the robot where `m... | dolphin |
Please focus on the algorithm of this problem and provide code in Lisp:
Write a program to solve a Sudoku puzzle by filling the empty cells.
A sudoku solution must satisfy **all of the following rules**:
1. Each of the digits `1-9` must occur exactly once in each row.
2. Each of the digits `1-9` must occur exactly ... | dolphin |
Please explain the following problem in detail and provide code in Lisp:
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 to the reco... | dolphin |
Please explain the reasoning behind the following solution and provide code in Lisp:
Given two arrays of integers `nums1` and `nums2`, return the number of triplets formed (type 1 and type 2) under the following rules:
* Type 1: Triplet (i, j, k) if `nums1[i]2 == nums2[j] * nums2[k]` where `0 <= i < nums1.length` an... | dolphin |
Please focus on the algorithm of this problem and provide code in Perl:
You are given an integer array `height` of length `n`. There are `n` vertical lines drawn such that the two endpoints of the `ith` line are `(i, 0)` and `(i, height[i])`.
Find two lines that together with the x-axis form a container, such that the... | dolphin |
Please write the following solution using c++:
There are `n` houses evenly lined up on the street, and each house is beautifully painted. You are given a **0-indexed** integer array `colors` of length `n`, where `colors[i]` represents the color of the `ith` house.
Return _the **maximum** distance between **two** house... | dolphin |
port this code from Kotlin to F#:
```kotlin
fun findIntegers(n: Int): Int {
val dp = Array(32) { IntArray(2) }
dp[0][0] = 1
dp[0][1] = 1
for (i in 1 until 32) {
dp[i][0] = dp[i - 1][0] + dp[i - 1][1]
dp[i][1] = dp[i - 1][0]
}
var ans = 0
var prevBit = 0
for (i in 30 dow... | dolphin |
translate this code from Clojure to Swift:
```clojure
(defn recover-array [n sums]
(let [sums (frequencies sums)
ans []]
(while (< (count ans) n)
(if (= (sums 0) 1)
(do (delete sums 0) (conj ans 0))
(let [cur (first (keys sums))]
(delete sums cur)
(let [tmp (reduc... | dolphin |
Please write the following solution using Groovy:
Given the `root` of a binary tree, return _all root-to-leaf paths in **any order**_.
A **leaf** is a node with no children.
**Example 1:**
**Input:** root = \[1,2,3,null,5\]
**Output:** \[ "1->2->5 ", "1->3 "\]
**Example 2:**
**Input:** root = \[1\]
**Output:** \[ ... | dolphin |
Please explain the following problem in detail and provide code in Lua:
You are playing a game of tag with your friends. In tag, people are divided into two teams: people who are "it ", and people who are not "it ". The people who are "it " want to catch as many people as possible who are not "it ".
You are given a **... | dolphin |
port this code from Julia to Dart:
```julia
function check_stack(pushed::Vector{Int}, popped::Vector{Int})
stack = Int[]
i = 1
for element in pushed
push!(stack, element)
while !isempty(stack) && stack[end] == popped[i]
pop!(stack)
i += 1
end
end
isemp... | dolphin |
Please explain the reasoning behind the following solution and provide code in java:
Given an `n x n` array of integers `matrix`, return _the **minimum sum** of any **falling path** through_ `matrix`.
A **falling path** starts at any element in the first row and chooses the element in the next row that is either direc... | dolphin |
translate this code to python:
```cpp
class Fancy {
public:
Fancy() {}
void append(int val) {
sequence.push_back(val);
}
void addAll(int inc) {
for(auto& num : sequence) {
num += inc;
}
}
void multAll(int m) {
for(auto& num : sequence) {
... | dolphin |
Please write the following solution using Fortran:
Given a **sorted** integer array `arr`, two integers `k` and `x`, return the `k` closest integers to `x` in the array. The result should also be sorted in ascending order.
An integer `a` is closer to `x` than an integer `b` if:
* `|a - x| < |b - x|`, or
* `|a - x... | dolphin |
Please focus on the functionality of this problem and provide code in Go:
Given an array `nums` and an integer `target`, return _the maximum number of **non-empty** **non-overlapping** subarrays such that the sum of values in each subarray is equal to_ `target`.
**Example 1:**
**Input:** nums = \[1,1,1,1,1\], target ... | dolphin |
Please focus on the efficiency of this problem and provide code in Elixir:
Given a **positive** integer `n`, return _the smallest positive integer that is a multiple of **both**_ `2` _and_ `n`.
**Example 1:**
**Input:** n = 5
**Output:** 10
**Explanation:** The smallest multiple of both 5 and 2 is 10.
**Example 2:**... | dolphin |
translate this code to Swift:
```csharp
public int CountMatches(string[][] items, string ruleKey, string ruleValue) {
int count = 0;
int index = ruleKey == "type" ? 0 : ruleKey == "color" ? 1 : 2;
foreach(string[] item in items) {
if(item[index] == ruleValue) {
count++;
}
}
... | dolphin |
translate this code from Clojure to Go:
```clojure
(defn get-abbreviation [word]
(let [n (count word)]
(if (<= n 2)
word
(str (first word) (- n 2) (last word)))))
(defn- valid-word-abbr [dictionary]
(reduce (fn [word-map word]
(let [abbr (get-abbreviation word)]
(update wo... | dolphin |
translate this code from Go to Groovy:
```go
func pacificAtlantic(heights [][]int) [][]int {
var dfs func(r, c, prevHeight int, visited [][]bool)
dfs = func(r, c, prevHeight int, visited [][]bool) {
if r < 0 || r >= len(heights) || c < 0 || c >= len(heights[0]) {
return
}
if ... | dolphin |
port this code from C# to Perl:
```csharp
using System.Collections.Generic;
public class Solution {
public int ShortestPathBinaryMatrix(int[][] grid) {
int n = grid.Length;
if (grid[0][0] == 1 || grid[n - 1][n - 1] == 1) return -1;
int[][] dir = new int[][] {new int[] {-1,-1}, new int[] {-... | dolphin |
Please explain the following problem in detail and provide code in Rust:
You are given an array `nums` consisting of **positive** integers.
You can perform the following operation on the array **any** number of times:
* Choose any two **adjacent** elements and **replace** them with their **sum**.
* For exampl... | dolphin |
Please write the following solution using Scheme:
Design a number container system that can do the following:
* **Insert** or **Replace** a number at the given index in the system.
* **Return** the smallest index for the given number in the system.
Implement the `NumberContainers` class:
* `NumberContainers()`... | dolphin |
Please focus on the algorithm of this problem and provide code in javascript:
Given an `m x n` matrix `grid` where each cell is either a wall `'W'`, an enemy `'E'` or empty `'0'`, return _the maximum enemies you can kill using one bomb_. You can only place the bomb in an empty cell.
The bomb kills all the enemies in t... | dolphin |
convert this code to TypeScript:
```ruby
def wonderful_string(word)
count = 0
freq = [0] * 1024
mask = 0
freq[0] = 1
(0...word.length).each do |i|
c = word[i].ord - 'a'.ord
mask ^= 1 << c
count += freq[mask]
(0...10).each do |j|
count += freq[mask ^ (1 << ... | dolphin |
convert this code from R to Groovy:
```R
shortest_distance <- function(words, target, startIndex) {
n <- length(words)
left <- 0
right <- 0
i <- startIndex
while (TRUE) {
if (words[i] == target) {
return(min(left, right))
}
left <- left + 1
right <- right + 1
i <- (i + 1) %% n
if... | dolphin |
Please explain the following problem in detail and provide code in Julia:
You are given an integer array `prices` where `prices[i]` is the price of a given stock on the `ith` day.
On each day, you may decide to buy and/or sell the stock. You can only hold **at most one** share of the stock at any time. However, you ca... | dolphin |
Please focus on the efficiency of this problem and provide code in Erlang:
We are playing the Guessing Game. The game will work as follows:
1. I pick a number between `1` and `n`.
2. You guess a number.
3. If you guess the right number, **you win the game**.
4. If you guess the wrong number, then I will tell you w... | dolphin |
convert this code to Elixir:
```groovy
def inorder(node, nodes) {
if (!node) return
inorder(node.left, nodes)
if (nodes[1] && nodes[1].val > node.val) {
if (!nodes[0]) nodes[0] = nodes[1]
nodes[2] = node
}
nodes[1] = node
inorder(node.right, nodes)
}
def recoverTree(root) {
... | dolphin |
translate this code to Scala:
```fsharp
let decode (encoded: int list) =
let n = encoded.Length + 1
let mutable total_xor = 0
for i in 1..n do
total_xor <- total_xor ^ i
let mutable non_first_xor = 0
for i in 1..2..(n-2) do
non_first_xor <- non_first_xor ^ encoded.[i]
l... | dolphin |
Please write the following solution using PHP:
You are playing a game with integers. You start with the integer `1` and you want to reach the integer `target`.
In one move, you can either:
* **Increment** the current integer by one (i.e., `x = x + 1`).
* **Double** the current integer (i.e., `x = 2 * x`).
You ca... | dolphin |
Please explain the following problem in detail and provide code in Visual Basic .NET:
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 = 2... | dolphin |
Please explain the following problem in detail and provide code in Ruby:
Write a function that reverses a string. The input string is given as an array of characters `s`.
You must do this by modifying the input array [in-place](https://en.wikipedia.org/wiki/In-place_algorithm) with `O(1)` extra memory.
**Example 1:**... | dolphin |
Please explain the reasoning behind the following solution and provide code in Groovy:
You are given a **0-indexed** integer array `nums` of size `n` and a positive integer `k`.
We call an index `i` in the range `k <= i < n - k` **good** if the following conditions are satisfied:
* The `k` elements that are just **... | dolphin |
convert this code to R:
```scala
def countSubArrays(arr: Array[Int], k: Int, threshold: Int): Int = {
val n = arr.length
var count = 0
val prefix_sum = Array.ofDim[Int](n+1)
for (i <- 1 to n) {
prefix_sum(i) = prefix_sum(i-1) + arr(i-1)
}
for (i <- k to n) {
val subarray_sum = prefix_sum(i... | dolphin |
Please write the following solution using Erlang:
You are given two groups of points where the first group has `size1` points, the second group has `size2` points, and `size1 >= size2`.
The `cost` of the connection between any two points are given in an `size1 x size2` matrix where `cost[i][j]` is the cost of connecti... | dolphin |
translate this code to Elixir:
```erlang
-module(stone_game).
-export([optimal_play_alice_wins/1]).
optimal_play_alice_wins(Piles) ->
N = length(Piles),
AliceScore = 0,
lists:foreach(fun(I) ->
lists:foreach(fun(J) ->
AliceScor... | dolphin |
Please focus on the efficiency of this problem and provide code in Perl:
Given an integer array `arr`, remove a subarray (can be empty) from `arr` such that the remaining elements in `arr` are **non-decreasing**.
Return _the length of the shortest subarray to remove_.
A **subarray** is a contiguous subsequence of the... | dolphin |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.