instruction_seed stringlengths 29 40.5k | source stringclasses 6
values |
|---|---|
Please write the following solution using Objective-C:
Design a stack-like data structure to push elements to the stack and pop the most frequent element from the stack.
Implement the `FreqStack` class:
* `FreqStack()` constructs an empty frequency stack.
* `void push(int val)` pushes an integer `val` onto the to... | dolphin |
Please write the following solution using ANSI C:
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**... | dolphin |
Please explain the reasoning behind the following solution and provide code in Visual Basic .NET:
Given the `head` of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return _the reordered list_.
The **first** node is considered **odd**, and the **second*... | dolphin |
Please write the following solution using Scheme:
You are given a **0-indexed** 2D array `grid` of size `2 x n`, where `grid[r][c]` represents the number of points at position `(r, c)` on the matrix. Two robots are playing a game on this matrix.
Both robots initially start at `(0, 0)` and want to reach `(1, n-1)`. Eac... | dolphin |
Please explain the reasoning behind the following solution and provide code in Lisp:
You are given a **binary** string `s` and a positive integer `k`.
You can apply the following operation on the string **any** number of times:
* Choose any substring of size `k` from `s` and **flip** all its characters, that is, tu... | dolphin |
Please focus on the efficiency of this problem and provide code in Groovy:
Given a binary tree `root`, a node _X_ in the tree is named **good** if in the path from root to _X_ there are no nodes with a value _greater than_ X.
Return the number of **good** nodes in the binary tree.
**Example 1:**
**Input:** root = \[... | dolphin |
translate this code to ANSI C:
```swift
func minTime(_ colors: String, _ neededTime: [Int]) -> Int {
var res = 0
var prev = -1
var n = colors.count
let colorsArr = Array(colors)
var neededTimeArr = neededTime
for i in 0..<n-1 {
if colorsArr[i] == colorsArr[i+1] {
if prev... | dolphin |
convert this code from Swift to Perl:
```swift
func findPattern(_ arr: [Int], _ m: Int, _ k: Int) -> Bool {
for i in 0...arr.count - m*k {
let pattern = Array(arr[i..<i+m])
var count = 1
for j in i+m..<arr.count - m + 1 {
if Array(arr[j..<j+m]) == pattern {
count ... | dolphin |
Please write the following solution using Objective-C:
You are given a stream of `n` videos, each represented by a **distinct** number from `1` to `n` that you need to "upload " to a server. You need to implement a data structure that calculates the length of the **longest uploaded prefix** at various points in the upl... | dolphin |
Please explain the following problem in detail and provide code in Rust:
Given the `root` of a binary tree and a `leaf` node, reroot the tree so that the `leaf` is the new root.
You can reroot the tree with the following steps for each node `cur` on the path **starting from the** `leaf` up to the `root` **excluding... | dolphin |
Please explain the reasoning behind the following solution and provide code in Object Pascal:
Given a collection of numbers, `nums`, that might contain duplicates, return _all possible unique permutations **in any order**._
**Example 1:**
**Input:** nums = \[1,1,2\]
**Output:**
\[\[1,1,2\],
\[1,2,1\],
\[2,1,1\]\]
... | dolphin |
Please explain the following problem in detail and provide code in Erlang:
Given two integers `n` and `k`, return _all possible combinations of_ `k` _numbers chosen from the range_ `[1, n]`.
You may return the answer in **any order**.
**Example 1:**
**Input:** n = 4, k = 2
**Output:** \[\[1,2\],\[1,3\],\[1,4\],\[2,3... | dolphin |
Please focus on the efficiency of this problem and provide code in Clojure:
Given an `m x n` integer matrix `grid` where each entry is only `0` or `1`, return _the number of **corner rectangles**_.
A **corner rectangle** is four distinct `1`'s on the grid that forms an axis-aligned rectangle. Note that only the corner... | dolphin |
Please explain the following problem in detail and provide code in java:
Given two strings `s` and `t`, your goal is to convert `s` into `t` in `k` moves or less.
During the `ith` (`1 <= i <= k`) move you can:
* Choose any index `j` (1-indexed) from `s`, such that `1 <= j <= s.length` and `j` has not been chosen in... | dolphin |
Please focus on the functionality of this problem and provide code in F#:
Given a string `s` and an array of strings `words`, determine whether `s` is a **prefix string** of `words`.
A string `s` is a **prefix string** of `words` if `s` can be made by concatenating the first `k` strings in `words` for some **positive*... | dolphin |
Please explain the reasoning behind the following solution and provide code in Kotlin:
You are given an integer `num`. You can swap two digits at most once to get the maximum valued number.
Return _the maximum valued number you can get_.
**Example 1:**
**Input:** num = 2736
**Output:** 7236
**Explanation:** Swap the... | dolphin |
port this code to Mojo:
```cpp
#include <algorithm>
#include <vector>
bool canPlaceBalls(int force, const std::vector<int>& position, int m) {
int last_position = position[0];
int placed_balls = 1;
for (int i = 1; i < position.size(); i++) {
if (position[i] - last_position >= force) {
... | dolphin |
Please explain the reasoning behind the following solution and provide code in Julia:
Given an `m x n` binary grid `grid` where each `1` marks the home of one friend, return _the minimal **total travel distance**_.
The **total travel distance** is the sum of the distances between the houses of the friends and the meet... | dolphin |
Please focus on the efficiency of this problem and provide code in Clojure:
You are given two positive integers `n` and `target`.
An integer is considered **beautiful** if the sum of its digits is less than or equal to `target`.
Return the _minimum **non-negative** integer_ `x` _such that_ `n + x` _is beautiful_. The... | dolphin |
Please explain the reasoning behind the following solution and provide code in Kotlin:
You are given a binary string `binary`. A **subsequence** of `binary` is considered **good** if it is **not empty** and has **no leading zeros** (with the exception of `"0 "`).
Find the number of **unique good subsequences** of `bin... | dolphin |
translate this code from C# to Objective-C:
```csharp
public int NumEnclaves(int[][] grid) {
int m = grid.Length;
int n = grid[0].Length;
int count = 0;
void dfs(int i, int j) {
if (i < 0 || i >= m || j < 0 || j >= n || grid[i][j] == 0) {
return;
}
grid[i][j] = 0;
... | dolphin |
Please explain the following problem in detail and provide code in TypeScript:
A binary watch has 4 LEDs on the top to represent the hours (0-11), and 6 LEDs on the bottom to represent the minutes (0-59). Each LED represents a zero or one, with the least significant bit on the right.
* For example, the below binary ... | dolphin |
Please write the following solution using R:
Given an integer `num`, return _a string representing its hexadecimal representation_. For negative integers, [two's complement](https://en.wikipedia.org/wiki/Two%27s_complement) method is used.
All the letters in the answer string should be lowercase characters, and there ... | dolphin |
port this code to R:
```fsharp
let is_path_crossing (distance:int[]) : bool =
let mutable visited = Set([(0,0)])
let mutable x, y = 0, 0
let directions = [|(0, 1); (-1, 0); (0, -1); (1, 0)|]
for i in 0..distance.Length-1 do
let d = distance.[i]
let (dx, dy) = directions.[i % 4]
f... | dolphin |
Please explain the reasoning behind the following solution and provide code in Fortran:
Your friend is typing his `name` into a keyboard. Sometimes, when typing a character `c`, the key might get _long pressed_, and the character will be typed 1 or more times.
You examine the `typed` characters of the keyboard. Return... | dolphin |
Please explain the reasoning behind the following solution and provide code in F#:
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`.... | dolphin |
Please focus on the algorithm of this problem and provide code in javascript:
Given a Circular Linked List node, which is sorted in non-descending order, write a function to insert a value `insertVal` into the list such that it remains a sorted circular list. The given node can be a reference to any single node in the ... | dolphin |
Please write the following solution using Scheme:
Given a binary array `nums` and an integer `k`, return _the maximum number of consecutive_ `1`_'s in the array if you can flip at most_ `k` `0`'s.
**Example 1:**
**Input:** nums = \[1,1,1,0,0,0,1,1,1,1,0\], k = 2
**Output:** 6
**Explanation:** \[1,1,1,0,0,**1**,1,1,1,... | dolphin |
convert this code from Julia to TypeScript:
```julia
function minimum_perimeter_plot_apples(neededApples::Int)
low = 0
high = 10^6
while low < high
mid = div(low + high, 2)
total_apples = 2 * (mid * (mid + 1)) + (mid - 1) * mid * 2
if total_apples >= neededApples
high = m... | dolphin |
Please explain the reasoning behind the following solution and provide code in ANSI C:
You are given a binary string `binary`. A **subsequence** of `binary` is considered **good** if it is **not empty** and has **no leading zeros** (with the exception of `"0 "`).
Find the number of **unique good subsequences** of `bin... | dolphin |
Please write the following solution using C#:
There is a school that has classes of students and each class will be having a final exam. You are given a 2D integer array `classes`, where `classes[i] = [passi, totali]`. You know beforehand that in the `ith` class, there are `totali` total students, but only `passi` numb... | dolphin |
Please write the following solution using Lua:
You are given a **0-indexed** 2D integer array `grid` of size `m x n` which represents a field. Each cell has one of three values:
* `0` represents grass,
* `1` represents fire,
* `2` represents a wall that you and fire cannot pass through.
You are situated in the ... | dolphin |
Please focus on the functionality of this problem and provide code in Scala:
You are given an integer array `nums` and an integer `k`.
Split the array into some number of non-empty subarrays. The **cost** of a split is the sum of the **importance value** of each subarray in the split.
Let `trimmed(subarray)` be the v... | dolphin |
translate this code from Fortran to Lua:
```fortran
function FOLLOWING_OCCURRENCES(nums, key) result(max_target)
integer, intent(in) :: nums(:), key
integer :: i, max_count, max_target, j
integer, dimension(1000) :: counter
max_count = -1
do i = 1, size(nums)-1
if (nums(i) == key) then
... | dolphin |
translate this code from Erlang to R:
```erlang
is_match(S, P) ->
M = length(S),
N = length(P),
DP = lists:duplicate(M+1, lists:duplicate(N+1, false)),
DP_0 = fun(X) -> lists:nthtail(X, DP) end,
DP_1 = fun(X) -> lists:nth(X, DP) end,
DP_2 = fun(X, Y) -> lists:nth(Y, DP_1(X)) end,
DP_3 = fun(... | dolphin |
Please explain the reasoning behind the following solution and provide code in Erlang:
Given an integer n, return _the **largest palindromic integer** that can be represented as the product of two `n`\-digits integers_. Since the answer can be very large, return it **modulo** `1337`.
**Example 1:**
**Input:** n = 2
*... | dolphin |
Please focus on the algorithm of this problem and provide code in C#:
You are given a **0-indexed** array `nums` consisting of `n` positive integers.
The array `nums` is called **alternating** if:
* `nums[i - 2] == nums[i]`, where `2 <= i <= n - 1`.
* `nums[i - 1] != nums[i]`, where `1 <= i <= n - 1`.
In one **o... | dolphin |
Please explain the reasoning behind the following solution and provide code in PHP:
You are given a 2D `matrix` of size `m x n`, consisting of non-negative integers. You are also given an integer `k`.
The **value** of coordinate `(a, b)` of the matrix is the XOR of all `matrix[i][j]` where `0 <= i <= a < m` and `0 <= ... | dolphin |
Please explain the following problem in detail and provide code in javascript:
There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array `points` where `points[i] = [xstart, xend]` denotes a balloon whose **horizontal diameter** stretches b... | dolphin |
Please explain the reasoning behind the following solution and provide code in PHP:
Given a 2D matrix `matrix`, handle multiple queries of the following type:
* Calculate the **sum** of the elements of `matrix` inside the rectangle defined by its **upper left corner** `(row1, col1)` and **lower right corner** `(row2... | dolphin |
Please write the following solution using Erlang:
You are given an array of unique strings `words` where `words[i]` is six letters long. One word of `words` was chosen as a secret word.
You are also given the helper object `Master`. You may call `Master.guess(word)` where `word` is a six-letter-long string, and it mus... | dolphin |
Please focus on the efficiency of this problem and provide code in Lua:
You are given a positive integer `n` representing the number of nodes in a **connected undirected graph** containing **exactly one** cycle. The nodes are numbered from `0` to `n - 1` (**inclusive**).
You are also given a 2D integer array `edges`, ... | dolphin |
translate this code to Lua:
```rust
use std::rc::Rc;
use std::cell::RefCell;
struct TreeNode {
val: i32,
left: Option<Rc<RefCell<TreeNode>>>,
right: Option<Rc<RefCell<TreeNode>>>,
}
fn search_bst(root: Option<Rc<RefCell<TreeNode>>>, val: i32) -> Option<Rc<RefCell<TreeNode>>> {
match root {
Som... | dolphin |
Please explain the reasoning behind the following solution and provide code in Erlang:
You are in a city that consists of `n` intersections numbered from `0` to `n - 1` with **bi-directional** roads between some intersections. The inputs are generated such that you can reach any intersection from any other intersection... | dolphin |
Please write the following solution using Go:
Given an integer array `nums` and an integer `k`, return _the maximum length of a_ _subarray_ _that sums to_ `k`. If there is not one, return `0` instead.
**Example 1:**
**Input:** nums = \[1,-1,5,-2,3\], k = 3
**Output:** 4
**Explanation:** The subarray \[1, -1, 5, -2\] ... | dolphin |
Please write the following solution using Go:
You are given a **0-indexed** string array `words`, where `words[i]` consists of lowercase English letters.
In one operation, select any index `i` such that `0 < i < words.length` and `words[i - 1]` and `words[i]` are **anagrams**, and **delete** `words[i]` from `words`. K... | dolphin |
Please explain the following problem in detail and provide code in PHP:
You are given two **0-indexed** integer arrays `nums` and `removeQueries`, both of length `n`. For the `ith` query, the element in `nums` at the index `removeQueries[i]` is removed, splitting `nums` into different segments.
A **segment** is a cont... | dolphin |
Please focus on the efficiency of this problem and provide code in Groovy:
You are given a positive integer `n` representing the number of nodes in a **connected undirected graph** containing **exactly one** cycle. The nodes are numbered from `0` to `n - 1` (**inclusive**).
You are also given a 2D integer array `edges... | dolphin |
Please explain the following problem in detail and provide code in python:
An **additive number** is a string whose digits can form an **additive sequence**.
A valid **additive sequence** should contain **at least** three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum... | dolphin |
Please write the following solution using F#:
You are given a binary string `s`. You are allowed to perform two types of operations on the string in any sequence:
* **Type-1: Remove** the character at the start of the string `s` and **append** it to the end of the string.
* **Type-2: Pick** any character in `s` an... | dolphin |
convert this code to Object Pascal:
```lua
local function k_most_frequent(nums, k)
local frequency = {}
local min_heap = {}
for _, num in ipairs(nums) do
frequency[num] = (frequency[num] or 0) + 1
end
for num, freq in pairs(frequency) do
table.insert(min_heap, {freq, num})
... | dolphin |
convert this code from Visual Basic .NET to Fortran:
```vbnet
Imports System
Imports System.Collections.Generic
Module Solution
Public Function MaxEvents(events As List(Of List(Of Integer))) As Integer
events.Sort(Function(x, y) x(0).CompareTo(y(0)))
Dim minHeap As New List(Of Integer)
Dim ... | dolphin |
Please focus on the functionality of this problem and provide code in Lisp:
You are given a positive integer `p`. Consider an array `nums` (**1-indexed**) that consists of the integers in the **inclusive** range `[1, 2p - 1]` in their binary representations. You are allowed to do the following operation **any** number ... | dolphin |
translate this code to ANSI C:
```pascal
function maxAliveYear(logs: array of TPair<Integer, Integer>): Integer;
var
years: array[0..100] of Integer;
i, max_population, max_year: Integer;
begin
for i := Low(years) to High(years) do
years[i] := 0;
for i := Low(logs) to High(logs) do
begin
years[logs[i]... | dolphin |
convert this code from Erlang to c++:
```erlang
-module(matrix_score).
-export([matrix_score/1]).
matrix_score(Grid) ->
M = length(Grid),
N = length(hd(Grid)),
loop_through_rows(Grid, M, N).
loop_through_rows(Grid, M, N) ->
lists:foldl(fun (Row, Acc) ->
if hd(Row) == 0 ->
loop_thr... | dolphin |
Please write the following solution using Lua:
Under the grammar given below, strings can represent a set of lowercase words. Let `R(expr)` denote the set of words the expression represents.
The grammar can best be understood through simple examples:
* Single letters represent a singleton set containing that word.
... | dolphin |
translate this code to Scala:
```c
int absDiffK(int* nums, int numsSize, int k){
int count = 0;
for(int i=0; i<numsSize; i++){
for(int j=i+1; j<numsSize; j++){
if(abs(nums[i]-nums[j])==k){
count++;
}
}
}
return count;
}
``` | dolphin |
translate this code from python to Kotlin:
```python
from collections import defaultdict
def find_duplicate(paths):
content_map = defaultdict(list)
for path in paths:
parts = path.split()
directory = parts[0]
for file in parts[1:]:
start = file.index('(')
end = f... | dolphin |
Please explain the following problem in detail and provide code in Go:
You are given an integer array `nums`. The **absolute sum** of a subarray `[numsl, numsl+1, ..., numsr-1, numsr]` is `abs(numsl + numsl+1 + ... + numsr-1 + numsr)`.
Return _the **maximum** absolute sum of any **(possibly empty)** subarray of_ `nums... | dolphin |
port this code to R:
```lisp
(defun painting-plan (paint)
(let ((worklog (make-list (length paint) :initial-element 0))
(painted (make-hash-table)))
(loop for i below (length paint)
for start = (first (aref paint i))
for end = (second (aref paint i))
do (loop for j from start... | dolphin |
translate this code from ANSI C to Swift:
```
int find_min(int* nums, int length) {
int left = 0;
int right = length - 1;
while (left < right) {
int mid = left + (right - left) / 2;
if (nums[mid] > nums[right]) {
left = mid + 1;
} else {
right = mid;
... | dolphin |
Please explain the following problem in detail and provide code in Objective-C:
Given an integer `n`, return _the **decimal value** of the binary string formed by concatenating the binary representations of_ `1` _to_ `n` _in order, **modulo**_ `109 + 7`.
**Example 1:**
**Input:** n = 1
**Output:** 1
**Explanation: **... | dolphin |
Please focus on the algorithm of this problem and provide code in javascript:
Given a string `s` containing only three types of characters: `'('`, `')'` and `'*'`, return `true` _if_ `s` _is **valid**_.
The following rules define a **valid** string:
* Any left parenthesis `'('` must have a corresponding right paren... | dolphin |
Please explain the following problem in detail and provide code in Scheme:
Design a queue that supports `push` and `pop` operations in the front, middle, and back.
Implement the `FrontMiddleBack` class:
* `FrontMiddleBack()` Initializes the queue.
* `void pushFront(int val)` Adds `val` to the **front** of the que... | dolphin |
translate this code to PHP:
```cpp
#include <vector>
#include <string>
#include <algorithm>
std::string largestMultipleOfThree(std::vector<int>& digits) {
std::sort(digits.rbegin(), digits.rend());
int sum = 0;
for (int digit : digits) {
sum += digit;
}
if (sum % 3 == 0) {
if (digi... | dolphin |
convert this code to F#:
```python
def moveZeroes(nums):
index = 0
for i in range(len(nums)):
if nums[i] != 0:
nums[index] = nums[i]
index += 1
for i in range(index, len(nums)):
nums[i] = 0
```
| dolphin |
Please explain the reasoning behind the following solution and provide code in Go:
Given an array `nums` of integers and integer `k`, return the maximum `sum` such that there exists `i < j` with `nums[i] + nums[j] = sum` and `sum < k`. If no `i`, `j` exist satisfying this equation, return `-1`.
**Example 1:**
**Input... | dolphin |
Please focus on the efficiency of this problem and provide code in Lua:
A **substring** is a contiguous (non-empty) sequence of characters within a string.
A **vowel substring** is a substring that **only** consists of vowels (`'a'`, `'e'`, `'i'`, `'o'`, and `'u'`) and has **all five** vowels present in it.
Given a s... | dolphin |
Please write the following solution using Dart:
You are given two **0-indexed** binary arrays `nums1` and `nums2`. Find the **widest** pair of indices `(i, j)` such that `i <= j` and `nums1[i] + nums1[i+1] + ... + nums1[j] == nums2[i] + nums2[i+1] + ... + nums2[j]`.
The **widest** pair of indices is the pair with the ... | dolphin |
Please explain the following problem in detail and provide code in Fortran:
Given an array of integers `nums`, return _the number of **good pairs**_.
A pair `(i, j)` is called _good_ if `nums[i] == nums[j]` and `i` < `j`.
**Example 1:**
**Input:** nums = \[1,2,3,1,1,3\]
**Output:** 4
**Explanation:** There are 4 goo... | dolphin |
convert this code to Mojo:
```groovy
class TreeNode {
int val
TreeNode left
TreeNode right
TreeNode(int x) {
val = x
}
}
def recoverFromPreorder(String S) {
def helper = {
int numDashes = 0
while (index < S.length() && S.charAt(index) == '-') {
numDashes++
... | dolphin |
Please write the following solution using javascript:
Given the `root` of a binary tree, imagine yourself standing on the **right side** of it, return _the values of the nodes you can see ordered from top to bottom_.
**Example 1:**
**Input:** root = \[1,2,3,null,5,null,4\]
**Output:** \[1,3,4\]
**Example 2:**
**Inp... | dolphin |
Please explain the following problem in detail and provide code in Scala:
You have a data structure of employee information, including the employee's unique ID, importance value, and direct subordinates' IDs.
You are given an array of employees `employees` where:
* `employees[i].id` is the ID of the `ith` employee.... | dolphin |
Please explain the reasoning behind the following solution and provide code in c++:
Given an integer array `nums`, return _the maximum difference between two successive elements in its sorted form_. If the array contains less than two elements, return `0`.
You must write an algorithm that runs in linear time and uses ... | dolphin |
Please explain the following problem in detail and provide code in Groovy:
A **maximum tree** is a tree where every node has a value greater than any other value in its subtree.
You are given the `root` of a maximum binary tree and an integer `val`.
Just as in the [previous problem](https://leetcode.com/problems/maxi... | dolphin |
Please write the following solution using Objective-C:
You are given an array of positive integers `arr`. Perform some operations (possibly none) on `arr` so that it satisfies these conditions:
* The value of the **first** element in `arr` must be `1`.
* The absolute difference between any 2 adjacent elements must... | dolphin |
Please explain the following problem in detail and provide code in C#:
Given a string `num` which represents an integer, return `true` _if_ `num` _is a **strobogrammatic number**_.
A **strobogrammatic number** is a number that looks the same when rotated `180` degrees (looked at upside down).
**Example 1:**
**Input:... | dolphin |
convert this code to PHP:
```
function DetectSquares
points = list()
function add(point)
points.append(point)
function count(point)
count = 0
for (p1, p2) in points:
if p1 != point and p2 != point and p1[0] == point[0] and p2[0] == point[0] and p1[1] < point[1] and p2[1... | dolphin |
Please write the following solution using Erlang:
A binary string is monotone increasing if it consists of some number of `0`'s (possibly none), followed by some number of `1`'s (also possibly none).
You are given a binary string `s`. You can flip `s[i]` changing it from `0` to `1` or from `1` to `0`.
Return _the min... | dolphin |
Please explain the reasoning behind the following solution and provide code in Elixir:
An original string, consisting of lowercase English letters, can be encoded by the following steps:
* Arbitrarily **split** it into a **sequence** of some number of **non-empty** substrings.
* Arbitrarily choose some elements (p... | dolphin |
Please explain the reasoning behind the following solution and provide code in c++:
Roman numerals are represented by seven different symbols: `I`, `V`, `X`, `L`, `C`, `D` and `M`.
**Symbol** **Value**
I 1
V 5
X 10
L 50
C 100
D 500
M ... | dolphin |
Please write the following solution using javascript:
Given a `root` of an N-ary tree, return a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) (clone) of the tree.
Each node in the n-ary tree contains a val (`int`) and a list (`List[Node]`) of its children.
class Node {
public int val;
... | dolphin |
port this code to c++:
```c
#include <stdio.h>
#include <stdlib.h>
int countSubArrays(int* arr, int arrSize, int k, int threshold) {
int count = 0;
int* prefix_sum = (int*)calloc(arrSize+1, sizeof(int));
for(int i=1; i<=arrSize; i++){
prefix_sum[i] = prefix_sum[i-1] + arr[i-1];
}
... | dolphin |
Please explain the reasoning behind the following solution and provide code in PHP:
Given a string `s` consisting only of characters `'a'`, `'b'`, and `'c'`. You are asked to apply the following algorithm on the string any number of times:
1. Pick a **non-empty** prefix from the string `s` where all the characters in... | dolphin |
Please explain the reasoning behind the following solution and provide code in Rust:
You are given an array `nums` consisting of positive integers.
Starting with `score = 0`, apply the following algorithm:
* Choose the smallest integer of the array that is not marked. If there is a tie, choose the one with the smal... | dolphin |
Please explain the reasoning behind the following solution and provide code in Objective-C:
You are given an undirected graph. You are given an integer `n` which is the number of nodes in the graph and an array `edges`, where each `edges[i] = [ui, vi]` indicates that there is an undirected edge between `ui` and `vi`.
... | dolphin |
convert this code from Objective-C to R:
```objective-c
int numberOfWays(int numPeople) {
int const MOD = 1000000007;
int dp[numPeople / 2 + 1];
memset(dp, 0, sizeof(dp));
dp[0] = 1;
for (int i = 1; i <= numPeople / 2; i++) {
for (int j = 1; j <= i; j++) {
dp[i] = (dp[i] + (dp[i ... | dolphin |
Please explain the reasoning behind the following solution and provide code in Go:
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 le... | dolphin |
Please focus on the functionality of this problem and provide code in Go:
You are given two positive integer arrays `nums1` and `nums2`, both of length `n`.
The **absolute sum difference** of arrays `nums1` and `nums2` is defined as the **sum** of `|nums1[i] - nums2[i]|` for each `0 <= i < n` (**0-indexed**).
You can... | dolphin |
Please focus on the functionality of this problem and provide code in Mojo:
You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day.
You want to maximize your profit by choosing a **single day** to buy one stock and choosing a **different day in the future** to sell that stock.... | dolphin |
Please focus on the algorithm of this problem and provide code in Clojure:
Given a list of 24-hour clock time points in **"HH:MM "** format, return _the minimum **minutes** difference between any two time-points in the list_.
**Example 1:**
**Input:** timePoints = \["23:59","00:00"\]
**Output:** 1
**Example 2:**
**... | dolphin |
translate this code from java to Julia:
```java
public boolean canMeasureWater(int jug1Capacity, int jug2Capacity, int targetCapacity) {
if (targetCapacity > jug1Capacity + jug2Capacity) return false;
if (jug1Capacity == targetCapacity || jug2Capacity == targetCapacity
|| jug1Capacity + jug2Capacity ==... | dolphin |
Please focus on the efficiency of this problem and provide code in java:
There is a ball in a `maze` with empty spaces (represented as `0`) and walls (represented as `1`). The ball can go through the empty spaces by rolling **up, down, left or right**, but it won't stop rolling until hitting a wall. When the ball stops... | dolphin |
Please write the following solution using Julia:
Given `n` `points` on a 2D plane where `points[i] = [xi, yi]`, Return _the **widest vertical area** between two points such that no points are inside the area._
A **vertical area** is an area of fixed-width extending infinitely along the y-axis (i.e., infinite height). ... | dolphin |
Please explain the reasoning behind the following solution and provide code in Swift:
You are given a string `s` consisting of lowercase English letters, and an integer `k`.
First, **convert** `s` into an integer by replacing each letter with its position in the alphabet (i.e., replace `'a'` with `1`, `'b'` with `2`, ... | dolphin |
translate this code from python to TypeScript:
```python
from collections import defaultdict
def deleteDuplicateFolder(paths):
graph = defaultdict(set)
count = defaultdict(int)
for path in paths:
serialized_path = ""
for folder in path:
serialized_path += "/" + folder
... | dolphin |
Please explain the reasoning behind the following solution and provide code in java:
Given an integer array `nums`, return _the value of the bitwise_ **OR** _of the sum of all possible **subsequences** in the array_.
A **subsequence** is a sequence that can be derived from another sequence by removing zero or more ele... | dolphin |
translate this code from Julia to Go:
```julia
function lenLongestFibSubseq(arr::Array{Int,1})
index = Dict()
for (i,x) in enumerate(arr)
index[x] = i
end
longest = Dict()
ans = 0
for k in 1:length(arr)
for j in 1:k-1
i = get(index, arr[k] - arr[j], nothing)
... | dolphin |
Please write the following solution using Visual Basic .NET:
There is a row of `n` houses, where each house can be painted one of three colors: red, blue, or green. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color.
... | dolphin |
Please focus on the algorithm of this problem and provide code in R:
You are given a string `s` formed by digits and `'#'`. We want to map `s` to English lowercase characters as follows:
* Characters (`'a'` to `'i'`) are represented by (`'1'` to `'9'`) respectively.
* Characters (`'j'` to `'z'`) are represented by... | dolphin |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.