instruction_seed stringlengths 29 40.5k | source stringclasses 6
values |
|---|---|
Please focus on the efficiency of this problem and provide code in Erlang:
Given an array `nums` of **distinct** positive integers, return _the number of tuples_ `(a, b, c, d)` _such that_ `a * b = c * d` _where_ `a`_,_ `b`_,_ `c`_, and_ `d` _are elements of_ `nums`_, and_ `a != b != c != d`_._
**Example 1:**
**Input... | dolphin |
Please explain the following problem in detail and provide code in javascript:
An array is **squareful** if the sum of every pair of adjacent elements is a **perfect square**.
Given an integer array nums, return _the number of permutations of_ `nums` _that are **squareful**_.
Two permutations `perm1` and `perm2` are ... | dolphin |
convert this code from Rust to Julia:
```rust
use std::collections::HashMap;
struct Node {
val: i32,
next: Option<Box<Node>>,
random: Option<Box<Node>>,
}
impl Node {
fn new(val: i32) -> Self {
Self {
val,
next: None,
random: None,
}
}
}
fn copy... | dolphin |
Please explain the reasoning behind the following solution and provide code in Mojo:
You are given two **0-indexed** integer arrays `fronts` and `backs` of length `n`, where the `ith` card has the positive integer `fronts[i]` printed on the front and `backs[i]` printed on the back. Initially, each card is placed on a t... | dolphin |
translate this code to Lua:
```go
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func timeToInfect(node *TreeNode, start, minutes int) int {
if node == nil {
return 0
}
if node.Val == start {
return minutes
}
return max(timeToInfect(node.Left, start, ... | dolphin |
Please focus on the functionality of this problem and provide code in R:
You are given a positive integer array `skill` of **even** length `n` where `skill[i]` denotes the skill of the `ith` player. Divide the players into `n / 2` teams of size `2` such that the total skill of each team is **equal**.
The **chemistry**... | dolphin |
Please focus on the efficiency of this problem and provide code in Dart:
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 (... | dolphin |
Please focus on the algorithm of this problem and provide code in Rust:
Given an integer array `nums`, design an algorithm to randomly shuffle the array. All permutations of the array should be **equally likely** as a result of the shuffling.
Implement the `Solution` class:
* `Solution(int[] nums)` Initializes the ... | dolphin |
Please explain the reasoning behind the following solution and provide code in Haskell:
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 explain the following problem in detail and provide code in c++:
Given two sorted arrays `nums1` and `nums2` of size `m` and `n` respectively, return **the median** of the two sorted arrays.
The overall run time complexity should be `O(log (m+n))`.
**Example 1:**
**Input:** nums1 = \[1,3\], nums2 = \[2\]
**Ou... | dolphin |
Please explain the following problem in detail and provide code in Dart:
Given a string `s`, find _the longest palindromic **subsequence**'s length in_ `s`.
A **subsequence** is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
*... | dolphin |
Please explain the reasoning behind the following solution and provide code in Lua:
Alice and Bob are traveling to Rome for separate business meetings.
You are given 4 strings `arriveAlice`, `leaveAlice`, `arriveBob`, and `leaveBob`. Alice will be in the city from the dates `arriveAlice` to `leaveAlice` (**inclusive**... | dolphin |
Please write the following solution using Visual Basic .NET:
Given a string `word`, return _the **sum of the number of vowels** (_`'a'`, `'e'`_,_ `'i'`_,_ `'o'`_, and_ `'u'`_)_ _in every substring of_ `word`.
A **substring** is a contiguous (non-empty) sequence of characters within a string.
**Note:** Due to the larg... | dolphin |
Please explain the following problem in detail and provide code in TypeScript:
Given a binary tree where node values are digits from 1 to 9. A path in the binary tree is said to be **pseudo-palindromic** if at least one permutation of the node values in the path is a palindrome.
_Return the number of **pseudo-palindro... | dolphin |
Please explain the following problem in detail and provide code in Erlang:
You are given an array of non-overlapping axis-aligned rectangles `rects` where `rects[i] = [ai, bi, xi, yi]` indicates that `(ai, bi)` is the bottom-left corner point of the `ith` rectangle and `(xi, yi)` is the top-right corner point of the `i... | dolphin |
translate this code to Groovy:
```vb.net
Function IsOneEditDistance(s As String, t As String) As Boolean
Dim m As Integer = s.Length
Dim n As Integer = t.Length
If m > n Then
Return IsOneEditDistance(t, s)
End If
If n - m > 1 Then
Return False
End If
Dim i As Integer = 0
... | dolphin |
Please explain the reasoning behind the following solution and provide code in Elixir:
You are given `nums`, an array of positive integers of size `2 * n`. You must perform `n` operations on this array.
In the `ith` operation **(1-indexed)**, you will:
* Choose two elements, `x` and `y`.
* Receive a score of `i *... | dolphin |
Please explain the following problem in detail and provide code in java:
Given an array of strings `patterns` and a string `word`, return _the **number** of strings in_ `patterns` _that exist as a **substring** in_ `word`.
A **substring** is a contiguous sequence of characters within a string.
**Example 1:**
**Input... | dolphin |
port this code to Elixir:
```
goodStartingIndices <- function(arr) {
n <- length(arr)
nextOdd <- rep(0, n)
nextEven <- rep(0, n)
stack <- numeric()
for (i in 1:n) {
while (length(stack) > 0 && arr[i] > arr[stack[length(stack)]]) {
nextOdd[stack[length(stack)]] <- i
stack <- stack[-length(stack... | dolphin |
translate this code from java to Scala:
```java
public int minCost(int[] nums, int k) {
int n = nums.length;
int[] count = new int[1001], dp = new int[n + 1];
Arrays.fill(dp, Integer.MAX_VALUE);
dp[0] = 0;
for (int i = 0, j = 0; j < n; ++j) {
++count[nums[j]];
if (count[nums[j]] == ... | dolphin |
Please explain the following problem in detail and provide code in Swift:
The Leetcode file system keeps a log each time some user performs a _change folder_ operation.
The operations are described below:
* `"../ "` : Move to the parent folder of the current folder. (If you are already in the main folder, **remain ... | dolphin |
Please explain the reasoning behind the following solution and provide code in Visual Basic .NET:
You are given an undirected weighted graph of `n` nodes (0-indexed), represented by an edge list where `edges[i] = [a, b]` is an undirected edge connecting the nodes `a` and `b` with a probability of success of traversing ... | dolphin |
Please explain the reasoning behind the following solution and provide code in Object Pascal:
You are given a positive integer `n`. Each digit of `n` has a sign according to the following rules:
* The **most significant digit** is assigned a **positive** sign.
* Each other digit has an opposite sign to its adjacen... | dolphin |
Please write the following solution using R:
You are given an array of points in the **X-Y** plane `points` where `points[i] = [xi, yi]`.
Return _the minimum area of any rectangle formed from these points, with sides **not necessarily parallel** to the X and Y axes_. If there is not any such rectangle, return `0`.
An... | dolphin |
Please focus on the functionality of this problem and provide code in Haskell:
You are given two integer arrays `persons` and `times`. In an election, the `ith` vote was cast for `persons[i]` at time `times[i]`.
For each query at a time `t`, find the person that was leading the election at time `t`. Votes cast at time... | dolphin |
Please explain the reasoning behind the following solution and provide code in python:
You are given a string `s`.
A split is called **good** if you can split `s` into two non-empty strings `sleft` and `sright` where their concatenation is equal to `s` (i.e., `sleft + sright = s`) and the number of distinct letters in... | dolphin |
Please explain the following problem in detail and provide code in Clojure:
You are given two strings `s` and `sub`. You are also given a 2D character array `mappings` where `mappings[i] = [oldi, newi]` indicates that you may perform the following operation **any** number of times:
* **Replace** a character `oldi` o... | dolphin |
Please write the following solution using Lua:
Given an integer array `nums` and an integer `k`, return `true` _if there are two **distinct indices**_ `i` _and_ `j` _in the array such that_ `nums[i] == nums[j]` _and_ `abs(i - j) <= k`.
**Example 1:**
**Input:** nums = \[1,2,3,1\], k = 3
**Output:** true
**Example 2:... | dolphin |
Please focus on the algorithm of this problem and provide code in Rust:
Given a `time` represented in the format `"HH:MM "`, form the next closest time by reusing the current digits. There is no limit on how many times a digit can be reused.
You may assume the given input string is always valid. For example, `"01:34 "... | dolphin |
port this code to PHP:
```swift
func countGoodSubstrings(_ s: String) -> Int {
var count = 0
let sArray = Array(s)
let n = sArray.count
for i in 0..<n-2 {
if sArray[i] != sArray[i+1] && sArray[i] != sArray[i+2] && sArray[i+1] != sArray[i+2] {
count += 1
}
}
... | dolphin |
port this code to Fortran:
```fsharp
let findTripletEqualSum (nums: int[]) =
let n = nums.Length
let prefixSum = Array.zeroCreate (n + 1)
for i in 0..n-1 do
prefixSum.[i + 1] <- prefixSum.[i] + nums.[i]
for i in 1..n-3 do
for j in i+2..n-2 do
for k in j+2..n-1 do
... | dolphin |
Please write the following solution using Fortran:
You are given two integer arrays `nums1` and `nums2`. You are tasked to implement a data structure that supports queries of two types:
1. **Add** a positive integer to an element of a given index in the array `nums2`.
2. **Count** the number of pairs `(i, j)` such t... | dolphin |
convert this code from Dart to Object Pascal:
```dart
List<int> intervalFinding(List<List<int>> intervals, List<int> queries) {
intervals.sort((a, b) => a[0].compareTo(b[0]));
List<int> ans = [];
for (int q in queries) {
int minSize = double.infinity.toInt();
for (List<int> interval in intervals) {
... | dolphin |
Please explain the reasoning behind the following solution and provide code in Erlang:
In a garden represented as an infinite 2D grid, there is an apple tree planted at **every** integer coordinate. The apple tree planted at an integer coordinate `(i, j)` has `|i| + |j|` apples growing on it.
You will buy an axis-alig... | dolphin |
Please explain the reasoning behind the following solution and provide code in python:
You are given an `n x n` integer matrix `grid` where each value `grid[i][j]` represents the elevation at that point `(i, j)`.
The rain starts to fall. At time `t`, the depth of the water everywhere is `t`. You can swim from a square... | dolphin |
Please focus on the functionality of this problem and provide code in Lisp:
You are given a floating-point number `hour`, representing the amount of time you have to reach the office. To commute to the office, you must take `n` trains in sequential order. You are also given an integer array `dist` of length `n`, where ... | dolphin |
Please explain the reasoning behind the following solution and provide code in Clojure:
Given a non-negative integer `x`, return _the square root of_ `x` _rounded down to the nearest integer_. The returned integer should be **non-negative** as well.
You **must not use** any built-in exponent function or operator.
* ... | dolphin |
Please focus on the algorithm of this problem and provide code in Scala:
Design and implement a data structure for a [Least Frequently Used (LFU)](https://en.wikipedia.org/wiki/Least_frequently_used) cache.
Implement the `LFUCache` class:
* `LFUCache(int capacity)` Initializes the object with the `capacity` of the ... | dolphin |
Please explain the following problem in detail and provide code in TypeScript:
You are given a **0-indexed** integer array `candies`, where `candies[i]` represents the flavor of the `ith` candy. Your mom wants you to share these candies with your little sister by giving her `k` **consecutive** candies, but you want to ... | dolphin |
Please focus on the functionality of this problem and provide code in Scala:
Given three integers `x`, `y`, and `bound`, return _a list of all the **powerful integers** that have a value less than or equal to_ `bound`.
An integer is **powerful** if it can be represented as `xi + yj` for some integers `i >= 0` and `j >... | dolphin |
Please write the following solution using Lisp:
Given an integer `x`, return `true` _if_ `x` _is a_ _**palindrome**__, and_ `false` _otherwise_.
**Example 1:**
**Input:** x = 121
**Output:** true
**Explanation:** 121 reads as 121 from left to right and from right to left.
**Example 2:**
**Input:** x = -121
**Output... | dolphin |
translate this code to Ruby:
```scheme
(define (rearrange-number-with-minimal-value num)
(define (convert-to-string n)
(number->string n))
(define (convert-to-integer lst)
(string->number (list->string lst)))
(define (sort lst)
(sort lst <))
(define str-num (convert-to-string num))
(define digits ... | dolphin |
Please focus on the efficiency of this problem and provide code in Elixir:
Given a callable function `f(x, y)` **with a hidden formula** and a value `z`, reverse engineer the formula and return _all positive integer pairs_ `x` _and_ `y` _where_ `f(x,y) == z`. You may return the pairs in any order.
While the exact form... | dolphin |
convert this code to Dart:
```scheme
(define (max-and-sum nums num-slots)
(define (max-and-sum-recursive nums num-slots idx used sum)
(cond ((= idx (length nums)) sum)
(else (let ((max-sum 0))
(do ((i 1 (+ i 1)))
((> i (+ num-slots 1)))
(if (no... | dolphin |
convert this code to Erlang:
```cpp
int min_visible_white_tiles(const std::string& floor, int numCarpets, int carpetLen) {
int n = floor.size();
int visible_white_count = 0;
for (int i = 0; i < n; i++) visible_white_count += (floor[i] == '1');
int covered_tiles = 0;
for (int i = 0; i < n; i++) {
... | dolphin |
convert this code to python:
```rust
fn time_crossing_the_door(arrival: Vec<i32>, state: Vec<i32>) -> Vec<i32> {
let n = arrival.len();
let mut answer = vec![0; n];
let mut door_seen_time = [-1, -1];
let mut i = 0;
let mut t = 0;
while i < n {
while t < arrival[i] {
t += 1;
... | dolphin |
Please explain the following problem in detail and provide code in Scala:
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: ** "1 " ... | dolphin |
Please explain the following problem in detail and provide code in Fortran:
Given a `m x n` `grid` filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path.
**Note:** You can only move either down or right at any point in time.
**Example 1:**
... | dolphin |
port this code from Mojo to Lua:
```mojo
sub min_cuts(Int $n) returns Int {
if $n % 2 == 0 {
return $n div 2;
}
else {
return $n;
}
}
``` | dolphin |
translate this code from python to C#:
```python
def min_operations(nums):
nums.sort(reverse=True)
total_sum = sum(nums)
half_sum, operations = 0, 0
for num in nums:
half_sum += num
operations += 1
if half_sum >= (total_sum + 1) // 2:
break
return operations
```
| dolphin |
Please focus on the functionality of this problem and provide code in Perl:
Given a string `expression` of numbers and operators, return _all possible results from computing all the different possible ways to group numbers and operators_. You may return the answer in **any order**.
The test cases are generated such th... | dolphin |
Please explain the following problem in detail and provide code in javascript:
The **power** of the string is the maximum length of a non-empty substring that contains only one unique character.
Given a string `s`, return _the **power** of_ `s`.
**Example 1:**
**Input:** s = "leetcode "
**Output:** 2
**Explanation:... | dolphin |
Please focus on the algorithm of this problem and provide code in Objective-C:
You are given two strings `firstString` and `secondString` that are **0-indexed** and consist only of lowercase English letters. Count the number of index quadruples `(i,j,a,b)` that satisfy the following conditions:
* `0 <= i <= j < firs... | dolphin |
translate this code from Swift to Haskell:
```swift
class Solution {
func braceExpansionII(_ expression: String) -> [String] {
func parse(_ expr: String, _ i: Int) -> Set<String> {
var result = Set<String>(), current = [""]
var i = i
while i < expr.count {
... | dolphin |
Please explain the following problem in detail and provide code in javascript:
You are given an array of integers `nums`. Perform the following steps:
1. Find **any** two **adjacent** numbers in `nums` that are **non-coprime**.
2. If no such numbers are found, **stop** the process.
3. Otherwise, delete the two numb... | dolphin |
Please write the following solution using Objective-C:
There is a restaurant with a single chef. You are given an array `customers`, where `customers[i] = [arrivali, timei]:`
* `arrivali` is the arrival time of the `ith` customer. The arrival times are sorted in **non-decreasing** order.
* `timei` is the time need... | dolphin |
Please write the following solution using Elixir:
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`, ..., `'z'` with `26`). Then, **trans... | dolphin |
Please explain the following problem in detail and provide code in Perl:
You are given an integer array `nums` and an integer `k`. You can partition the array into **at most** `k` non-empty adjacent subarrays. The **score** of a partition is the sum of the averages of each subarray.
Note that the partition must use ev... | dolphin |
translate this code to javascript:
```rust
fn basketball_team_score(scores: Vec<i32>, ages: Vec<i32>) -> i32 {
let n = scores.len();
let mut players: Vec<(i32, i32)> = vec![(0,0); n];
for i in 0..n {
players[i] = (scores[i], ages[i]);
}
players.sort_by(|&(score1, age1), &(score2, age2)| {
... | dolphin |
Please explain the following problem in detail and provide code in python:
Given an `m x n` binary matrix `mat`, return _the number of special positions in_ `mat`_._
A position `(i, j)` is called **special** if `mat[i][j] == 1` and all other elements in row `i` and column `j` are `0` (rows and columns are **0-indexed*... | dolphin |
Please explain the reasoning behind the following solution and provide code in R:
Given the `root` of a binary tree, turn the tree upside down and return _the new root_.
You can turn a binary tree upside down with the following steps:
1. The original left child becomes the new root.
2. The original root becomes the... | dolphin |
Please explain the following problem in detail and provide code in java:
You are given an integer array `nums` and an integer `x`. In one operation, you can either remove the leftmost or the rightmost element from the array `nums` and subtract its value from `x`. Note that this **modifies** the array for future operati... | dolphin |
translate this code from Ruby to Lisp:
```ruby
require 'set'
class Solution
def smallest_string_with_swaps(s, pairs)
n = s.length
p = (0...n).to_a
# Helper method to find the parent of an index
def find(x, p)
p[x] = find(p[x], p) if p[x] != x
p[x]
end
# Union-find, grouping conn... | dolphin |
Please write the following solution using Scala:
For a string `sequence`, a string `word` is **`k`\-repeating** if `word` concatenated `k` times is a substring of `sequence`. The `word`'s **maximum `k`\-repeating value** is the highest value `k` where `word` is `k`\-repeating in `sequence`. If `word` is not a substring... | dolphin |
translate this code from C# to Erlang:
```csharp
public class Solution {
public double MaxAverageRatio(int[][] classes, int extraStudents) {
double low = 0, high = 1;
while (high - low > 1e-6) {
double mid = (low + high) / 2;
double extra = 0;
foreach (int[] c i... | dolphin |
Please focus on the functionality of this problem and provide code in Elixir:
Given the `root` of an n-ary tree, return _the preorder traversal of its nodes' values_.
Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples)
**Exa... | dolphin |
Please explain the following problem in detail and provide code in Visual Basic .NET:
Given two strings `s` and `t`, return `true` _if_ `t` _is an anagram of_ `s`_, and_ `false` _otherwise_.
An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the orig... | dolphin |
translate this code to F#:
```groovy
def findHighestAltitude(int[] gain) {
def maxAltitude = 0
def currentAltitude = 0
for (int i = 0; i < gain.length; i++) {
currentAltitude += gain[i]
if (currentAltitude > maxAltitude) {
maxAltitude = currentAltitude
}
}
return ... | dolphin |
Please explain the reasoning behind the following solution and provide code in python:
Given an `m x n` integer matrix `matrix`, if an element is `0`, set its entire row and column to `0`'s.
You must do it [in place](https://en.wikipedia.org/wiki/In-place_algorithm).
**Example 1:**
**Input:** matrix = \[\[1,1,1\],\[... | dolphin |
Please explain the reasoning behind the following solution and provide code in Clojure:
There is an **undirected** connected tree with `n` nodes labeled from `1` to `n` and `n - 1` edges. You are given the integer `n`. The parent node of a node with a label `v` is the node with the label `floor (v / 2)`. The root of th... | dolphin |
Please focus on the algorithm of this problem and provide code in F#:
Given an array of integers `arr`, you are initially positioned at the first index of the array.
In one step you can jump from index `i` to index:
* `i + 1` where: `i + 1 < arr.length`.
* `i - 1` where: `i - 1 >= 0`.
* `j` where: `arr[i] == ar... | dolphin |
convert this code from Visual Basic .NET to Rust:
```vb.net
Function MinMaxStoneMoves(ByVal a As Integer, ByVal b As Integer, ByVal c As Integer) As Integer()
Dim sortedStones() As Integer = {a, b, c}.OrderBy(Function(n) n).ToArray()
If sortedStones(2) - sortedStones(0) = 2 Then
Return {0, 0}
ElseIf... | dolphin |
Please write the following solution using Clojure:
You are given a string expression representing a Lisp-like expression to return the integer value of.
The syntax for these expressions is given as follows.
* An expression is either an integer, let expression, add expression, mult expression, or an assigned variabl... | dolphin |
Please write the following solution using python:
You are given a **0-indexed** array `nums` of **distinct** integers. You want to rearrange the elements in the array such that every element in the rearranged array is **not** equal to the **average** of its neighbors.
More formally, the rearranged array should have th... | dolphin |
Please explain the following problem in detail and provide code in Haskell:
A [**trie**](https://en.wikipedia.org/wiki/Trie) (pronounced as "try ") or **prefix tree** is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such... | dolphin |
Please explain the following problem in detail and provide code in Ruby:
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 of ... | dolphin |
convert this code from Swift to Objective-C:
```swift
func addBinary(_ a: String, _ b: String) -> String {
var result = ""
var carry = 0
var i = a.count - 1
var j = b.count - 1
while i >= 0 || j >= 0 || carry != 0 {
if i >= 0 {
carry += Int(String(a[a.index(a.startIndex, off... | dolphin |
Please focus on the algorithm of this problem and provide code in F#:
You are given two arrays of strings that represent two inclusive events that happened **on the same day**, `event1` and `event2`, where:
* `event1 = [startTime1, endTime1]` and
* `event2 = [startTime2, endTime2]`.
Event times are valid 24 hours... | dolphin |
Please write the following solution using python:
Given two strings `str1` and `str2`, return _the shortest string that has both_ `str1` _and_ `str2` _as **subsequences**_. If there are multiple valid strings, return **any** of them.
A string `s` is a **subsequence** of string `t` if deleting some number of characters... | dolphin |
port this code to python:
```scheme
(define (magic-beans beans)
(let* ((n (length beans))
(total (apply + beans))
(avg (floor (/ total n)))
(diff 0)
(count 0))
(if (not (= (modulo total n) 0))
-1
(begin
(for-each
(lambda (x)
(s... | dolphin |
Please explain the reasoning behind the following solution and provide code in C#:
You have a list `arr` of all integers in the range `[1, n]` sorted in a strictly increasing order. Apply the following algorithm on `arr`:
* Starting from left to right, remove the first number and every other number afterward until y... | dolphin |
translate this code to Objective-C:
```cpp
#include <vector>
using namespace std;
vector<int> constructArray(int n, int k) {
vector<int> answer(n);
for (int i = 0; i < n; ++i) {
if (i % 2 == 0) {
answer[i] = i / 2 + 1;
} else {
answer[i] = n - (i - 1) / 2;
--... | dolphin |
Please explain the following problem in detail and provide code in Haskell:
Given a binary string `s`, return _the number of substrings with all characters_ `1`_'s_. Since the answer may be too large, return it modulo `109 + 7`.
**Example 1:**
**Input:** s = "0110111 "
**Output:** 9
**Explanation:** There are 9 subs... | dolphin |
Please write the following solution using ANSI C:
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and **it will automatically contact ... | dolphin |
Please focus on the functionality of this problem and provide code in Objective-C:
You are given two **non-increasing 0-indexed** integer arrays `nums1` and `nums2`.
A pair of indices `(i, j)`, where `0 <= i < nums1.length` and `0 <= j < nums2.length`, is **valid** if both `i <= j` and `nums1[i] <= nums2[j... | dolphin |
Please explain the following problem in detail and provide code in javascript:
You are given a **0-indexed** integer array `nums`. You are also given an integer `key`, which is present in `nums`.
For every unique integer `target` in `nums`, **count** the number of times `target` immediately follows an occurrence of `k... | dolphin |
Please explain the following problem in detail and provide code in Rust:
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 |
Please explain the reasoning behind the following solution and provide code in Fortran:
You are given two strings `a` and `b` that consist of lowercase letters. In one operation, you can change any character in `a` or `b` to **any lowercase letter**.
Your goal is to satisfy **one** of the following three conditions:
... | dolphin |
convert this code from Lisp to Lua:
```lisp
(defun replace-words (dict sentence)
(let ((roots (make-hash-table :test 'equal))
(words (split-sequence #\Space sentence)))
(dolist (root dict)
(setf (gethash root roots) t))
(mapconcat (lambda (word)
(let ((prefix "")
... | dolphin |
Please explain the following problem in detail and provide code in Visual Basic .NET:
You are given an array `target` that consists of **distinct** integers and another integer array `arr` that **can** have duplicates.
In one operation, you can insert any integer at any position in `arr`. For example, if `arr = [1,4,1... | dolphin |
translate this code to TypeScript:
```c
#include <stdio.h>
#include <string.h>
#define MOD 1000000007
int numDecodings(char* s, int k) {
int n = strlen(s);
int dp[n + 1];
memset(dp, 0, sizeof(dp));
dp[n] = 1;
for (int i = n - 1; i >= 0; i--) {
int num = 0;
for (int j = i; j < n; j... | dolphin |
Please focus on the algorithm of this problem and provide code in Fortran:
Given an integer array nums, return all the triplets `[nums[i], nums[j], nums[k]]` such that `i != j`, `i != k`, and `j != k`, and `nums[i] + nums[j] + nums[k] == 0`.
Notice that the solution set must not contain duplicate triplets.
**Example ... | dolphin |
Please focus on the efficiency of this problem and provide code in Lisp:
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 equal to the su... | dolphin |
Please focus on the algorithm of this problem and provide code in Go:
Given an array `nums` of integers, return how many of them contain an **even number** of digits.
**Example 1:**
**Input:** nums = \[12,345,2,6,7896\]
**Output:** 2
**Explanation:**
12 contains 2 digits (even number of digits).
345 contains 3 digi... | dolphin |
Please explain the reasoning behind the following solution and provide code in Perl:
Given an integer `num`, return _the number of digits in `num` that divide_ `num`.
An integer `val` divides `nums` if `nums % val == 0`.
**Example 1:**
**Input:** num = 7
**Output:** 1
**Explanation:** 7 divides itself, hence the ans... | dolphin |
Please write the following solution using R:
You have `n` super washing machines on a line. Initially, each washing machine has some dresses or is empty.
For each move, you could choose any `m` (`1 <= m <= n`) washing machines, and pass one dress of each washing machine to one of its adjacent washing machines at the s... | dolphin |
Please explain the following problem in detail and provide code in ANSI C:
There is an undirected tree with `n` nodes labeled from `0` to `n - 1`.
You are given a **0-indexed** integer array `nums` of length `n` where `nums[i]` represents the value of the `ith` node. You are also given a 2D integer array `edges` of le... | dolphin |
Please explain the following problem in detail and provide code in TypeScript:
Given a **zero-based permutation** `nums` (**0-indexed**), build an array `ans` of the **same length** where `ans[i] = nums[nums[i]]` for each `0 <= i < nums.length` and return it.
A **zero-based permutation** `nums` is an array of **distin... | dolphin |
port this code to ANSI C:
```rust
fn maximize_sum(matrix: &Vec<Vec<i32>>) -> i32 {
let n = matrix.len();
let mut sum = 0;
let mut negatives = 0;
let mut min_val = std::i32::MAX;
for i in 0..n {
for j in 0..n {
let curr_val = matrix[i][j];
let absolute_val = curr_... | dolphin |
Please write the following solution using Scala:
Given the `head` of a linked list, reverse the nodes of the list `k` at a time, and return _the modified list_.
`k` is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of `k` then left-out nodes, in ... | dolphin |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.