instruction_seed stringlengths 29 40.5k | source stringclasses 6
values |
|---|---|
Please explain the following problem in detail and provide code in Julia:
Given an array of characters `chars`, compress it using the following algorithm:
Begin with an empty string `s`. For each group of **consecutive repeating characters** in `chars`:
* If the group's length is `1`, append the character to `s`.
*... | dolphin |
port this code from Mojo to Ruby:
```
sub teach_language(n: int, languages: array[int, array[int]], friendships: array[array[int]]) -> int {
var adjacency_list = build_adjacency_list(languages, friendships);
var min_users = infinity;
for language in 1..n {
var num_users = bfs(adjacency_list, languag... | dolphin |
Please focus on the functionality of this problem and provide code in Elixir:
You are given a **0-indexed** integer array `stones` sorted in **strictly increasing order** representing the positions of stones in a river.
A frog, initially on the first stone, wants to travel to the last stone and then return to the firs... | dolphin |
Please focus on the efficiency of this problem and provide code in Elixir:
A subsequence of a string `s` is considered a **good palindromic subsequence** if:
* It is a subsequence of `s`.
* It is a palindrome (has the same value if reversed).
* It has an **even** length.
* No two consecutive characters are equ... | dolphin |
port this code to c++:
```haskell
import qualified Data.Map as Map
findSubstring :: String -> [String] -> [Int]
findSubstring s words
| null s || null words = []
| otherwise =
let wordCount = foldr (\w -> Map.insertWith (+) w 1) Map.empty words
wordLength = length $ head words
... | dolphin |
Please explain the reasoning behind the following solution and provide code in PHP:
You are given an array of strings `equations` that represent relationships between variables where each string `equations[i]` is of length `4` and takes one of two different forms: `"xi==yi "` or `"xi!=yi "`.Here, `xi` and `yi` are lowe... | dolphin |
Please explain the reasoning behind the following solution and provide code in c++:
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 ... | dolphin |
Please focus on the functionality of this problem and provide code in Scala:
Given a `wordlist`, we want to implement a spellchecker that converts a query word into a correct word.
For a given `query` word, the spell checker handles two categories of spelling mistakes:
* Capitalization: If the query matches a word ... | dolphin |
convert this code to Julia:
```kotlin
/**
* Definition for a binary tree node.
* class TreeNode(var `val`: Int = 0) {
* var left: TreeNode? = null
* var right: TreeNode? = null
* }
*/
class Solution {
fun sufficientSubset(root: TreeNode?, limit: Int): TreeNode? {
if (root == null) {
... | dolphin |
Please write the following solution using C#:
Given an integer `n`, return `true` _if it is possible to represent_ `n` _as the sum of distinct powers of three._ Otherwise, return `false`.
An integer `y` is a power of three if there exists an integer `x` such that `y == 3x`.
**Example 1:**
**Input:** n = 12
**Output:... | dolphin |
Please explain the reasoning behind the following solution and provide code in Lua:
There are several cards **arranged in a row**, and each card has an associated number of points. The points are given in the integer array `cardPoints`.
In one step, you can take one card from the beginning or from the end of the row. ... | dolphin |
convert this code from TypeScript to Go:
```typescript
function findBottomLeftValue(root: TreeNode | null): number {
const result: [number, number] = [0, 0]; // [depth, value]
helper(root, 1, result);
return result[1];
}
function helper(node: TreeNode | null, depth: number, result: [number, number]): void {
if... | dolphin |
Please focus on the functionality of this problem and provide code in Objective-C:
There are `n` cities numbered from `1` to `n`. You are given an array `edges` of size `n-1`, where `edges[i] = [ui, vi]` represents a bidirectional edge between cities `ui` and `vi`. There exists a unique path between each pair of cities... | dolphin |
Please explain the following problem in detail and provide code in Visual Basic .NET:
Suppose you are at a party with `n` people labeled from `0` to `n - 1` and among them, there may exist one celebrity. The definition of a celebrity is that all the other `n - 1` people know the celebrity, but the celebrity does not kn... | dolphin |
Please explain the following problem in detail and provide code in Ruby:
You are given a binary array `nums` containing only the integers `0` and `1`. Return _the number of **subarrays** in nums that have **more**_ `1`'_s than_ `0`_'s. Since the answer may be very large, return it **modulo**_ `109 + 7`.
A **subarray**... | dolphin |
Please explain the reasoning behind the following solution and provide code in c++:
You are given a string `s` and a robot that currently holds an empty string `t`. Apply one of the following operations until `s` and `t` **are both empty**:
* Remove the **first** character of a string `s` and give it to the robot. T... | dolphin |
Please explain the reasoning behind the following solution and provide code in Julia:
Given a single-digit integer `d` and two integers `low` and `high`, return _the number of times that_ `d` _occurs as a digit in all integers in the inclusive range_ `[low, high]`.
**Example 1:**
**Input:** d = 1, low = 1, high = 13
... | dolphin |
Please explain the reasoning behind the following solution and provide code in Dart:
You are given a **0-indexed** array of `n` integers `differences`, which describes the **differences** between each pair of **consecutive** integers of a **hidden** sequence of length `(n + 1)`. More formally, call the hidden sequence ... | dolphin |
Please focus on the algorithm of this problem and provide code in Scheme:
There are `n` cars going to the same destination along a one-lane road. The destination is `target` miles away.
You are given two integer array `position` and `speed`, both of length `n`, where `position[i]` is the position of the `ith` car and ... | dolphin |
translate this code to Groovy:
```rust
fn find_ball(grid: Vec<Vec<i32>>) -> Vec<i32> {
let m = grid.len();
let n = grid[0].len();
let mut ans = vec![-1; n];
for i in 0..n {
let mut r = 0;
let mut c = i;
while r < m {
if grid[r][c] == 1 {
if c == n - 1... | dolphin |
Please focus on the algorithm of this problem and provide code in python:
You have a keypad with `9` buttons, numbered from `1` to `9`, each mapped to lowercase English letters. You can choose which characters each button is matched to as long as:
* All 26 lowercase English letters are mapped to.
* Each character ... | dolphin |
Please explain the reasoning behind the following solution and provide code in F#:
Given an integer array `nums`, handle multiple queries of the following types:
1. **Update** the value of an element in `nums`.
2. Calculate the **sum** of the elements of `nums` between indices `left` and `right` **inclusive** where ... | dolphin |
translate this code to Go:
```python
def xor_operation(n, start):
xor_result = 0
for i in range(n):
xor_result ^= (start + 2 * i)
return xor_result
```
| dolphin |
Please focus on the efficiency of this problem and provide code in Scheme:
A **valid IP address** consists of exactly four integers separated by single dots. Each integer is between `0` and `255` (**inclusive**) and cannot have leading zeros.
* For example, `"0.1.2.201 "` and `"192.168.1.1 "` are **valid** IP addres... | dolphin |
convert this code to TypeScript:
```erlang
combination_sum(Candidates, Target) ->
find_combinations(0, Target, Candidates).
find_combinations(_, 0, _) ->
[[]];
find_combinations(_, _, []) ->
[];
find_combinations(StartIndex, Remaining, Candidates) ->
Result = [],
Result1 = find_combinations(StartIn... | dolphin |
convert this code to Ruby:
```perl
sub count_square_submatrices {
my ($matrix) = @_;
my $n = scalar(@$matrix);
my $m = scalar(@{$matrix->[0]});
my $count = 0;
for (my $i = 0; $i < $n; $i++) {
for (my $j = 0; $j < $m; $j++) {
if ($matrix->[$i][$j] == 1) {
if ($i ==... | dolphin |
Please focus on the functionality of this problem and provide code in F#:
Given a list of `words`, list of single `letters` (might be repeating) and `score` of every character.
Return the maximum score of **any** valid set of words formed by using the given letters (`words[i]` cannot be used two or more times).
It is... | dolphin |
Please write the following solution using Lisp:
You are given two integer arrays `nums1` and `nums2` both of the same length. The **advantage** of `nums1` with respect to `nums2` is the number of indices `i` for which `nums1[i] > nums2[i]`.
Return _any permutation of_ `nums1` _that maximizes its **advantage** with res... | dolphin |
Please explain the reasoning behind the following solution and provide code in Ruby:
Given two binary search trees `root1` and `root2`, return _a list containing all the integers from both trees sorted in **ascending** order_.
**Example 1:**
**Input:** root1 = \[2,1,4\], root2 = \[1,0,3\]
**Output:** \[0,1,1,2,3,4\]
... | dolphin |
Please write the following solution using Scheme:
There is an undirected graph consisting of `n` nodes numbered from `0` to `n - 1`. You are given a **0-indexed** integer array `vals` of length `n` where `vals[i]` denotes the value of the `ith` node.
You are also given a 2D integer array `edges` where `edges[i] = [ai,... | dolphin |
convert this code to Go:
```python
def removeDuplicateLetters(s):
count = [0] * 256
visited = [False] * 256
st = []
for ch in s:
count[ord(ch)] += 1
for ch in s:
count[ord(ch)] -= 1
if visited[ord(ch)]:
continue
while st and ch < st[-1] and count[ord(st[... | dolphin |
Please focus on the algorithm of this problem and provide code in Kotlin:
You are given an integer array `nums` of length `n`, and an integer array `queries` of length `m`.
Return _an array_ `answer` _of length_ `m` _where_ `answer[i]` _is the **maximum** size of a **subsequence** that you can take from_ `nums` _such ... | dolphin |
Please explain the following problem in detail and provide code in Scala:
Given an integer `n`, return the `nth` digit of the infinite integer sequence `[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...]`.
**Example 1:**
**Input:** n = 3
**Output:** 3
**Example 2:**
**Input:** n = 11
**Output:** 0
**Explanation:** The 11th d... | dolphin |
convert this code to Groovy:
```dart
String makeLargestSpecial(String s) {
int count = 0;
int i = 0;
List<String> subs = [];
for (int j = 0; j < s.length; j++) {
if (s[j] == '1') {
count += 1;
} else {
count -= 1;
}
if (count == 0) {
subs.add("1" + makeLargestSpecial(s.substr... | dolphin |
Please explain the reasoning behind the following solution and provide code in c++:
There are several consecutive houses along a street, each of which has some money inside. There is also a robber, who wants to steal money from the homes, but he **refuses to steal from adjacent homes**.
The **capability** of the robbe... | dolphin |
port this code from Fortran to Swift:
```
subroutine find_same_binary_value_parts(arr, idx)
integer :: arr(:), idx(2)
integer :: ones, target, count, i, j, n
ones = sum(arr)
if (mod(ones, 3) /= 0) then
idx = [-1, -1]
return
end if
target = ones / 3
if (target == 0) then
... | dolphin |
Please explain the reasoning behind the following solution and provide code in Fortran:
Given two positive integers `a` and `b`, return _the number of **common** factors of_ `a` _and_ `b`.
An integer `x` is a **common factor** of `a` and `b` if `x` divides both `a` and `b`.
**Example 1:**
**Input:** a = 12, b = 6
**... | dolphin |
Please explain the reasoning behind the following solution and provide code in Rust:
A scenic location is represented by its `name` and attractiveness `score`, where `name` is a **unique** string among all locations and `score` is an integer. Locations can be ranked from the best to the worst. The **higher** the score,... | dolphin |
Please write the following solution using Rust:
Given a string `s` and an integer `k`, return _the number of substrings in_ `s` _of length_ `k` _with no repeated characters_.
**Example 1:**
**Input:** s = "havefunonleetcode ", k = 5
**Output:** 6
**Explanation:** There are 6 substrings they are: 'havef','avefu','vef... | dolphin |
Please focus on the algorithm of this problem and provide code in PHP:
Design a max stack data structure that supports the stack operations and supports finding the stack's maximum element.
Implement the `MaxStack` class:
* `MaxStack()` Initializes the stack object.
* `void push(int x)` Pushes element `x` onto th... | dolphin |
convert this code to Elixir:
```swift
struct PQ<T: Comparable> {
var heap: [(T, Int)] = []
var count: Int = 0
mutating func push(_ val: T) {
heap.append((val, count))
count += 1
siftUp(heap.count - 1)
}
mutating func pop() -> T? {
if heap.isEmpty { return ni... | dolphin |
Please explain the following problem in detail and provide code in Julia:
Given a signed 32-bit integer `x`, return `x` _with its digits reversed_. If reversing `x` causes the value to go outside the signed 32-bit integer range `[-231, 231 - 1]`, then return `0`.
**Assume the environment does not allow you to store 64... | dolphin |
Please write the following solution using javascript:
You are given an integer `mass`, which represents the original mass of a planet. You are further given an integer array `asteroids`, where `asteroids[i]` is the mass of the `ith` asteroid.
You can arrange for the planet to collide with the asteroids in **any arbitr... | dolphin |
Please write the following solution using SmallTalk:
Given a string `path`, which is an **absolute path** (starting with a slash `'/'`) to a file or directory in a Unix-style file system, convert it to the simplified **canonical path**.
In a Unix-style file system, a period `'.'` refers to the current directory, a dou... | dolphin |
Please explain the reasoning behind the following solution and provide code in Lisp:
You are given a string `number` representing a **positive integer** and a character `digit`.
Return _the resulting string after removing **exactly one occurrence** of_ `digit` _from_ `number` _such that the value of the resulting stri... | dolphin |
Please explain the reasoning behind the following solution and provide code in c++:
Given two strings `s1` and `s2`, return _the lowest **ASCII** sum of deleted characters to make two strings equal_.
**Example 1:**
**Input:** s1 = "sea ", s2 = "eat "
**Output:** 231
**Explanation:** Deleting "s " from "sea " adds... | dolphin |
Please focus on the algorithm of this problem and provide code in Scala:
You are given a string `text`. You should split it to k substrings `(subtext1, subtext2, ..., subtextk)` such that:
* `subtexti` is a **non-empty** string.
* The concatenation of all the substrings is equal to `text` (i.e., `subtext1 + subtex... | dolphin |
port this code from C# to Erlang:
```csharp
public class VideoSharingPlatform
{
private class Video
{
public int VideoId;
public string VideoString;
public int Views;
public int Likes;
public int Dislikes;
public Video(int videoId, string videoString)
{
... | dolphin |
translate this code from Visual Basic .NET to python:
```vb.net
Function CountHomeworkStudents(startTime As Integer(), endTime As Integer(), queryTime As Integer) As Integer
Dim count As Integer = 0
For i As Integer = 0 To startTime.Length - 1
If startTime(i) <= queryTime AndAlso endTime(i) >= queryTime... | dolphin |
Please write the following solution using Swift:
Given an integer `n`, _return a string with `n` characters such that each character in such string occurs **an odd number of times**_.
The returned string must contain only lowercase English letters. If there are multiples valid strings, return **any** of them.
**Examp... | dolphin |
convert this code to Erlang:
```lua
function removeSubfolders(folder)
local result = {}
table.sort(folder)
local prefix = "/"
for i,path in ipairs(folder) do
if not string.match(path, "^"..prefix) then
table.insert(result, path)
prefix = path .. "/"
end
e... | dolphin |
convert this code to Clojure:
```vb.net
Imports System.Collections.Generic
Module Module1
Function BeforeAndAfterPuzzles(phrases As String()) As String()
Dim first_word_map As New Dictionary(Of String, HashSet(Of String))
Dim result As New HashSet(Of String)
For Each phrase As String In p... | dolphin |
convert this code from Perl to ANSI C:
```perl
use strict;
use warnings;
use List::Util qw[min];
sub soup_empty_probability {
my ($n) = @_;
my @dp = ([$n, $n, $n, $n]);
while (1) {
my $prev = $dp[-1];
my $cur = [map {[$_->[0], $_->[1], $_->[2], $_->[3]]} @$prev];
for my $i (0..3) ... | dolphin |
Please explain the following problem in detail and provide code in TypeScript:
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:*... | dolphin |
Please explain the reasoning behind the following solution and provide code in java:
Given two integer arrays `nums1` and `nums2`, return _an array of their intersection_. Each element in the result must be **unique** and you may return the result in **any order**.
**Example 1:**
**Input:** nums1 = \[1,2,2,1\], nums2... | dolphin |
Please explain the reasoning behind the following solution and provide code in Fortran:
There is a donuts shop that bakes donuts in batches of `batchSize`. They have a rule where they must serve **all** of the donuts of a batch before serving any donuts of the next batch. You are given an integer `batchSize` and an int... | dolphin |
Please write the following solution using Kotlin:
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** `k` no larger than `wo... | dolphin |
Please explain the reasoning behind the following solution and provide code in PHP:
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 obsta... | dolphin |
port this code from Object Pascal to Visual Basic .NET:
```pascal
unit CircularQueue;
interface
type
TMyCircularQueue = class
private
size: Integer;
data: array of Integer;
front, rear: Integer;
public
constructor Create(k: Integer);
function enQueue(value: Integer): Boolean;
function de... | dolphin |
Please write the following solution using TypeScript:
Suppose you have `n` integers labeled `1` through `n`. A permutation of those `n` integers `perm` (**1-indexed**) is considered a **beautiful arrangement** if for every `i` (`1 <= i <= n`), **either** of the following is true:
* `perm[i]` is divisible by `i`.
* ... | dolphin |
port this code to Groovy:
```elixir
defmodule Solution do
def remove_invalid_parentheses(s) do
is_valid = fn (s) ->
count = 0
Enum.each(s, fn (c) ->
cond do
c == "(" -> count += 1
c == ")" -> count -= 1
count < 0 -> return false
true -> nil
end
... | dolphin |
Please focus on the algorithm of this problem and provide code in Lisp:
Given an integer array `arr` and an integer `difference`, return the length of the longest subsequence in `arr` which is an arithmetic sequence such that the difference between adjacent elements in the subsequence equals `difference`.
A **subseque... | dolphin |
port this code to Julia:
```R
set.seed(42)
randPoint <- function(radius, x_center, y_center) {
r <- sqrt(runif(1)) * radius
theta <- runif(1) * 2 * pi
x_offset <- r * cos(theta)
y_offset <- r * sin(theta)
c(x_center + x_offset, y_center + y_offset)
}
Solution <- function(radius, x_center, y_center) {
list... | dolphin |
Please explain the reasoning behind the following solution and provide code in Scala:
A **swap** is defined as taking two **distinct** positions in an array and swapping the values in them.
A **circular** array is defined as an array where we consider the **first** element and the **last** element to be **adjacent**.
... | dolphin |
Please explain the reasoning behind the following solution and provide code in Go:
We have `n` jobs, where every job is scheduled to be done from `startTime[i]` to `endTime[i]`, obtaining a profit of `profit[i]`.
You're given the `startTime`, `endTime` and `profit` arrays, return the maximum profit you can take such t... | dolphin |
Please explain the reasoning behind the following solution and provide code in Scheme:
Given an integer `n`, return _the number of strings of length_ `n` _that consist only of vowels (_`a`_,_ `e`_,_ `i`_,_ `o`_,_ `u`_) and are **lexicographically sorted**._
A string `s` is **lexicographically sorted** if for all valid... | dolphin |
Please focus on the efficiency of this problem and provide code in Perl:
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 so... | dolphin |
Please explain the following problem in detail and provide code in java:
You are given an array of strings `words` and a string `pref`.
Return _the number of strings in_ `words` _that contain_ `pref` _as a **prefix**_.
A **prefix** of a string `s` is any leading contiguous substring of `s`.
**Example 1:**
**Input:*... | dolphin |
Please explain the following problem in detail and provide code in python:
Given a positive integer num, return _the smallest positive integer_ `x` _whose multiplication of each digit equals_ `num`. If there is no answer or the answer is not fit in **32-bit** signed integer, return `0`.
**Example 1:**
**Input:** num ... | dolphin |
Please write the following solution using Ruby:
You have a 2-D `grid` of size `m x n` representing a box, and you have `n` balls. The box is open on the top and bottom sides.
Each cell in the box has a diagonal board spanning two corners of the cell that can redirect a ball to the right or to the left.
* A board th... | dolphin |
translate this code to F#:
```ruby
def max_score(s)
left_zeros = 0
right_ones = s.count("1")
max_score = 0
(0...s.length).each do |i|
if s[i] == "0"
left_zeros += 1
else
right_ones -= 1
end
max_score = [max_score, left_zeros + right_o... | dolphin |
Please write the following solution using Scala:
Given a string `formula` representing a chemical formula, return _the count of each atom_.
The atomic element always starts with an uppercase character, then zero or more lowercase letters, representing the name.
One or more digits representing that element's count may... | dolphin |
Please focus on the algorithm of this problem and provide code in Object Pascal:
Given the `root` of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST.
As a reminder, a _binary se... | dolphin |
Please explain the following problem in detail and provide code in Object Pascal:
Given an integer array `nums` and two integers `left` and `right`, return _the number of contiguous non-empty **subarrays** such that the value of the maximum array element in that subarray is in the range_ `[left, right]`.
The test case... | dolphin |
Please write the following solution using TypeScript:
Given an integer `num`, find the closest two integers in absolute difference whose product equals `num + 1` or `num + 2`.
Return the two integers in any order.
**Example 1:**
**Input:** num = 8
**Output:** \[3,3\]
**Explanation:** For num + 1 = 9, the closest div... | dolphin |
Please focus on the functionality of this problem and provide code in Elixir:
You are given an array `time` where `time[i]` denotes the time taken by the `ith` bus to complete **one trip**.
Each bus can make multiple trips **successively**; that is, the next trip can start **immediately after** completing the current ... | dolphin |
Please explain the reasoning behind the following solution and provide code in Julia:
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**... | dolphin |
translate this code to Objective-C:
```elixir
defmodule Solution do
def sum_of_mins(arr) do
mod = 1_000_000_007
n = length(arr)
left = List.new(n, 0)
right = List.new(n, 0)
st = []
for i <- 0..(n-1) do
while st != [] and Enum.at(arr, hd(st)) > Enum.at(arr, i) do
st = List.delete... | dolphin |
Please write the following solution using Perl:
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
**Output:** 7
**Explanation... | dolphin |
Please write the following solution using Groovy:
You are given an integer array `stations` that represents the positions of the gas stations on the **x-axis**. You are also given an integer `k`.
You should add `k` new gas stations. You can add the stations anywhere on the **x-axis**, and not necessarily on an integer... | dolphin |
port this code to F#:
```Swift
class MovingAverage {
var queue = [Int]()
var maxSize: Int
var sum = 0.0
init(_ size: Int) {
maxSize = size
}
func next(_ val: Int) -> Double {
if queue.count == maxSize {
sum -= Double(queue.removeFirst())
}
qu... | dolphin |
Please explain the reasoning behind the following solution and provide code in Haskell:
Given a string `s`, return _the number of **distinct** substrings of_ `s`.
A **substring** of a string is obtained by deleting any number of characters (possibly zero) from the front of the string and any number (possibly zero) fro... | dolphin |
Please focus on the algorithm of this problem and provide code in python:
Given an array `arr`, replace every element in that array with the greatest element among the elements to its right, and replace the last element with `-1`.
After doing so, return the array.
**Example 1:**
**Input:** arr = \[17,18,5,4,6,1\]
**... | dolphin |
Please explain the reasoning behind the following solution and provide code in Fortran:
There are a row of `n` houses, each house can be painted with one of the `k` colors. 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 ... | dolphin |
Please focus on the efficiency of this problem and provide code in Rust:
You are given an integer `num.` **Rearrange** the digits of `num` such that its value is **minimized** and it does not contain **any** leading zeros.
Return _the rearranged number with minimal value_.
Note that the sign of the number does not ch... | dolphin |
convert this code from Go to Lua:
```go
func canJump(nums []int) bool {
maxReach := 0
for i, num := range nums {
if i > maxReach {
return false
}
maxReach = max(maxReach, i+num)
}
return true
}
func max(a, b int) int {
if a > b {
return a
}
return... | dolphin |
Please focus on the functionality of this problem and provide code in Haskell:
You are given four integers `minLength`, `maxLength`, `oneGroup` and `zeroGroup`.
A binary string is **good** if it satisfies the following conditions:
* The length of the string is in the range `[minLength, maxLength]`.
* The size of ... | dolphin |
port this code from Go to TypeScript:
```go
func maxProfit(prices []int, fee int) int {
cash, hold := 0, -prices[0]
for i := 1; i < len(prices); i++ {
temp := cash
cash = max(cash, hold+prices[i]-fee)
hold = max(hold, temp-prices[i])
}
return cash
}
func max(a, b int) int {
... | dolphin |
Please focus on the efficiency of this problem and provide code in Elixir:
A **sentence** is a list of words that are separated by a single space with no leading or trailing spaces. Each word consists of lowercase and uppercase English letters.
A sentence can be **shuffled** by appending the **1-indexed word position*... | dolphin |
Please explain the reasoning behind the following solution and provide code in Go:
You have an array `arr` of length `n` where `arr[i] = (2 * i) + 1` for all valid values of `i` (i.e., `0 <= i < n`).
In one operation, you can select two indices `x` and `y` where `0 <= x, y < n` and subtract `1` from `arr[x]` and add `... | dolphin |
convert this code to Clojure:
```haskell
import Data.List (isPrefixOf)
addBoldTag :: [String] -> String -> String
addBoldTag words s =
let bold = map (\x -> any (\w -> w `isPrefixOf` drop x s) words) [0..length s - 1]
insertTags [] [] = []
insertTags (b:bs) (c:cs)
| b && (null cs || no... | dolphin |
Please write the following solution using F#:
You are given a **0-indexed** integer array `costs` where `costs[i]` is the cost of hiring the `ith` worker.
You are also given two integers `k` and `candidates`. We want to hire exactly `k` workers according to the following rules:
* You will run `k` sessions and hire ... | dolphin |
Please explain the following problem in detail and provide code in Erlang:
Given an array `nums` of positive integers. Your task is to select some subset of `nums`, multiply each element by an integer and add all these numbers. The array is said to be **good** if you can obtain a sum of `1` from the array by any possib... | dolphin |
translate this code from PHP to Mojo:
```php
function hasAlternatingBits($n) {
$prev_bit = $n % 2;
$n = floor($n / 2);
while ($n > 0) {
$curr_bit = $n % 2;
if ($curr_bit == $prev_bit) {
return false;
}
$prev_bit = $curr_bit;
$n = floor($n / 2);
}
r... | dolphin |
Please explain the reasoning behind the following solution and provide code in R:
Given an integer `n`, return _a string array_ `answer` _(**1-indexed**) where_:
* `answer[i] == "FizzBuzz "` if `i` is divisible by `3` and `5`.
* `answer[i] == "Fizz "` if `i` is divisible by `3`.
* `answer[i] == "Buzz "` if `i` i... | dolphin |
Please focus on the functionality of this problem and provide code in python:
Given an integer array `nums` and a positive integer `k`, return _the most **competitive** subsequence of_ `nums` _of size_ `k`.
An array's subsequence is a resulting sequence obtained by erasing some (possibly zero) elements from the array.... | dolphin |
Please explain the following problem in detail and provide code in Rust:
Design a data structure that will be initialized with a string array, and then it should answer queries of the shortest distance between two different strings from the array.
Implement the `WordDistance` class:
* `WordDistance(String[] wordsDi... | dolphin |
Please explain the reasoning behind the following solution and provide code in Objective-C:
Design a simplified version of Twitter where users can post tweets, follow/unfollow another user, and is able to see the `10` most recent tweets in the user's news feed.
Implement the `Twitter` class:
* `Twitter()` Initializ... | dolphin |
Please explain the reasoning behind the following solution and provide code in Visual Basic .NET:
You are given a string `s`, a string `chars` of **distinct** characters and an integer array `vals` of the same length as `chars`.
The **cost of the substring** is the sum of the values of each character in the substring.... | dolphin |
Please explain the reasoning behind the following solution and provide code in Lisp:
A sequence of numbers is called **arithmetic** if it consists of at least two elements, and the difference between every two consecutive elements is the same. More formally, a sequence `s` is arithmetic if and only if `s[i+1] - s[i] ==... | dolphin |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.