instruction_seed stringlengths 29 40.5k | source stringclasses 6
values |
|---|---|
port this code to Scheme:
```dart
int removeElement(List<int> nums, int val) {
int i = 0;
for (int j = 0; j < nums.length; j++) {
if (nums[j] != val) {
nums[i] = nums[j];
i++;
}
}
return i;
}
``` | dolphin |
Please explain the following problem in detail and provide code in Scala:
There are `n` friends that are playing a game. The friends are sitting in a circle and are numbered from `1` to `n` in **clockwise order**. More formally, moving clockwise from the `ith` friend brings you to the `(i+1)th` friend for `1 <= i < n`,... | dolphin |
Please focus on the efficiency of this problem and provide code in Go:
You have `n` tasks and `m` workers. Each task has a strength requirement stored in a **0-indexed** integer array `tasks`, with the `ith` task requiring `tasks[i]` strength to complete. The strength of each worker is stored in a **0-indexed** integer... | dolphin |
translate this code from Erlang to Julia:
```erlang
min_moves(Grid) ->
N = length(Grid),
case lists:nth(3, lists:nth(1, Grid)) of
1 -> -1;
_ -> Q = [{0, 0, 0, 1}], % (row1, col1, row2, col2)
Visited = sets:new([Q]),
Moves = 0,
min_moves(Q, Visited, Moves, N... | dolphin |
Please focus on the algorithm of this problem and provide code in Ruby:
You have an `inventory` of different colored balls, and there is a customer that wants `orders` balls of **any** color.
The customer weirdly values the colored balls. Each colored ball's value is the number of balls **of that color** you currently... | dolphin |
Please focus on the efficiency of this problem and provide code in Dart:
Given an `m x n` integer matrix `heightMap` representing the height of each unit cell in a 2D elevation map, return _the volume of water it can trap after raining_.
**Example 1:**
**Input:** heightMap = \[\[1,4,3,1,3,2\],\[3,2,1,3,2,4\],\[2,3,3,... | dolphin |
Please explain the following problem in detail and provide code in Elixir:
There is an undirected connected tree with `n` nodes labeled from `0` to `n - 1` and `n - 1` edges.
You are given the integer `n` and the array `edges` where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi` in t... | dolphin |
Please focus on the efficiency of this problem and provide code in Lisp:
You are given an `m x n` integer array `grid`. There is a robot initially located at the **top-left corner** (i.e., `grid[0][0]`). The robot tries to move to the **bottom-right corner** (i.e., `grid[m - 1][n - 1]`). The robot can only move either ... | dolphin |
translate this code to javascript:
```python
def longestOnes(nums, k):
left, right, max_ones, zero_count = 0, 0, 0, 0
while right < len(nums):
if nums[right] == 0:
zero_count += 1
while zero_count > k:
if nums[left] == 0:
zero_count -= 1
left +... | dolphin |
convert this code to Groovy:
```go
func firstUniqChar(s string) int {
charCount := make(map[rune]int)
for _, c := range s {
charCount[c]++
}
for i, c := range s {
if charCount[c] == 1 {
return i
}
}
return -1
}
``` | dolphin |
Please explain the following problem in detail and provide code in java:
You are given a **0-indexed** array of non-negative integers `nums`. For each integer in `nums`, you must find its respective **second greater** integer.
The **second greater** integer of `nums[i]` is `nums[j]` such that:
* `j > i`
* `nums[j... | dolphin |
Please explain the following problem in detail and provide code in Scala:
You have a cubic storeroom where the width, length, and height of the room are all equal to `n` units. You are asked to place `n` boxes in this room where each box is a cube of unit side length. There are however some rules to placing the boxes:
... | dolphin |
Please explain the following problem in detail and provide code in C#:
Given four integer arrays `nums1`, `nums2`, `nums3`, and `nums4` all of length `n`, return the number of tuples `(i, j, k, l)` such that:
* `0 <= i, j, k, l < n`
* `nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0`
**Example 1:**
**Input:** num... | dolphin |
Please focus on the functionality of this problem and provide code in java:
You are given a positive integer **0-indexed** array `nums`.
A subset of the array `nums` is **square-free** if the product of its elements is a **square-free integer**.
A **square-free integer** is an integer that is divisible by no square n... | dolphin |
Please explain the following problem in detail and provide code in Objective-C:
Given a string `s`, remove duplicate letters so that every letter appears once and only once. You must make sure your result is **the smallest in lexicographical order** among all possible results.
**Example 1:**
**Input:** s = "bcabc "
... | dolphin |
translate this code from c++ to Rust:
```cpp
int maxChunksToSorted(vector<int>& arr) {
int max_val = 0, chunks = 0;
for (int i = 0; i < arr.size(); ++i) {
max_val = max(max_val, arr[i]);
if (max_val == i) {
chunks++;
}
}
return chunks;
}
```
| dolphin |
Please explain the following problem in detail and provide code in ANSI C:
Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (`push`, `peek`, `pop`, and `empty`).
Implement the `MyQueue` class:
* `void push(int x)` Pushes elem... | dolphin |
Please write the following solution using Rust:
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 <= j <= b < n` **(0-indexed)**.
Find t... | dolphin |
port this code from Object Pascal to Ruby:
```pascal
function SortNamesByHeight(names: array of string; heights: array of integer): array of string;
type
TNameHeightPair = record
Name: string;
Height: integer;
end;
var
NameHeightPairs: array of TNameHeightPair;
i: integer;
begin
SetLength(NameHeightPa... | dolphin |
Please focus on the efficiency of this problem and provide code in SmallTalk:
You are given two string arrays, `queries` and `dictionary`. All words in each array comprise of lowercase English letters and have the same length.
In one **edit** you can take a word from `queries`, and change any letter in it to any other... | dolphin |
convert this code to TypeScript:
```Perl
use strict;
use warnings;
use feature 'say';
use Data::Dumper;
use List::Util qw(max);
package TreeNode {
use Moose;
has 'val' => (is => 'ro', isa => 'Int');
has 'left' => (is => 'rw', isa => 'Maybe[TreeNode]');
has 'right' => (is => 'rw', isa => 'Maybe[TreeNode... | dolphin |
translate this code to Kotlin:
```typescript
function partitionWithScore(nums: number[], k: number): number {
const n = nums.length;
const dp: number[][] = Array.from({ length: n }, () => Array(k).fill(0));
for (let i = 0; i < n; i++) {
dp[i][0] = nums.slice(0, i + 1).reduce((a, b) => a + b, 0)... | dolphin |
Please explain the following problem in detail and provide code in java:
You have some apples and a basket that can carry up to `5000` units of weight.
Given an integer array `weight` where `weight[i]` is the weight of the `ith` apple, return _the maximum number of apples you can put in the basket_.
**Example 1:**
*... | dolphin |
translate this code from Ruby to Kotlin:
```ruby
def max_score(nums)
nums.sort!
result, prefix_sum = 0, 0
nums.each do |num|
if prefix_sum + num > 0
result += 1
prefix_sum += num
end
end
return result
end
``` | dolphin |
port this code to F#:
```kotlin
fun minOperations(target: IntArray, initial: IntArray): Int {
val n = target.size
var operations = 0
for (i in 0 until n) {
var diff = target[i] - initial[i]
if (diff > 0) {
for (j in i until n) {
if (initial[j] < target[j] && ini... | dolphin |
Please explain the following problem in detail and provide code in python:
Given an integer `n`, return _all the structurally unique **BST'**s (binary search trees), which has exactly_ `n` _nodes of unique values from_ `1` _to_ `n`. Return the answer in **any order**.
**Example 1:**
**Input:** n = 3
**Output:** \[\[1... | dolphin |
Please focus on the algorithm of this problem and provide code in TypeScript:
Numbers can be regarded as the product of their factors.
* For example, `8 = 2 x 2 x 2 = 2 x 4`.
Given an integer `n`, return _all possible combinations of its factors_. You may return the answer in **any order**.
**Note** that the facto... | dolphin |
Please write the following solution using Erlang:
Given an integer array `nums` of length `n` and an integer `target`, find three integers in `nums` such that the sum is closest to `target`.
Return _the sum of the three integers_.
You may assume that each input would have exactly one solution.
**Example 1:**
**Inpu... | dolphin |
translate this code from java to Ruby:
```java
public int findSubstringInWraproundString(String p) {
int[] cnt = new int[26];
int length = 0;
for (int i = 0; i < p.length(); i++) {
if (i > 0 && (p.charAt(i) == p.charAt(i - 1) + 1 || p.charAt(i - 1) - p.charAt(i) == 25)) {
length++;
... | dolphin |
Please focus on the efficiency of this problem and provide code in ANSI C:
Given a **1-indexed** array of integers `numbers` that is already **_sorted in non-decreasing order_**, find two numbers such that they add up to a specific `target` number. Let these two numbers be `numbers[index1]` and `numbers[index2]` where ... | dolphin |
translate this code from Scala to Mojo:
```scala
def validSquare(p1: Array[Int], p2: Array[Int], p3: Array[Int], p4: Array[Int]): Boolean = {
def dist_sq(p: Array[Int], q: Array[Int]): Int = {
(p(0) - q(0)) * (p(0) - q(0)) + (p(1) - q(1)) * (p(1) - q(1))
}
val points = Array(p1, p2, p3, p4)
val dists = c... | dolphin |
Please explain the following problem in detail and provide code in C#:
The **Fibonacci numbers**, commonly denoted `F(n)` form a sequence, called the **Fibonacci sequence**, such that each number is the sum of the two preceding ones, starting from `0` and `1`. That is,
F(0) = 0, F(1) = 1
F(n) = F(n - 1) + F(n - 2), fo... | dolphin |
translate this code to TypeScript:
```fortran
recursive function decimal_value_of_binary_string(n) result(res)
integer, intent(in) :: n
integer :: mod = 1000000007, res = 0, length = 0, i, k
do i = 1, n
k = i
do while (k > 0)
res = mod(mod(res * 2 + mod(k, 2)))
k = k ... | dolphin |
Please explain the reasoning behind the following solution and provide code in Dart:
Given an `m x n` binary matrix `mat`, return _the distance of the nearest_ `0` _for each cell_.
The distance between two adjacent cells is `1`.
**Example 1:**
**Input:** mat = \[\[0,0,0\],\[0,1,0\],\[0,0,0\]\]
**Output:** \[\[0,0,0\... | dolphin |
port this code from PHP to Visual Basic .NET:
```php
function minimumTotalCost($n, $highways, $discounts) {
$graph = [];
for($i=0;$i<$n;$i++) {
$graph[$i] = [];
}
foreach($highways as $highway) {
$graph[$highway[0]][$highway[1]] = $highway[2];
$graph[$highway[1]][$highway[0]] = $... | dolphin |
Please explain the reasoning behind the following solution and provide code in C#:
Given two strings `s` and `t`, return _the number of distinct_ **_subsequences_** _of_ `s` _which equals_ `t`.
The test cases are generated so that the answer fits on a 32-bit signed integer.
**Example 1:**
**Input:** s = "rabbbit ",... | dolphin |
convert this code to PHP:
```
function isToeplitzMatrix(matrix: array of array of char): boolean;
var
rows, cols, i, j: integer;
begin
rows := Length(matrix);
cols := Length(matrix[0]);
for i := 0 to rows - 2 do
begin
for j := 0 to cols - 2 do
begin
if matrix[i][j] <> matrix[i+1][j+1] then
... | dolphin |
convert this code from Dart to java:
```Dart
import 'dart:collection';
List<int> sumOfDistancesInTree(int n, List<List<int>> edges) {
Map<int, Set<int>> tree = Map<int, Set<int>>.fromIterable(
List<int>.generate(n, (i) => i),
key: (i) => i,
value: (_) => Set<int>());
for (var edge in edges) {
... | dolphin |
Please explain the reasoning behind the following solution and provide code in c++:
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 ... | dolphin |
Please focus on the efficiency of this problem and provide code in SmallTalk:
You are given a **0-indexed** string `expression` of the form `"+ "` where and represent positive integers.
Add a pair of parentheses to `expression` such that after the addition of parentheses, `expression` is a **valid** mathematical expre... | dolphin |
Please focus on the functionality of this problem and provide code in Lisp:
The **value** of an alphanumeric string can be defined as:
* The **numeric** representation of the string in base `10`, if it comprises of digits **only**.
* The **length** of the string, otherwise.
Given an array `strs` of alphanumeric s... | dolphin |
Please write the following solution using Visual Basic .NET:
Given an integer `n` represented as a string, return _the smallest **good base** of_ `n`.
We call `k >= 2` a **good base** of `n`, if all digits of `n` base `k` are `1`'s.
**Example 1:**
**Input:** n = "13 "
**Output:** "3 "
**Explanation:** 13 base 3 is... | dolphin |
Please focus on the functionality of this problem and provide code in Clojure:
Given an array of integers `nums` sorted in non-decreasing order, find the starting and ending position of a given `target` value.
If `target` is not found in the array, return `[-1, -1]`.
You must write an algorithm with `O(log n)` runtim... | dolphin |
Please explain the reasoning behind the following solution and provide code in C#:
You are given an integer array `nums` that is **sorted in non-decreasing order**.
Determine if it is possible to split `nums` into **one or more subsequences** such that **both** of the following conditions are true:
* Each subsequen... | dolphin |
Please focus on the algorithm of this problem and provide code in Objective-C:
In an `n*n` grid, there is a snake that spans 2 cells and starts moving from the top left corner at `(0, 0)` and `(0, 1)`. The grid has empty cells represented by zeros and blocked cells represented by ones. The snake wants to reach the lowe... | dolphin |
convert this code to Clojure:
```ruby
def sum_of_digits(nums)
min_val = nums.min
digit_sum = min_val.to_s.chars.map(&:to_i).sum
digit_sum % 2 == 0 ? 1 : 0
end
``` | dolphin |
port this code to Julia:
```haskell
maxBeauty :: [(Int,Int)] -> [Int] -> [Int]
maxBeauty items queries =
let sortedItems = replicate 10001 0
setMaxBeauty (p,b) =
sortedItems !! p = max (sortedItems !! p) b
setMaxBeautyForRange i =
sortedItems !! i = max (sortedItems !! i) (sortedItems !! (... | dolphin |
Please write the following solution using Fortran:
There is a group of `n` members, and a list of various crimes they could commit. The `ith` crime generates a `profit[i]` and requires `group[i]` members to participate in it. If a member participates in one crime, that member can't participate in another crime.
Let's ... | dolphin |
Please explain the following problem in detail and provide code in Visual Basic .NET:
Given a binary tree `root` and a linked list with `head` as the first node.
Return True if all the elements in the linked list starting from the `head` correspond to some _downward path_ connected in the binary tree otherwise return ... | dolphin |
Please focus on the functionality of this problem and provide code in Ruby:
The thief has found himself a new place for his thievery again. There is only one entrance to this area, called `root`.
Besides the `root`, each house has one and only one parent house. After a tour, the smart thief realized that all houses in... | dolphin |
Please write the following solution using Elixir:
An integer array `original` is transformed into a **doubled** array `changed` by appending **twice the value** of every element in `original`, and then randomly **shuffling** the resulting array.
Given an array `changed`, return `original` _if_ `changed` _is a **double... | dolphin |
port this code to Lua:
```cpp
int count_odds(int low, int high) {
return (high - low) / 2 + ((low % 2 == 1 || high % 2 == 1) ? 1 : 0);
}
```
| dolphin |
Please explain the reasoning behind the following solution and provide code in Julia:
You are given two positive integer arrays `spells` and `potions`, of length `n` and `m` respectively, where `spells[i]` represents the strength of the `ith` spell and `potions[j]` represents the strength of the `jth` potion.
You are ... | dolphin |
Please explain the following problem in detail and provide code in ANSI 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 integ... | dolphin |
convert this code to Haskell:
```fsharp
let countTriplets(nums: int[]) =
let mutable count = 0
let n = nums.Length
let sortedNums = nums |> Array.sort
for i = 0 to n-3 do
let mutable j = i+1
let mutable k = n-1
while j < k do
if sortedNums.[i] <> sortedNums.[j] &... | dolphin |
Please explain the following problem in detail and provide code in Visual Basic .NET:
You are given a string `s` that contains digits `0-9`, addition symbols `'+'`, and multiplication symbols `'*'` **only**, representing a **valid** math expression of **single digit numbers** (e.g., `3+5*2`). This expression was given ... | dolphin |
translate this code to Clojure:
```perl
sub min_race_time {
my ($tires, $changeTime, $numLaps) = @_;
my $n = scalar @$tires;
my @total_time;
for (my $i = 0; $i < $n; $i++) {
$total_time[$i][0] = $tires->[$i][0];
}
for (my $i = 1; $i <= $numLaps; $i++) {
for (my $j = 0; $j < $n; $... | dolphin |
Please write the following solution using Dart:
You are given two **positive** integers `startPos` and `endPos`. Initially, you are standing at position `startPos` on an **infinite** number line. With one step, you can move either one position to the left, or one position to the right.
Given a positive integer `k`, re... | dolphin |
Please write the following solution using Rust:
You are given an integer `n`, which indicates that there are `n` courses labeled from `1` to `n`. You are also given a 2D integer array `relations` where `relations[j] = [prevCoursej, nextCoursej]` denotes that course `prevCoursej` has to be completed **before** course `n... | dolphin |
Please explain the following problem in detail and provide code in Elixir:
Given an integer array `nums` and an integer `k`, return `true` if it is possible to divide this array into `k` non-empty subsets whose sums are all equal.
**Example 1:**
**Input:** nums = \[4,3,2,3,5,2,1\], k = 4
**Output:** true
**Explanatio... | dolphin |
Please explain the reasoning behind the following solution and provide code in Clojure:
There is a tree (i.e., a connected, undirected graph with no cycles) structure country network consisting of `n` cities numbered from `0` to `n - 1` and exactly `n - 1` roads. The capital city is city `0`. You are given a 2D integer... | dolphin |
convert this code from javascript to Mojo:
```javascript
function numberOfWays(n, m, k, mod = 1_000_000_007) {
if (k > 1) {
let result = 1;
for (let i = 0; i < n; ++i) {
result = (result * m) % mod;
}
return result;
}
return n % 2 === 0 ? 1 : m;
}
```
| dolphin |
Please focus on the functionality of this problem and provide code in Go:
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... | dolphin |
Please explain the reasoning behind the following solution and provide code in Julia:
You are given two integers `m` and `n`. Consider an `m x n` grid where each cell is initially white. You can paint each cell **red**, **green**, or **blue**. All cells **must** be painted.
Return _the number of ways to color the grid... | dolphin |
Please focus on the algorithm of this problem and provide code in Haskell:
Given an integer array `nums` and an integer `k`, return _the number of non-empty **subarrays** that have a sum divisible by_ `k`.
A **subarray** is a **contiguous** part of an array.
**Example 1:**
**Input:** nums = \[4,5,0,-2,-3,1\], k = 5
... | dolphin |
Please focus on the functionality of this problem and provide code in Objective-C:
You are given a string `s`, and an array of pairs of indices in the string `pairs` where `pairs[i] = [a, b]` indicates 2 indices(0-indexed) of the string.
You can swap the characters at any pair of indices in the given `pairs` **any num... | dolphin |
Please write the following solution using python:
Given a list `paths` of directory info, including the directory path, and all the files with contents in this directory, return _all the duplicate files in the file system in terms of their paths_. You may return the answer in **any order**.
A group of duplicate files ... | dolphin |
Please write the following solution using Scheme:
You are working in a ball factory where you have `n` balls numbered from `lowLimit` up to `highLimit` **inclusive** (i.e., `n == highLimit - lowLimit + 1`), and an infinite number of boxes numbered from `1` to `infinity`.
Your job at this factory is to put each ball in... | dolphin |
Please write the following solution using Elixir:
You are given an `m x n` grid `grid` of values `0`, `1`, or `2`, where:
* each `0` marks **an empty land** that you can pass by freely,
* each `1` marks **a building** that you cannot pass through, and
* each `2` marks **an obstacle** that you cannot pass through... | dolphin |
port this code to javascript:
```erlang
parse_ternary(Expression) ->
Stack = [],
ReverseExpression = lists:reverse(Expression),
parse_ternary_helper(ReverseExpression, Stack).
parse_ternary_helper([C|Rest], Stack) ->
case Stack of
['?']++Stack2 ->
{First, ['?']++[':']++Stack3} = spl... | dolphin |
Please write the following solution using Rust:
Given an integer array `nums`, find the **maximum** possible **bitwise OR** of a subset of `nums` and return _the **number of different non-empty subsets** with the maximum bitwise OR_.
An array `a` is a **subset** of an array `b` if `a` can be obtained from `b` by delet... | dolphin |
Please explain the following problem in detail and provide code in R:
A delivery company wants to build a new service center in a new city. The company knows the positions of all the customers in this city on a 2D-Map and wants to build the new center in a position such that **the sum of the euclidean distances to all ... | dolphin |
convert this code to java:
```groovy
def badPairs(nums) {
int count = 0
for (int i = 0; i < nums.size(); i++) {
for (int j = i + 1; j < nums.size(); j++) {
if (j - i != nums[j] - nums[i]) {
count++
}
}
}
return count
}
``` | dolphin |
Please write the following solution using Object Pascal:
Given an array of `intervals` where `intervals[i] = [starti, endi]`, merge all overlapping intervals, and return _an array of the non-overlapping intervals that cover all the intervals in the input_.
**Example 1:**
**Input:** intervals = \[\[1,3\],\[2,6\],\[8,1... | dolphin |
Please focus on the functionality of this problem and provide code in Lua:
Given the `root` of a binary tree, determine if it is a _complete binary tree_.
In a **[complete binary tree](http://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_trees)**, every level, except possibly the last, is completely filled, and al... | dolphin |
convert this code to javascript:
```lua
function min_penalty(customers)
local n = #customers
local open_penalty = 0
local closed_penalty = 0
for i = 1, n do
if customers:sub(i,i) == 'N' then
open_penalty = open_penalty + 1
else
closed_penalty = closed_penalty + 1... | dolphin |
Please explain the following problem in detail and provide code in javascript:
You are given an integer array `nums` and a **positive** integer `k`.
The **frequency score** of an array is the sum of the **distinct** values in the array raised to the power of their **frequencies**, taking the sum **modulo** `109 + 7`.
... | dolphin |
Please explain the reasoning behind the following solution and provide code in python:
Given a date, return the corresponding day of the week for that date.
The input is given as three integers representing the `day`, `month` and `year` respectively.
Return the answer as one of the following values `{ "Sunday ", "Mon... | dolphin |
Please write the following solution using Visual Basic .NET:
You are given a string `s` and an array of strings `words`.
You should add a closed pair of bold tag **and** to wrap the substrings in `s` that exist in `words`.
* If two such substrings overlap, you should wrap them together with only one pair of closed ... | dolphin |
Please explain the following problem in detail and provide code in Visual Basic .NET:
You are given a **0-indexed** integer array `mapping` which represents the mapping rule of a shuffled decimal system. `mapping[i] = j` means digit `i` should be mapped to digit `j` in this system.
The **mapped value** of an integer i... | dolphin |
Please write the following solution using c++:
Given the array of integers `nums`, you will choose two different indices `i` and `j` of that array. _Return the maximum value of_ `(nums[i]-1)*(nums[j]-1)`.
**Example 1:**
**Input:** nums = \[3,4,5,2\]
**Output:** 12
**Explanation:** If you choose the indices i=1 and j... | dolphin |
convert this code to Visual Basic .NET:
```javascript
function ipToCIDR(ip, n) {
const [a, b, c, d] = ip.split('.').map(Number);
let start = (a << 24) + (b << 16) + (c << 8) + d;
const end = start + n - 1;
const ans = [];
while (start <= end) {
let samePrefixBits = Math.clz32(~(start & ... | dolphin |
translate this code to Scala:
```ruby
def can_construct_k_palindromes(s, k)
char_freq = Hash.new(0)
num_odd_freq_chars = 0
s.each_char do |char|
char_freq[char] += 1
end
char_freq.each_value do |freq|
num_odd_freq_chars += 1 if freq.odd?
end
return num_odd_freq_chars <= k && ... | dolphin |
convert this code from C# to javascript:
```csharp
using System;
using System.Collections.Generic;
public class Solution {
public int MinMeetingRooms(int[][] intervals) {
if (intervals.Length == 0) {
return 0;
}
Array.Sort(intervals, (a, b) => a[0].CompareTo(b[0]));
... | dolphin |
Please explain the following problem in detail and provide code in c++:
Given an integer array `arr`, and an integer `target`, return the number of tuples `i, j, k` such that `i < j < k` and `arr[i] + arr[j] + arr[k] == target`.
As the answer can be very large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:... | dolphin |
Please explain the following problem in detail and provide code in Clojure:
In a string composed of `'L'`, `'R'`, and `'X'` characters, like `"RXXLRXRXL "`, a move consists of either replacing one occurrence of `"XL "` with `"LX "`, or replacing one occurrence of `"RX "` with `"XR "`. Given the starting string `start` ... | dolphin |
convert this code to Objective-C:
```javascript
function minimumPathCost(stones) {
let n = stones.length;
let max_cost = stones[n-1];
for(let i = 1; i < n-1; ++i){
max_cost = Math.min(max_cost, Math.max(stones[i], stones[n-1]-stones[i]));
}
return max_cost;
}
```
| dolphin |
Please write the following solution using Clojure:
Given an integer array of size `n`, find all elements that appear more than `⌊ n/3 ⌋` times.
**Example 1:**
**Input:** nums = \[3,2,3\]
**Output:** \[3\]
**Example 2:**
**Input:** nums = \[1\]
**Output:** \[1\]
**Example 3:**
**Input:** nums = \[1,2\]
**Output:**... | dolphin |
Please explain the reasoning behind the following solution and provide code in Scala:
A sentence consists of lowercase letters (`'a'` to `'z'`), digits (`'0'` to `'9'`), hyphens (`'-'`), punctuation marks (`'!'`, `'.'`, and `','`), and spaces (`' '`) only. Each sentence can be broken down into **one or more tokens** se... | dolphin |
Please explain the reasoning behind the following solution and provide code in java:
Given a string `s`, return the maximum number of ocurrences of **any** substring under the following rules:
* The number of unique characters in the substring must be less than or equal to `maxLetters`.
* The substring size must b... | dolphin |
Please focus on the efficiency of this problem and provide code in C#:
Android devices have a special lock screen with a `3 x 3` grid of dots. Users can set an "unlock pattern " by connecting the dots in a specific sequence, forming a series of joined line segments where each segment's endpoints are two consecutive dot... | dolphin |
Please explain the following problem in detail and provide code in Fortran:
The **width** of a sequence is the difference between the maximum and minimum elements in the sequence.
Given an array of integers `nums`, return _the sum of the **widths** of all the non-empty **subsequences** of_ `nums`. Since the answer may... | dolphin |
Please write the following solution using Kotlin:
You would like to make dessert and are preparing to buy the ingredients. You have `n` ice cream base flavors and `m` types of toppings to choose from. You must follow these rules when making your dessert:
* There must be **exactly one** ice cream base.
* You can ad... | dolphin |
port this code from Scheme to Julia:
```scheme
(define (min-operations startValue target)
(cond ((< target startValue) (- startValue target))
((= target startValue) 0)
((= (remainder target 2) 0) (+ 1 (min-operations startValue (/ target 2))))
(else (+ 1 (min (min-operations startValue (- targ... | dolphin |
Please focus on the algorithm of this problem and provide code in Object Pascal:
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,2]`,... | dolphin |
Please explain the following problem in detail and provide code in Julia:
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 following problem in detail and provide code in TypeScript:
You are a hiker preparing for an upcoming hike. You are given `heights`, a 2D array of size `rows x columns`, where `heights[row][col]` represents the height of cell `(row, col)`. You are situated in the top-left cell, `(0, 0)`, and you hope... | dolphin |
translate this code to Mojo:
```php
function optimal_score_difference($stones) {
$alice_turn = true;
$alice_score = 0;
$bob_score = 0;
while(count($stones) > 1) {
if($alice_turn) {
$x = get_max_x($stones);
$alice_score += array_sum(array_slice($stones, 0, $x));
... | dolphin |
Please write the following solution using ANSI C:
Given the `head` of a linked list, remove the `nth` node from the end of the list and return its head.
**Example 1:**
**Input:** head = \[1,2,3,4,5\], n = 2
**Output:** \[1,2,3,5\]
**Example 2:**
**Input:** head = \[1\], n = 1
**Output:** \[\]
**Example 3:**
**Inp... | dolphin |
Please explain the following problem in detail and provide code in Mojo:
We are given `n` different types of `stickers`. Each sticker has a lowercase English word on it.
You would like to spell out the given string `target` by cutting individual letters from your collection of stickers and rearranging them. You can us... | dolphin |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.