instruction_seed stringlengths 29 40.5k | source stringclasses 6
values |
|---|---|
translate this code to Swift:
```Go
package main
import (
"fmt"
"math"
)
func shortestDistance(wordsDict []string, word1 string, word2 string) int {
index1, index2, minDistance := -1, -1, math.MaxInt32
for i, word := range wordsDict {
if word == word1 {
index1 = i
}
if word == word2 {
index2 = i
}
... | dolphin |
convert this code from Object Pascal to Perl:
```pascal
function createTargetArray(nums: array of integer; index: array of integer): array of integer;
var
target: array of integer;
i: integer;
begin
SetLength(target, Length(nums));
for i := 0 to High(nums) do
Insert(nums[i], target, index[i]);
Result := t... | dolphin |
Please focus on the algorithm of this problem and provide code in python:
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 to `n` eleme... | dolphin |
Please explain the reasoning behind the following solution and provide code in Objective-C:
You are given an `n x n` integer matrix `grid`.
Generate an integer matrix `maxLocal` of size `(n - 2) x (n - 2)` such that:
* `maxLocal[i][j]` is equal to the **largest** value of the `3 x 3` matrix in `grid` centered aroun... | dolphin |
Please explain the reasoning behind the following solution and provide code in Julia:
You are given two strings `s` and `t`.
You are allowed to remove any number of characters from the string `t`.
The score of the string is `0` if no characters are removed from the string `t`, otherwise:
* Let `left` be the minimu... | dolphin |
convert this code from Julia to javascript:
```julia
function circular_permutation(n::Int, start::Int)::Vector{Int}
result = Vector{Int}(undef, 1 << n)
result[1] = start
for i in 1:(1 << n) - 1
result[i+1] = start ⊻ (i ⊻ (i >> 1))
end
return result
end
``` | dolphin |
convert this code from Haskell to Ruby:
```haskell
import Data.List
hasPath :: [[Int]] -> [Int] -> [Int] -> Bool
hasPath maze start destination = bfs [(start, maze)]
where
bfs [] = False
bfs ((cur, maze):xs)
| cur == destination = True
| otherwise = bfs $ xs ++ [(next, markVisited maze next) | ne... | dolphin |
Please write the following solution using Mojo:
You are given a large sample of integers in the range `[0, 255]`. Since the sample is so large, it is represented by an array `count` where `count[k]` is the **number of times** that `k` appears in the sample.
Calculate the following statistics:
* `minimum`: The minim... | dolphin |
translate this code to javascript:
```scala
val MOD = 1000000007
def numDivisions(corridor: String): Int = {
val n = corridor.length
var count = 0
var i = 1
while (i < n - 1) {
if (corridor(i-1) == 'S' && corridor(i+1) == 'S' && corridor(i) == 'P') {
var left = i - 1
var right = i + 1
w... | dolphin |
Please explain the reasoning behind the following solution and provide code in Object Pascal:
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... | dolphin |
translate this code from ANSI C to c++:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LENGTH 30
#define MAX_WORDS 10000
int dp[MAX_LENGTH + 1];
int is_concatenated(char* word, char** word_dict, int word_dict_size) {
int n = strlen(word);
memset(dp, 0, sizeof(dp));
dp[0] = 1;... | dolphin |
Please write the following solution using TypeScript:
You are given a string `s` consisting only of lowercase English letters.
In one **move**, you can select any two **adjacent** characters of `s` and swap them.
Return _the **minimum number of moves** needed to make_ `s` _a palindrome_.
**Note** that the input will... | dolphin |
convert this code to Objective-C:
```lua
function bad_pairs(nums)
table.sort(nums)
local count = 0
for j = 2, #nums do
local i = j - 1
while i >= 1 and nums[j] - nums[i] > j - i do
i = i - 1
end
if i >= 1 then
count = count + j - i - 1
end
... | dolphin |
Please explain the reasoning behind the following solution and provide code in Lisp:
Given two strings `a` and `b`, return _the length of the **longest uncommon subsequence** between_ `a` _and_ `b`. If the longest uncommon subsequence does not exist, return `-1`.
An **uncommon subsequence** between two strings is a st... | dolphin |
translate this code from Erlang to PHP:
```erlang
merge(Nums, Start, Mid, End, Temp) ->
I = Start,
J = Mid + 1,
K = Start,
merge_loop(Nums, Temp, I, J, K, End, Mid).
merge_loop(Nums, Temp, I, J, K, End, Mid) when I =< Mid, J =< End ->
case Nums[I] =< Nums[J] of
true ->
Temp ... | dolphin |
Please explain the following problem in detail and provide code in Objective-C:
You are given a string `s` consisting of `n` characters which are either `'X'` or `'O'`.
A **move** is defined as selecting **three** **consecutive characters** of `s` and converting them to `'O'`. Note that if a move is applied to the cha... | dolphin |
Please write the following solution using Object Pascal:
A magical string `s` consists of only `'1'` and `'2'` and obeys the following rules:
* The string s is magical because concatenating the number of contiguous occurrences of characters `'1'` and `'2'` generates the string `s` itself.
The first few elements of ... | dolphin |
Please explain the reasoning behind the following solution and provide code in Fortran:
Alice and Bob take turns playing a game, with Alice starting first.
There are `n` stones in a pile. On each player's turn, they can **remove** a stone from the pile and receive points based on the stone's value. Alice and Bob may *... | dolphin |
port this code to Scala:
```c
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#define MOD 1000000007
int maxSumMinProduct(int* nums, int numsSize) {
long long max_product = 0;
int* stk = (int*)malloc(sizeof(int) * numsSize);
int top = -1;
long long* prefix_sum = (long long*)malloc(sizeof(lo... | dolphin |
Please explain the reasoning behind the following solution and provide code in Erlang:
Given an integer array `nums`, return _the largest perimeter of a triangle with a non-zero area, formed from three of these lengths_. If it is impossible to form any triangle of a non-zero area, return `0`.
**Example 1:**
**Input:*... | dolphin |
Please explain the reasoning behind the following solution and provide code in Haskell:
Given a list of strings `words` and a string `pattern`, return _a list of_ `words[i]` _that match_ `pattern`. You may return the answer in **any order**.
A word matches the pattern if there exists a permutation of letters `p` so th... | dolphin |
Please explain the reasoning behind the following solution and provide code in Lua:
You have `k` servers numbered from `0` to `k-1` that are being used to handle multiple requests simultaneously. Each server has infinite computational capacity but **cannot handle more than one request at a time**. The requests are assi... | dolphin |
Please focus on the algorithm of this problem and provide code in Julia:
A program was supposed to print an array of integers. The program forgot to print whitespaces and the array is printed as a string of digits `s` and all we know is that all integers in the array were in the range `[1, k]` and there are no leading ... | dolphin |
Please write the following solution using ANSI C:
Given an array `nums` of `n` integers, return _an array of all the **unique** quadruplets_ `[nums[a], nums[b], nums[c], nums[d]]` such that:
* `0 <= a, b, c, d < n`
* `a`, `b`, `c`, and `d` are **distinct**.
* `nums[a] + nums[b] + nums[c] + nums[d] == target`
Yo... | dolphin |
Please focus on the efficiency of this problem and provide code in Rust:
Given a **0-indexed** integer array `nums` of size `n` containing all numbers from `1` to `n`, return _the number of increasing quadruplets_.
A quadruplet `(i, j, k, l)` is increasing if:
* `0 <= i < j < k < l < n`, and
* `nums[i] < nums[k] ... | dolphin |
Please explain the reasoning behind the following solution and provide code in Scala:
Given an integer array `arr`, return _the length of a maximum size turbulent subarray of_ `arr`.
A subarray is **turbulent** if the comparison sign flips between each adjacent pair of elements in the subarray.
More formally, a subar... | dolphin |
Please explain the following problem in detail and provide code in Go:
You are given `n` tasks labeled from `0` to `n - 1` represented by a 2D integer array `tasks`, where `tasks[i] = [enqueueTimei, processingTimei]` means that the `ith` task will be available to process at `enqueueTimei` and will take ... | dolphin |
convert this code to Objective-C:
```swift
func wordPatternMatch(_ pattern: String, _ s: String) -> Bool {
var patternMap = [Character: String]()
var words = Set<String>()
func backtrack(_ pIndex: Int, _ sIndex: Int) -> Bool {
if pIndex == pattern.count && sIndex == s.count {
return... | dolphin |
translate this code from Scala to java:
```scala
def maxVariance(s: String): Int = {
val n = s.length
var maxVar = 0
for (i <- 0 until n - 1) {
val freq = Array.fill(26)(0)
for (j <- i until n) {
freq(s(j) - 'a') += 1
val maxFreq = freq.max
val minFreq = freq.filter(_ > 0).min
if (... | dolphin |
convert this code from Fortran to Scheme:
```fortran
function numSpecial(mat) result(special_positions)
integer, intent(in) :: mat(:,:)
integer :: m, n, i, j, special_positions
integer :: row(size(mat, 1)), col(size(mat, 2))
m = size(mat, 1)
n = size(mat, 2)
do i = 1, m
do j = 1, n
... | dolphin |
Please explain the reasoning behind the following solution and provide code in F#:
You are given an integer array `nums` and an integer `threshold`.
Find any subarray of `nums` of length `k` such that **every** element in the subarray is **greater** than `threshold / k`.
Return _the **size** of **any** such subarray_... | dolphin |
Please explain the reasoning behind the following solution and provide code in TypeScript:
Given the `root` of a binary tree, return _the same tree where every subtree (of the given tree) not containing a_ `1` _has been removed_.
A subtree of a node `node` is `node` plus every node that is a descendant of `node`.
**E... | dolphin |
port this code from Visual Basic .NET to Erlang:
```vb.net
Function count_good_substrings(s As String) As Integer
Dim count As Integer = 0
For i As Integer = 0 To s.Length - 3
If s(i) <> s(i + 1) AndAlso s(i) <> s(i + 2) AndAlso s(i + 1) <> s(i + 2) Then
count += 1
End If
Next
... | dolphin |
port this code to Lisp:
```fsharp
let binarySearchTreeDepth (order: int[]) =
let n = order.Length
let depths = Array.zeroCreate n
depths.[0] <- 1
for i in 1 .. n-1 do
let mutable depth = 1
for j in i-1 .. -1 .. 0 do
if order.[j] < order.[i] then
depth <- max d... | dolphin |
Please explain the following problem in detail and provide code in Fortran:
You are given a 2D integer array `ranges` where `ranges[i] = [starti, endi]` denotes that all integers between `starti` and `endi` (both **inclusive**) are contained in the `ith` range.
You are to split `ranges` into **two** (possibly empty) g... | dolphin |
translate this code from Scheme to Clojure:
```scheme
(define (sum-of-distances-in-tree n edges)
(define tree (make-hash))
(define (dfs node parent count res)
(for-each (lambda (child)
(unless (eq? child parent)
(dfs child node count res)
(set! count (alist-up... | dolphin |
Please explain the reasoning behind the following solution and provide code in Dart:
You are climbing a staircase. It takes `n` steps to reach the top.
Each time you can either climb `1` or `2` steps. In how many distinct ways can you climb to the top?
**Example 1:**
**Input:** n = 2
**Output:** 2
**Explanation:** T... | dolphin |
convert this code from Clojure to Objective-C:
```clojure
(defn convert-to-base7 [num]
(if (= num 0)
"0"
(let [result (atom "")
negative (if (< num 0) true false)]
(when negative (set! num (* num -1)))
(while (> num 0)
(reset! result (str (mod num 7) @result))
(set! num (... | dolphin |
convert this code to Haskell:
```fsharp
let largestPerimeter nums =
nums |> List.sortDescending
|> List.windowed 3
|> List.tryFind (fun [|a;b;c|] -> a < b + c)
|> Option.map (fun [|a;b;c|] -> a+b+c)
|> Option.defaultValue 0
``` | dolphin |
Please explain the reasoning behind the following solution and provide code in Elixir:
Given a string `s` of lower and upper case English letters.
A good string is a string which doesn't have **two adjacent characters** `s[i]` and `s[i + 1]` where:
* `0 <= i <= s.length - 2`
* `s[i]` is a lower-case letter and `s... | dolphin |
Please explain the reasoning behind the following solution and provide code in ANSI C:
There are `n` **unique** virus variants in an infinite 2D grid. You are given a 2D array `points`, where `points[i] = [xi, yi]` represents a virus originating at `(xi, yi)` on day `0`. Note that it is possible for **multiple** virus ... | dolphin |
Please explain the reasoning behind the following solution and provide code in python:
You are given two strings `s` and `t`.
You are allowed to remove any number of characters from the string `t`.
The score of the string is `0` if no characters are removed from the string `t`, otherwise:
* Let `left` be the minim... | dolphin |
port this code from ANSI C to Go:
```c
#include <stdio.h>
#include <stdbool.h>
int odd_even_jumps(int* arr, int n) {
bool can_reach_odd[n], can_reach_even[n];
can_reach_odd[n-1] = can_reach_even[n-1] = true;
int index_map[n];
index_map[arr[n-1]] = n - 1;
int good_indices = 1;
for(int i = n -... | dolphin |
Please explain the following problem in detail and provide code in Scheme:
A permutation `perm` of `n` integers of all the integers in the range `[1, n]` can be represented as a string `s` of length `n - 1` where:
* `s[i] == 'I'` if `perm[i] < perm[i + 1]`, and
* `s[i] == 'D'` if `perm[i] > perm[i + 1]`.
Given a ... | dolphin |
Please focus on the efficiency of this problem and provide code in Haskell:
Given a string `s` consisting only of characters _a_, _b_ and _c_.
Return the number of substrings containing **at least** one occurrence of all these characters _a_, _b_ and _c_.
**Example 1:**
**Input:** s = "abcabc "
**Output:** 10
**Exp... | dolphin |
Please explain the reasoning behind the following solution and provide code in Scala:
You are given an `m x n` `grid` where each cell can have one of three values:
* `0` representing an empty cell,
* `1` representing a fresh orange, or
* `2` representing a rotten orange.
Every minute, any fresh orange that is *... | dolphin |
Please focus on the functionality of this problem and provide code in Kotlin:
Given the `root` of a binary tree, construct a **0-indexed** `m x n` string matrix `res` that represents a **formatted layout** of the tree. The formatted layout matrix should be constructed using the following rules:
* The **height** of t... | dolphin |
translate this code to Kotlin:
```scala
import scala.collection.mutable.PriorityQueue
object Solution {
def maximumScore(a: Int, b: Int, c: Int): Int = {
val pq = PriorityQueue(a, b, c)(Ordering.Int.reverse)
var score = 0
while (pq.length >= 2) {
val x = pq.dequeue()
... | dolphin |
port this code from java to Perl:
```java
import java.util.HashMap;
class WordFilter {
private HashMap<String, Integer> dict;
public WordFilter(String[] words) {
dict = new HashMap<>();
for (int i = 0; i < words.length; i++) {
for (int j = 0; j <= words[i].length(); j++) {
... | dolphin |
Please focus on the functionality of this problem and provide code in Mojo:
Design a HashMap without using any built-in hash table libraries.
Implement the `MyHashMap` class:
* `MyHashMap()` initializes the object with an empty map.
* `void put(int key, int value)` inserts a `(key, value)` pair into the HashMap. ... | dolphin |
port this code from Julia to Swift:
```julia
function connect_two_islands(grid::Array{Int,2})::Int
n = size(grid)[1]
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
def fill_island(i, j, mark)
if i < 1 || i > n || j < 1 || j > n || grid[i, j] != 1
return
end
grid[i, j] = ... | dolphin |
Please explain the following problem in detail and provide code in Kotlin:
You are given a **0-indexed** 2D integer array `tires` where `tires[i] = [fi, ri]` indicates that the `ith` tire can finish its `xth` successive lap in `fi * ri(x-1)` seconds.
* For example, if `fi = 3` and `ri = 2`, then the tire would finis... | dolphin |
Please explain the reasoning behind the following solution and provide code in java:
Given a Circular Linked List node, which is sorted in non-descending order, write a function to insert a value `insertVal` into the list such that it remains a sorted circular list. The given node can be a reference to any single node ... | dolphin |
Please explain the reasoning behind the following solution and provide code in Elixir:
Given two strings `s` and `t` of lengths `m` and `n` respectively, return _the **minimum window**_ **_substring_** _of_ `s` _such that every character in_ `t` _(**including duplicates**) is included in the window_. If there is no suc... | dolphin |
Please write the following solution using Swift:
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 variable.... | dolphin |
convert this code to Kotlin:
```java
public String countAndSay(int n) {
if (n == 1) return "1";
String previous = countAndSay(n-1);
StringBuilder result = new StringBuilder();
int count = 1;
for (int i = 1; i < previous.length(); i++) {
if (previous.charAt(i) == previous.charAt(i-1)) {
... | dolphin |
convert this code to Mojo:
```vb.net
Function minOperations(nums() As Integer) As Integer
Dim count As Integer = 0
Array.Sort(nums)
Dim i As Integer = 0
While i < nums.Length
If nums(i) > 0 Then
Dim target As Integer = nums(i)
While i < nums.Length AndAlso nums(i) = targ... | dolphin |
Please explain the following problem in detail and provide code in Dart:
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 focus on the algorithm of this problem and provide code in Swift:
Given a string `path`, where `path[i] = 'N'`, `'S'`, `'E'` or `'W'`, each representing moving one unit north, south, east, or west, respectively. You start at the origin `(0, 0)` on a 2D plane and walk on the path specified by `path`.
Return `tru... | dolphin |
port this code from python to Scala:
```python
def next_balanced(n):
while True:
n += 1
digit_count = {}
temp = n
while temp:
digit = temp % 10
digit_count[digit] = digit_count.get(digit, 0) + 1
temp //= 10
balanced = all(k == v for k, v in... | dolphin |
Please focus on the algorithm of this problem and provide code in Haskell:
Given a data stream input of non-negative integers `a1, a2, ..., an`, summarize the numbers seen so far as a list of disjoint intervals.
Implement the `SummaryRanges` class:
* `SummaryRanges()` Initializes the object with an empty stream.
* ... | dolphin |
convert this code to java:
```go
type Logger struct {
messageTimestamps map[string]int
}
func Constructor() Logger {
return Logger{messageTimestamps: make(map[string]int)}
}
func (l *Logger) shouldPrintMessage(timestamp int, message string) bool {
if ts, ok := l.messageTimestamps[message]; !ok || timestam... | dolphin |
Please write the following solution using Perl:
The **abbreviation** of a word is a concatenation of its first letter, the number of characters between the first and last letter, and its last letter. If a word has only two characters, then it is an **abbreviation** of itself.
For example:
* `dog --> d1g` because th... | dolphin |
Please focus on the efficiency of this problem and provide code in C#:
You are given a 2D integer array `items` where `items[i] = [pricei, weighti]` denotes the price and weight of the `ith` item, respectively.
You are also given a **positive** integer `capacity`.
Each item can be divided into two items with ratios `... | dolphin |
Please write the following solution using Swift:
You are given the customer visit log of a shop represented by a **0-indexed** string `customers` consisting only of characters `'N'` and `'Y'`:
* if the `ith` character is `'Y'`, it means that customers come at the `ith` hour
* whereas `'N'` indicates that no custom... | dolphin |
Please write the following solution using Kotlin:
You are given two positive integer arrays `nums` and `numsDivide`. You can delete any number of elements from `nums`.
Return _the **minimum** number of deletions such that the **smallest** element in_ `nums` _**divides** all the elements of_ `numsDivide`. If this is no... | dolphin |
Please explain the reasoning behind the following solution and provide code in Dart:
You are given a binary string `s` consisting only of zeroes and ones.
A substring of `s` is considered balanced if **all zeroes are before ones** and the number of zeroes is equal to the number of ones inside the substring. Notice tha... | dolphin |
Please write the following solution using F#:
You are given an array `nums` consisting of positive integers.
Split the array into **one or more** disjoint subarrays such that:
* Each element of the array belongs to **exactly one** subarray, and
* The **GCD** of the elements of each subarray is strictly greater th... | dolphin |
port this code from C# to F#:
```csharp
using System.Collections.Generic;
using System.Linq;
public class Solution {
public string RemoveDuplicates(string s) {
Stack<char> stack = new Stack<char>();
foreach (char c in s) {
if (stack.Count > 0 && stack.Peek() == c) {
stac... | dolphin |
Please focus on the efficiency of this problem and provide code in C#:
An **ugly number** is a positive integer whose prime factors are limited to `2`, `3`, and `5`.
Given an integer `n`, return `true` _if_ `n` _is an **ugly number**_.
**Example 1:**
**Input:** n = 6
**Output:** true
**Explanation:** 6 = 2 \* 3
**E... | dolphin |
port this code to Objective-C:
```R
ListNode <- function(x) {
val <<- x
next <<- NULL
}
deleteDuplicates <- function(head) {
dummy <- ListNode(0)
dummy$next <- head
prev <- dummy
curr <- head
while (!is.null(curr)) {
while (!is.null(curr$next) && curr$val == curr$next$val) {
curr <- curr$next
... | dolphin |
Please explain the following problem in detail and provide code in TypeScript:
Given an `m x n` `picture` consisting of black `'B'` and white `'W'` pixels and an integer target, return _the number of **black** lonely pixels_.
A black lonely pixel is a character `'B'` that located at a specific position `(r, c)` where:... | dolphin |
translate this code from Erlang to Go:
```erlang
-module(min_stack).
-export([new/0, push/2, pop/1, top/1, get_min/1]).
new() -> {[], []}.
push(Val, {Stack, MinStack}) ->
Stack1 = [Val | Stack],
MinStack1 = case MinStack of
[] -> [Val];
[M | _] when Val =< M -> [Val | MinStack];
_ -> M... | dolphin |
Please focus on the algorithm of this problem and provide code in Elixir:
Given an integer array `nums` of length `n`, you want to create an array `ans` of length `2n` where `ans[i] == nums[i]` and `ans[i + n] == nums[i]` for `0 <= i < n` (**0-indexed**).
Specifically, `ans` is the **concatenation** of two `nums` arra... | dolphin |
translate this code from Visual Basic .NET to Elixir:
```vb.net
Public Function FindValidSplit(nums As Integer()) As Integer
Dim n As Integer = nums.Length
Dim prefix(n - 1) As Integer
Dim suffix(n - 1) As Integer
prefix(0) = nums(0)
suffix(n - 1) = nums(n - 1)
For i As Integer = 1 To n - 1
... | dolphin |
translate this code from Swift to R:
```swift
func kFrequentWords(_ words: [String], _ k: Int) -> [String] {
var wordCount = [String: Int]()
for word in words {
wordCount[word, default: 0] += 1
}
var heap = [(-count, word) for (word, count) in wordCount]
heap.sort()
var result = [String... | dolphin |
Please explain the following problem in detail and provide code in Objective-C:
A positive integer is _magical_ if it is divisible by either `a` or `b`.
Given the three integers `n`, `a`, and `b`, return the `nth` magical number. Since the answer may be very large, **return it modulo** `109 + 7`.
**Example 1:**
**In... | dolphin |
Please focus on the algorithm of this problem and provide code in Perl:
Given the `root` of a binary tree, split the binary tree into two subtrees by removing one edge such that the product of the sums of the subtrees is maximized.
Return _the maximum product of the sums of the two subtrees_. Since the answer may be t... | dolphin |
Please write the following solution using TypeScript:
A **valid cut** in a circle can be:
* A cut that is represented by a straight line that touches two points on the edge of the circle and passes through its center, or
* A cut that is represented by a straight line that touches one point on the edge of the circl... | dolphin |
Please explain the reasoning behind the following solution and provide code in PHP:
Your car starts at position `0` and speed `+1` on an infinite number line. Your car can go into negative positions. Your car drives automatically according to a sequence of instructions `'A'` (accelerate) and `'R'` (reverse):
* When ... | dolphin |
Please write the following solution using python:
Given a **0-indexed** string `word` and a character `ch`, **reverse** the segment of `word` that starts at index `0` and ends at the index of the **first occurrence** of `ch` (**inclusive**). If the character `ch` does not exist in `word`, do nothing.
* For example, ... | dolphin |
convert this code to Objective-C:
```elixir
defmodule Solution do
def is_printable(target_grid) do
color_bounds = %{}
{m, n} = {length(target_grid), length(target_grid[0])}
for i <- 0..(m-1), j <- 0..(n-1) do
color = target_grid[i][j]
if !Map.has_key?(color_bounds, color) do
bounds = ... | dolphin |
Please explain the reasoning behind the following solution and provide code in Erlang:
Given an integer array `queries` and a **positive** integer `intLength`, return _an array_ `answer` _where_ `answer[i]` _is either the_ `queries[i]th` _smallest **positive palindrome** of length_ `intLength` _or_ `-1` _if no such pal... | dolphin |
translate this code to Lisp:
```R
tree_diameter <- function(edges) {
tree <- vector(mode = "list", length = length(edges) + 1)
for (i in 1:length(edges)) {
tree[[edges[i][1] + 1]] <- c(tree[[edges[i][1] + 1]], edges[i][2] + 1)
tree[[edges[i][2] + 1]] <- c(tree[[edges[i][2] + 1]], edges[i][1] + 1)
}
q... | dolphin |
translate this code to Swift:
```
function MatchPattern(words: array of string; pattern: string): array of string;
var
result: array of string;
wordMap, patternMap: array of char;
match: boolean;
i, j: integer;
begin
SetLength(result, 0);
for i := 0 to High(words) do
begin
if Length(words[i]) <> Lengt... | dolphin |
port this code from Lisp to PHP:
```lisp
(defclass ParkingSystem ()
((big-slots :accessor big-slots :initarg :big-slots)
(medium-slots :accessor medium-slots :initarg :medium-slots)
(small-slots :accessor small-slots :initarg :small-slots)))
(defmethod add-car ((parking-system ParkingSystem) (car-type integer)... | dolphin |
port this code to python:
```kotlin
class Node(var `val`: Int, var left: Node?, var right: Node?)
class Solution {
fun treeToDoublyList(root: Node?): Node? {
if (root == null) return null
var first: Node? = null
var last: Node? = null
fun inOrder(node: Node?) {
... | dolphin |
Please explain the following problem in detail and provide code in java:
Given an array `nums` of positive integers, return the longest possible length of an array prefix of `nums`, such that it is possible to remove **exactly one** element from this prefix so that every number that has appeared in it will have the sam... | dolphin |
Please focus on the algorithm of this problem and provide code in C#:
Given a binary array `nums` and an integer `goal`, return _the number of non-empty **subarrays** with a sum_ `goal`.
A **subarray** is a contiguous part of the array.
**Example 1:**
**Input:** nums = \[1,0,1,0,1\], goal = 2
**Output:** 4
**Explana... | dolphin |
Please focus on the functionality of this problem and provide code in R:
Write a program to solve a Sudoku puzzle by filling the empty cells.
A sudoku solution must satisfy **all of the following rules**:
1. Each of the digits `1-9` must occur exactly once in each row.
2. Each of the digits `1-9` must occur exactly... | dolphin |
convert this code to Fortran:
```pascal
function reachNumber(target: Integer): Integer;
var
step, sum: Integer;
begin
target := Abs(target);
step := 0;
sum := 0;
while sum < target do
begin
Inc(step);
Inc(sum, step);
end;
while (sum - target) mod 2 <> 0 do
begin
Inc(step);
Inc(sum, ste... | dolphin |
Please explain the reasoning behind the following solution and provide code in Object Pascal:
A certain bug's home is on the x-axis at position `x`. Help them get there from position `0`.
The bug jumps according to the following rules:
* It can jump exactly `a` positions **forward** (to the right).
* It can jump ... | dolphin |
port this code from Ruby to java:
```ruby
def invalid_transactions(transactions)
invalids = []
transactions.each_with_index do |t1, i|
name1, time1, amount1, city1 = t1.split(",")
if amount1.to_i > 1000
invalids << t1
next
end
transactions[(i+1)..-1].each ... | dolphin |
Please focus on the functionality of this problem and provide code in Julia:
You want to water `n` plants in your garden with a watering can. The plants are arranged in a row and are labeled from `0` to `n - 1` from left to right where the `ith` plant is located at `x = i`. There is a river at `x = -1` that you can ref... | dolphin |
translate this code to Dart:
```clojure
(defn count-differences [a b]
(let [chars-a (seq a)
chars-b (seq b)]
(reduce + (map #(if (= %1 %2) 0 1) chars-a chars-b))))
(defn find-matching-words [queries dictionary]
(let [result []]
(doseq [query queries :while (not-any? #(= result %) queries)]
... | dolphin |
Please focus on the algorithm of this problem and provide code in javascript:
Given an `m x n` integer matrix `grid`, return _the maximum **score** of a path starting at_ `(0, 0)` _and ending at_ `(m - 1, n - 1)` moving in the 4 cardinal directions.
The **score** of a path is the minimum value in that path.
* For e... | dolphin |
port this code to Lua:
```typescript
function minDays(bloomDay: number[], m: number, k: number): number {
if (m * k > bloomDay.length) {
return -1;
}
let left = 1, right = Math.max(...bloomDay);
while (left < right) {
const mid = Math.floor((left + right) / 2);
let count = 0, bou... | dolphin |
Please write the following solution using Mojo:
A **valid number** can be split up into these components (in order):
1. A **decimal number** or an **integer**.
2. (Optional) An `'e'` or `'E'`, followed by an **integer**.
A **decimal number** can be split up into these components (in order):
1. (Optional) A sign c... | dolphin |
Please write the following solution using Ruby:
You are given an `m x n` **0-indexed** 2D array of positive integers `heights` where `heights[i][j]` is the height of the person standing at position `(i, j)`.
A person standing at position `(row1, col1)` can see a person standing at position `(row2, col2)` if:
* The ... | dolphin |
translate this code from Scala to java:
```scala
class Bitset(size: Int) {
private val bitset = new Array[Int]((size + 31) / 32)
def fix(idx: Int): Unit = {
if (idx < 0 || idx >= size) return
bitset(idx / 32) |= (1 << (idx % 32))
}
def unfix(idx: Int): Unit = {
if (idx < 0 || idx >= size) return
... | dolphin |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.