instruction_seed stringlengths 29 40.5k | source stringclasses 6
values |
|---|---|
convert this code to Ruby:
```fsharp
let minOperationsMaxProfit customers boardingCost runningCost =
let mutable waiting = 0
let mutable profit = 0
let mutable max_profit = 0
let mutable rotations = 0
let mutable result = -1
for i in 0..(customers.Length + Array.sum customers) - 1 do
if... | dolphin |
Please explain the reasoning behind the following solution and provide code in Kotlin:
Given an array of strings `nums` containing `n` **unique** binary strings each of length `n`, return _a binary string of length_ `n` _that **does not appear** in_ `nums`_. If there are multiple answers, you may return **any** of them... | dolphin |
Please write the following solution using Elixir:
In LeetCode Store, there are `n` items to sell. Each item has a price. However, there are some special offers, and a special offer consists of one or more different kinds of items with a sale price.
You are given an integer array `price` where `price[i]` is the price o... | dolphin |
convert this code to Rust:
```php
function difference_product_sum_digits($n) {
$product = 1;
$sum = 0;
while ($n > 0) {
$digit = $n % 10;
$product *= $digit;
$sum += $digit;
$n = (int) ($n / 10);
}
return $product - $sum;
}
``` | dolphin |
Please focus on the efficiency of this problem and provide code in Go:
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You must write an algorithm with `O(log n)` runtime complexity.
**Examp... | dolphin |
convert this code from Elixir to ANSI C:
```elixir
def max_score(nums1, nums2) do
i = 0
j = 0
score = 0
n1 = length(nums1)
n2 = length(nums2)
sum1 = 0
sum2 = 0
while i < n1 and j < n2 do
if hd(nums1) < hd(nums2) do
sum1 += hd(nums1)
nums1 = tl(nums1)
... | dolphin |
convert this code to python:
```fsharp
let minMoves(nums: int[]) =
Array.sort nums
let mid = nums.[(nums.Length - 1) / 2]
let mutable moves = 0
for num in nums do
moves <- moves + abs(num - mid)
moves
``` | dolphin |
translate this code from Kotlin to ANSI C:
```kotlin
class Solution {
fun expTree(s: String): TreeNode? {
fun precedence(a: Char, b: Char): Boolean {
if (a == '(')
return false
if (b == '(' || b == ')')
return true
if ((a == '*' || a == '/'... | dolphin |
Please focus on the functionality of this problem and provide code in Haskell:
You are given a positive integer `primeFactors`. You are asked to construct a positive integer `n` that satisfies the following conditions:
* The number of prime factors of `n` (not necessarily distinct) is **at most** `primeFactors`.
* ... | dolphin |
Please focus on the algorithm of this problem and provide code in Ruby:
Given two positive integers `n` and `k`, the binary string `Sn` is formed as follows:
* `S1 = "0 "`
* `Si = Si - 1 + "1 " + reverse(invert(Si - 1))` for `i > 1`
Where `+` denotes the concatenation operation, `reverse(x)` returns the reversed ... | dolphin |
Please explain the following problem in detail and provide code in Haskell:
Given an array `nums` with `n` integers, your task is to check if it could become non-decreasing by modifying **at most one element**.
We define an array is non-decreasing if `nums[i] <= nums[i + 1]` holds for every `i` (**0-based**) such that... | dolphin |
convert this code to Julia:
```lisp
(defun merge-2-lists (l1 l2)
(cond ((null l1) l2)
((null l2) l1)
((<= (car l1) (car l2))
(cons (car l1) (merge-2-lists (cdr l1) l2)))
(t (cons (car l2) (merge-2-lists l1 (cdr l2))))))
(defun merge-k-lists (lists)
(cond ((null lists) nil)
... | dolphin |
Please explain the reasoning behind the following solution and provide code in java:
Given the `head` of a singly linked list and two integers `left` and `right` where `left <= right`, reverse the nodes of the list from position `left` to position `right`, and return _the reversed list_.
**Example 1:**
**Input:** hea... | dolphin |
Please focus on the algorithm of this problem and provide code in C#:
You are given a **0-indexed** `m x n` binary matrix `matrix` and an integer `numSelect`, which denotes the number of **distinct** columns you must select from `matrix`.
Let us consider `s = {c1, c2, ...., cnumSelect}` as the set of columns selected ... | dolphin |
Please explain the following problem in detail and provide code in Perl:
There are `n` **unique** candies (labeled `1` through `n`) and `k` bags. You are asked to distribute **all** the candies into the bags such that every bag has **at least** one candy.
There can be multiple ways to distribute the candies. Two ways ... | dolphin |
port this code from Visual Basic .NET to Elixir:
```vb.net
Public Function MinOperations(ByVal nums1 As Integer(), ByVal nums2 As Integer()) As Integer
Dim sum1 As Integer = nums1.Sum()
Dim sum2 As Integer = nums2.Sum()
If sum1 > sum2 Then
Return MinOperations(nums2, nums1)
End If
Dim diff A... | dolphin |
convert this code to python:
```scala
class ListNode(var _x: Int = 0) {
var next: ListNode = null
var x: Int = _x
}
def deleteDuplicates(head: ListNode): ListNode = {
var current = head
while (current != null && current.next != null) {
if (current.x == current.next.x) {
current.next = current.next.ne... | dolphin |
Please explain the following problem in detail and provide code in c++:
Every **valid email** consists of a **local name** and a **domain name**, separated by the `'@'` sign. Besides lowercase letters, the email may contain one or more `'.'` or `'+'`.
* For example, in `"alice@leetcode.com "`, `"alice "` is the **lo... | dolphin |
Please focus on the efficiency of this problem and provide code in ANSI C:
There are some stones in different positions on the X-axis. You are given an integer array `stones`, the positions of the stones.
Call a stone an **endpoint stone** if it has the smallest or largest position. In one move, you pick up an **endpo... | dolphin |
Please write the following solution using R:
You are given a **positive** integer `n`.
Let `even` denote the number of even indices in the binary representation of `n` (**0-indexed**) with value `1`.
Let `odd` denote the number of odd indices in the binary representation of `n` (**0-indexed**) with value `1`.
Return... | dolphin |
Please explain the reasoning behind the following solution and provide code in Scala:
You are given two images, `img1` and `img2`, represented as binary, square matrices of size `n x n`. A binary matrix has only `0`s and `1`s as values.
We **translate** one image however we choose by sliding all the `1` bits left, rig... | dolphin |
Please write the following solution using Kotlin:
Given an array of integers `arr` and an integer `d`. In one step you can jump from index `i` to index:
* `i + x` where: `i + x < arr.length` and `0 < x <= d`.
* `i - x` where: `i - x >= 0` and `0 < x <= d`.
In addition, you can only jump from index `i` to index `j... | dolphin |
Please focus on the algorithm of this problem and provide code in Elixir:
Given a string `expression` of numbers and operators, return _all possible results from computing all the different possible ways to group numbers and operators_. You may return the answer in **any order**.
The test cases are generated such that... | dolphin |
Please explain the reasoning behind the following solution and provide code in Julia:
There is a **family tree** rooted at `0` consisting of `n` nodes numbered `0` to `n - 1`. You are given a **0-indexed** integer array `parents`, where `parents[i]` is the parent for node `i`. Since node `0` is the **root**, `parents[0... | dolphin |
port this code to PHP:
```c
#include <stdio.h>
int num_jewels_in_stones(char* jewels, char* stones) {
int count = 0;
for (int i = 0; stones[i] != '\0'; i++) {
for (int j = 0; jewels[j] != '\0'; j++) {
if (stones[i] == jewels[j]) {
count++;
break;
... | dolphin |
Please focus on the functionality of this problem and provide code in java:
You are given a string `word` that consists of digits and lowercase English letters.
You will replace every non-digit character with a space. For example, `"a123bc34d8ef34 "` will become `" 123 34 8 34 "`. Notice that you are left with some in... | dolphin |
translate this code to C#:
```vbnet
Imports System.Collections.Generic
Public Class Solution
Public Function EventualSafeNodes(ByVal graph As Integer()()) As IList(Of Integer)
Dim n As Integer = graph.Length
Dim safeNodes As New HashSet(Of Integer)()
Dim visitedNodes As New HashSet(Of Integ... | dolphin |
convert this code to Mojo:
```fsharp
type Table(columns: int) =
let mutable next_id = 1
let mutable rows = []
member this.insertRow(row: string list) =
rows <- [(next_id, row)] @ rows
next_id <- next_id + 1
member this.deleteRow(rowId: int) =
rows <- List.filter (fun row -> fst... | dolphin |
port this code from Rust to Scala:
```rust
fn validate_ip(query_ip: &str) -> String {
let ipv4_parts: Vec<&str> = query_ip.split('.').collect();
let ipv6_parts: Vec<&str> = query_ip.split(':').collect();
if ipv4_parts.len() == 4 {
if is_valid_ipv4(&ipv4_parts) {
return String::from("IPv... | dolphin |
Please focus on the efficiency of this problem and provide code in Kotlin:
You are given a **0-indexed** 2D integer array `grid` of size `m x n`. Each cell has one of two values:
* `0` represents an **empty** cell,
* `1` represents an **obstacle** that may be removed.
You can move up, down, left, or right from an... | dolphin |
Please focus on the algorithm of this problem and provide code in Perl:
You are given an array `routes` representing bus routes where `routes[i]` is a bus route that the `ith` bus repeats forever.
* For example, if `routes[0] = [1, 5, 7]`, this means that the `0th` bus travels in the sequence `1 -> 5 -> 7 -> 1 -> 5 ... | dolphin |
Please write the following solution using R:
A phrase is a **palindrome** if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
Given a string `s`, return `true` _if it... | dolphin |
Please explain the reasoning behind the following solution and provide code in Erlang:
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.
... | dolphin |
Please explain the following problem in detail and provide code in Scala:
You are painting a fence of `n` posts with `k` different colors. You must paint the posts following these rules:
* Every post must be painted **exactly one** color.
* There **cannot** be three or more **consecutive** posts with the same colo... | dolphin |
Please write the following solution using Lisp:
Given an array of `prices` `[p1,p2...,pn]` and a `target`, round each price `pi` to `Roundi(pi)` so that the rounded array `[Round1(p1),Round2(p2)...,Roundn(pn)]` sums to the given `target`. Each operation `Roundi(pi)` could be either `Floor(pi)` or `Ceil(pi)`.
Return th... | dolphin |
Please write the following solution using Scheme:
You are given two integers, `x` and `y`, which represent your current location on a Cartesian grid: `(x, y)`. You are also given an array `points` where each `points[i] = [ai, bi]` represents that a point exists at `(ai, bi)`. A point is **valid** if it shares the same ... | dolphin |
Please explain the following problem in detail and provide code in Swift:
Given a `root` of an N-ary tree, return a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) (clone) of the tree.
Each node in the n-ary tree contains a val (`int`) and a list (`List[Node]`) of its children.
class Node {
... | dolphin |
port this code from javascript to Dart:
```javascript
function pillowHolder(n, time) {
time %= (2 * n - 2);
if (time <= n - 1) return time + 1;
else return 2 * n - time - 1;
}
```
| dolphin |
Please write the following solution using Kotlin:
A phrase is a **palindrome** if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
Given a string `s`, return `true` _... | dolphin |
Please write the following solution using c++:
You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day.
Find the maximum profit you can achieve. You may complete **at most two transactions**.
**Note:** You may not engage in multiple transactions simultaneously (i.e., you must ... | dolphin |
port this code from java to Perl:
```java
public int minCandies(int[] ratings) {
int n = ratings.length;
int[] candies = new int[n];
for (int i = 0; i < n; i++) candies[i] = 1;
for (int i = 1; i < n; i++) {
if (ratings[i] > ratings[i - 1]) candies[i] = candies[i - 1] + 1;
}
for (int i =... | dolphin |
port this code to Rust:
```R
countSubgraphsForEachD <- function(n, edges){
tree <- list()
for (i in 1:n){
tree[[i]] <- c()
}
for (i in 1:length(edges)){
u <- edges[i][1]
v <- edges[i][2]
tree[[u]] <- c(tree[[u]], v)
tree[[v]] <- c(tree[[v]], u)
}
dfs <- function(node, parent){
dep... | dolphin |
Please write the following solution using Visual Basic .NET:
You are given an integer array `gifts` denoting the number of gifts in various piles. Every second, you do the following:
* Choose the pile with the maximum number of gifts.
* If there is more than one pile with the maximum number of gifts, choose any.
*... | dolphin |
convert this code to Mojo:
```typescript
function maxProductOfPalindromicSubsequences(s: string): number {
const n = s.length;
const dp: number[][] = Array.from({ length: n }, () => Array(n).fill(0));
for (let i = n - 1; i >= 0; i--) {
for (let j = i + 1; j < n; j++) {
if (s[i] === s[j]... | dolphin |
Please write the following solution using Rust:
Given an integer array `nums` and two integers `firstLen` and `secondLen`, return _the maximum sum of elements in two non-overlapping **subarrays** with lengths_ `firstLen` _and_ `secondLen`.
The array with length `firstLen` could occur before or after the array with len... | dolphin |
Please explain the reasoning behind the following solution and provide code in javascript:
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` ... | dolphin |
Please write the following solution using PHP:
You are given an array of network towers `towers`, where `towers[i] = [xi, yi, qi]` denotes the `ith` network tower with location `(xi, yi)` and quality factor `qi`. All the coordinates are **integral coordinates** on the X-Y plane, and the distance between the two coordin... | dolphin |
Please focus on the efficiency of this problem and provide code in Go:
There is a special kind of apple tree that grows apples every day for `n` days. On the `ith` day, the tree grows `apples[i]` apples that will rot after `days[i]` days, that is on day `i + days[i]` the apples will be rotten and cannot be eaten. On so... | dolphin |
port this code from C# to java:
```csharp
public static int CountLatticePoints(int[][] circles)
{
int xmin = int.MaxValue, xmax = int.MinValue;
int ymin = int.MaxValue, ymax = int.MinValue;
foreach (int[] circle in circles)
{
xmin = Math.Min(xmin, circle[0] - circle[2]);
xmax = Math.Max(... | dolphin |
Please explain the reasoning behind the following solution and provide code in PHP:
A binary tree is **uni-valued** if every node in the tree has the same value.
Given the `root` of a binary tree, return `true` _if the given tree is **uni-valued**, or_ `false` _otherwise._
**Example 1:**
**Input:** root = \[1,1,1,1,... | dolphin |
Please focus on the algorithm of this problem and provide code in Clojure:
You are given an integer array `nums` (**0-indexed**). In one operation, you can choose an element of the array and increment it by `1`.
* For example, if `nums = [1,2,3]`, you can choose to increment `nums[1]` to make `nums = [1,**3**,3]`.
... | dolphin |
Please explain the reasoning behind the following solution and provide code in python:
Given a string `s` containing just the characters `'('`, `')'`, `'{'`, `'}'`, `'['` and `']'`, determine if the input string is valid.
An input string is valid if:
1. Open brackets must be closed by the same type of brackets.
2. ... | dolphin |
Please focus on the functionality of this problem and provide code in Scala:
Given an integer array `nums`, return `true` _if there exists a triple of indices_ `(i, j, k)` _such that_ `i < j < k` _and_ `nums[i] < nums[j] < nums[k]`. If no such indices exists, return `false`.
**Example 1:**
**Input:** nums = \[1,2,3,4... | dolphin |
port this code from TypeScript to Go:
```typescript
function successfulPairs(spells: number[], potions: number[], success: number): number[] {
const pairs: number[] = new Array(spells.length).fill(0);
const sortedPotions: number[] = potions.sort((a, b) => a - b);
for (let i = 0; i < spells.length; i++)... | dolphin |
Please write the following solution using Groovy:
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 number other than `1`.
Ret... | dolphin |
Please explain the reasoning behind the following solution and provide code in Scala:
A tree rooted at node 0 is given as follows:
* The number of nodes is `nodes`;
* The value of the `ith` node is `value[i]`;
* The parent of the `ith` node is `parent[i]`.
Remove every subtree whose sum of values of nodes is ze... | dolphin |
Please explain the reasoning behind the following solution and provide code in Julia:
Given a string `licensePlate` and an array of strings `words`, find the **shortest completing** word in `words`.
A **completing** word is a word that **contains all the letters** in `licensePlate`. **Ignore numbers and spaces** in `l... | dolphin |
translate this code to Rust:
```typescript
function kthSmallestPath(destination: number[], k: number): string {
const [row, col] = destination;
const n = row + col;
const dp: number[][] = Array.from({ length: n + 1 }, () => Array(col + 1).fill(0));
for (let i = 0; i <= n; i++) {
dp[i][0] = 1;
... | dolphin |
Please explain the reasoning behind the following solution and provide code in Elixir:
Implement the `RandomizedSet` class:
* `RandomizedSet()` Initializes the `RandomizedSet` object.
* `bool insert(int val)` Inserts an item `val` into the set if not present. Returns `true` if the item was not present, `false` oth... | dolphin |
Please explain the reasoning behind the following solution and provide code in Objective-C:
Given an array of **unique** strings `words`, return _all the_ **[word squares](https://en.wikipedia.org/wiki/Word_square)** _you can build from_ `words`. The same word from `words` can be used **multiple times**. You can return... | dolphin |
Please write the following solution using c++:
Given a Circular Linked List node, which is sorted in non-descending order, write a function to insert a value `insertVal` into the list such that it remains a sorted circular list. The given node can be a reference to any single node in the list and may not necessarily be... | dolphin |
port this code from Perl to Erlang:
```perl
sub minimumEffort {
my @tasks = @_;
@tasks = sort { ($b->[1] - $b->[0]) <=> ($a->[1] - $a->[0]) } @tasks;
my ($ans, $sum_energy) = (0, 0);
foreach my $task (@tasks) {
$ans = ($ans > $sum_energy + $task->[1]) ? $ans : ($sum_energy + $task->[1]);
... | dolphin |
Please explain the following problem in detail and provide code in ANSI 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
... | dolphin |
convert this code from Object Pascal to Erlang:
```pascal
function numberOfMatches(n: integer): integer;
var
matches: integer;
begin
matches := 0;
while n > 1 do
begin
matches := matches + (n div 2);
n := (n + 1) div 2;
end;
Result := matches;
end;
``` | dolphin |
translate this code from Groovy to Object Pascal:
```groovy
import java.util.Deque;
import java.util.LinkedList;
List<Integer> maxSlidingWindow(int[] nums, int k) {
Deque<Integer> dq = new LinkedList<>();
List<Integer> result = new ArrayList<>();
for (int i = 0; i < nums.length; i++) {
while (!dq.... | dolphin |
convert this code from c++ to Visual Basic .NET:
```cpp
int numberOfWays(int numPeople) {
const int MOD = 1000000007;
vector<int> dp(numPeople / 2 + 1);
dp[0] = 1;
for (int i = 1; i <= numPeople / 2; ++i) {
for (int j = 1; j <= i; ++j) {
dp[i] = (dp[i] + ((long long) dp[i - j] * dp[j... | dolphin |
port this code from TypeScript to Fortran:
```typescript
function isPrefixString(s: string, words: string[]): boolean {
let i = 0;
let j = 0;
let currStr = "";
while (i < words.length && currStr !== s) {
currStr += words[i];
i++;
}
return currStr === s;
}
``` | dolphin |
Please explain the following problem in detail and provide code in java:
Given a string `s`, return _the maximum number of unique substrings that the given string can be split into_.
You can split string `s` into any list of **non-empty substrings**, where the concatenation of the substrings forms the original string.... | dolphin |
Please explain the following problem in detail and provide code in Scala:
The **median** is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle values.
* For examples, if `arr = [2,3,4]`, the median is `3`.
* For exampl... | dolphin |
Please explain the following problem in detail and provide code in ANSI C:
A word's **generalized abbreviation** can be constructed by taking any number of **non-overlapping** and **non-adjacent** substrings and replacing them with their respective lengths.
* For example, `"abcde "` can be abbreviated into:
* ... | dolphin |
Please focus on the algorithm of this problem and provide code in Julia:
There is a supermarket that is frequented by many customers. The products sold at the supermarket are represented as two parallel integer arrays `products` and `prices`, where the `ith` product has an ID of `products[i]` and a price of `prices[i]`... | dolphin |
Please focus on the efficiency of this problem and provide code in Scala:
You have an initial **power** of `power`, an initial **score** of `0`, and a bag of `tokens` where `tokens[i]` is the value of the `ith` token (0-indexed).
Your goal is to maximize your total **score** by potentially playing each token in one of... | dolphin |
Please focus on the functionality of this problem and provide code in Lisp:
You are given an `m x n` binary matrix `grid`. An island is a group of `1`'s (representing land) connected **4-directionally** (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.
An island is considered... | dolphin |
translate this code to Haskell:
```scheme
(define (alphabet-position-sum s k)
(let loop ((sum 0) (k k))
(cond ((= k 0) sum)
(else (let loop2 ((new-sum 0) (sum sum))
(cond ((= sum 0) (loop sum (- k 1)))
(else (loop2 (+ new-sum (remainder sum 10)) (quotient sum 10... | dolphin |
convert this code from Haskell to Scala:
```haskell
import qualified Data.Map as Map
import qualified Data.Set as Set
advantageCount :: [Int] -> [Int] -> [Int]
advantageCount nums1 nums2 = go (Map.fromListWith (+) $ zip nums1 (repeat 1)) nums2 []
where
go _ [] res = reverse res
go m (x : xs) res =
case... | dolphin |
Please focus on the algorithm of this problem and provide code in F#:
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` arrays.
... | dolphin |
port this code to Julia:
```groovy
def isShortestAndUniqueSupersequence(nums, sequences) {
def pos = nums.withIndex().collectEntries() { [(it.value): it.index] }
sequences.each { seq ->
if (pos[seq[0]] > pos[seq[-1]]) {
return false
}
}
return true
}
``` | dolphin |
translate this code to Julia:
```lua
function numberOfEvenSubarrays(nums)
local n = #nums
local evenCount, oddCount, result = 0, 0, 0
for i = 1, n do
local num = nums[i]
if num % 2 == 0 then
evenCount = evenCount + 1
result = result + evenCount
else
... | dolphin |
Please explain the following problem in detail and provide code in Erlang:
Given two integer arrays `arr1` and `arr2`, and the integer `d`, _return the distance value between the two arrays_.
The distance value is defined as the number of elements `arr1[i]` such that there is not any element `arr2[j]` where `|arr1[i]-... | dolphin |
port this code from Scala to C#:
```scala
def buildRooms(prevRoom: Array[Int]): Int = {
val n = prevRoom.length
val inDegree = Array.ofDim[Int](n)
for (i <- 0 until n) {
if (prevRoom(i) != -1)
inDegree(prevRoom(i)) += 1
}
val queue = scala.collection.mutable.Queue[Int]()
for (i <- 0 until n) {
... | dolphin |
translate this code from Visual Basic .NET to c++:
```vb.net
Function MinOperationsToAlternate(ByVal s As String) As Integer
Dim count_a As Integer = 0
Dim count_b As Integer = 0
For i As Integer = 0 To s.Length - 1
If i Mod 2 = 0 Then
If s(i) = "0" Then
count_a += 1
... | dolphin |
convert this code from Perl to c++:
```perl
sub is_palindrome {
my $x = shift;
my $s = "$x";
my $n = length($s);
for (my $i = 0; $i < int($n/2); $i++) {
return 0 if substr($s, $i, 1) ne substr($s, $n-$i-1, 1);
}
return 1;
}
sub super_palindrome_count {
my ($left, $right) = @_;
m... | dolphin |
port this code from Swift to Lisp:
```swift
func maxCoins(_ piles: [[Int]], _ k: Int) -> Int {
var pq = [Int]()
for pile in piles {
for coin in pile {
pq.append(-coin)
}
}
pq.sort()
var max_value = 0
for i in 0..<k {
max_value -= pq[i]
}
return ma... | dolphin |
port this code from Swift to TypeScript:
```swift
func isMirror(s: String, k: Int) -> Bool {
if s.first == "0" {
return false
}
var num = Int(s)!
var newNum = 0
var base = 1
while num > 0 {
newNum += (num % k) * base
base *= 10
num /= k
}
return newNum == ... | dolphin |
Please explain the reasoning behind the following solution and provide code in Erlang:
It is a sweltering summer day, and a boy wants to buy some ice cream bars.
At the store, there are `n` ice cream bars. You are given an array `costs` of length `n`, where `costs[i]` is the price of the `ith` ice cream bar in coins. ... | dolphin |
Please focus on the efficiency of this problem and provide code in ANSI C:
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 ... | dolphin |
port this code from TypeScript to javascript:
```typescript
function checkNum(num: string): boolean {
const freq = new Array(10).fill(0);
for (let i = 0; i < num.length; i++) {
freq[parseInt(num[i])] += 1;
}
for (let i = 0; i < num.length; i++) {
if (freq[i] != parseInt(num[i])) {
... | dolphin |
Please explain the following problem in detail and provide code in Visual Basic .NET:
The **alternating sum** of a **0-indexed** array is defined as the **sum** of the elements at **even** indices **minus** the **sum** of the elements at **odd** indices.
* For example, the alternating sum of `[4,2,5,3]` is `(4 + 5) ... | dolphin |
Please focus on the algorithm of this problem and provide code in Rust:
Let's define a function `countUniqueChars(s)` that returns the number of unique characters on `s`.
* For example, calling `countUniqueChars(s)` if `s = "LEETCODE "` then `"L "`, `"T "`, `"C "`, `"O "`, `"D "` are the unique characters since they... | dolphin |
Please write the following solution using Visual Basic .NET:
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
**Output:** 4
**Explanation:*... | dolphin |
translate this code from F# to Scala:
```fsharp
let generate (numRows:int) =
let pascalsTriangle = List.empty<List<int>>()
for i = 0 to numRows-1 do
let row = List.empty<int>()
row <- 1::row
if i > 0 then
for j = 1 to i-1 do
row <- row @ [ (List.item (j-1) (Li... | dolphin |
convert this code from Kotlin to python:
```kotlin
class TreeNode(var `val`: Int = 0) {
var left: TreeNode? = null
var right: TreeNode? = null
}
fun sumOfLeftLeaves(root: TreeNode?): Int {
if (root == null) return 0
var leftSum = 0
if (root.left != null && root.left?.left == null && root.left?.righ... | dolphin |
Please write the following solution using Julia:
Given an integer array `data` representing the data, return whether it is a valid **UTF-8** encoding (i.e. it translates to a sequence of valid UTF-8 encoded characters).
A character in **UTF8** can be from **1 to 4 bytes** long, subjected to the following rules:
1. F... | dolphin |
Please explain the following problem in detail and provide code in R:
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 example, ... | dolphin |
Please explain the reasoning behind the following solution and provide code in Go:
Given an array of integers `arr`, a **lucky integer** is an integer that has a frequency in the array equal to its value.
Return _the largest **lucky integer** in the array_. If there is no **lucky integer** return `-1`.
**Example 1:**... | dolphin |
translate this code from Haskell to Clojure:
```haskell
import qualified Data.Map.Strict as Map
data BrowserHistory = BrowserHistory {
homepage :: String,
history :: [String],
index :: Int
}
newBrowserHistory :: String -> BrowserHistory
newBrowserHistory homepage = BrowserHistory homepage [homepage] 0
vi... | dolphin |
Please focus on the efficiency of this problem and provide code in Scala:
Given an integer `n`, return _`true` if it is a power of three. Otherwise, return `false`_.
An integer `n` is a power of three, if there exists an integer `x` such that `n == 3x`.
**Example 1:**
**Input:** n = 27
**Output:** true
**Explanation... | dolphin |
Please explain the following problem in detail and provide code in Elixir:
You are currently designing a dynamic array. You are given a **0-indexed** integer array `nums`, where `nums[i]` is the number of elements that will be in the array at time `i`. In addition, you are given an integer `k`, the **maximum** number o... | dolphin |
Please explain the reasoning behind the following solution and provide code in Objective-C:
Given two **sorted 0-indexed** integer arrays `nums1` and `nums2` as well as an integer `k`, return _the_ `kth` _(**1-based**) smallest product of_ `nums1[i] * nums2[j]` _where_ `0 <= i < nums1.length` _and_ `0 <= j < nums2.leng... | dolphin |
port this code to Rust:
```pascal
function minimumDeleteSum(s1: string; s2: string): integer;
var
dp: array of array of integer;
i, j: integer;
begin
SetLength(dp, Length(s1) + 1, Length(s2) + 1);
for i := 1 to Length(s1) do
dp[i][0] := dp[i - 1][0] + Ord(s1[i]);
for j := 1 to Length(s2) do
dp[0][j] :... | dolphin |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.