instruction_seed
stringlengths
29
40.5k
source
stringclasses
6 values
Please focus on the algorithm of this problem and provide code in python: Given two arrays of strings `list1` and `list2`, find the **common strings with the least index sum**. A **common string** is a string that appeared in both `list1` and `list2`. A **common string with the least index sum** is a common string su...
dolphin
port this code to Julia: ```typescript function findBrightestPosition(lights: number[][]): number { let n = lights.length; let maxBrightness = 0; let brightestPos = Infinity; for (let i = 0; i < n; i++) { let pos = lights[i][0]; let range = lights[i][1]; let brightness = 0; for (let j = 0; j <...
dolphin
Please explain the reasoning behind the following solution and provide code in Object Pascal: Given an integer array **sorted** in non-decreasing order, there is exactly one integer in the array that occurs more than 25% of the time, return that integer. **Example 1:** **Input:** arr = \[1,2,2,6,6,6,6,7,10\] **Output...
dolphin
Please write the following solution using C#: Given an integer array `nums`, reorder it such that `nums[0] < nums[1] > nums[2] < nums[3]...`. You may assume the input array always has a valid answer. **Example 1:** **Input:** nums = \[1,5,1,1,6,4\] **Output:** \[1,6,1,5,1,4\] **Explanation:** \[1,4,1,5,1,6\] is also...
dolphin
port this code from python to Haskell: ```python def check_good_line(board, r, c, color, dr, dc): opp_color = 'B' if color == 'W' else 'W' count = 0 r += dr c += dc while 0 <= r < 8 and 0 <= c < 8 and board[r][c] == opp_color: count += 1 r += dr c += dc return 0 <= r < 8 ...
dolphin
port this code to Scheme: ```pascal type TMagicDictionary = class private word_list: TDictionary<Integer, TArray<string>>; public constructor Create; procedure buildDict(dictionary: TArray<string>); function search(searchWord: string): Boolean; end; constructor TMagicDictionary.Create; begin ...
dolphin
Please explain the following problem in detail and provide code in Mojo: You are installing a billboard and want it to have the largest height. The billboard will have two steel supports, one on each side. Each steel support must be an equal height. You are given a collection of `rods` that can be welded together. For...
dolphin
Please write the following solution using C#: Given the `head` of a linked list, find all the values that appear **more than once** in the list and delete the nodes that have any of those values. Return _the linked list after the deletions._ **Example 1:** **Input:** head = \[1,2,3,2\] **Output:** \[1,3\] **Explanat...
dolphin
Please explain the reasoning behind the following solution and provide code in PHP: 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 colo...
dolphin
Please explain the following problem in detail and provide code in c++: Given an integer `numRows`, return the first numRows of **Pascal's triangle**. In **Pascal's triangle**, each number is the sum of the two numbers directly above it as shown: **Example 1:** **Input:** numRows = 5 **Output:** \[\[1\],\[1,1\],\[1,...
dolphin
Please focus on the functionality of this problem and provide code in Lua: Given the `root` of a binary tree, return _the length of the longest **consecutive sequence path**_. A **consecutive sequence path** is a path where the values **increase by one** along the path. Note that the path can start **at any node** in...
dolphin
convert this code to Objective-C: ```go func countArrangement(n int) int { var helper func(int, []bool, int) int helper = func(idx int, visited []bool, n int) int { if idx > n { return 1 } count := 0 for i := 1; i <= n; i++ { if !visited[i] && (idx % i == ...
dolphin
Please focus on the functionality of this problem and provide code in Elixir: You are given a map of a server center, represented as a `m * n` integer matrix `grid`, where 1 means that on that cell there is a server and 0 means that it is no server. Two servers are said to communicate if they are on the same row or on ...
dolphin
Please write the following solution using Scala: You are given two string arrays, `queries` and `dictionary`. All words in each array comprise of lowercase English letters and have the same length. In one **edit** you can take a word from `queries`, and change any letter in it to any other letter. Find all words from ...
dolphin
Please focus on the efficiency of this problem and provide code in TypeScript: The **DNA sequence** is composed of a series of nucleotides abbreviated as `'A'`, `'C'`, `'G'`, and `'T'`. * For example, `"ACGAATTCCG "` is a **DNA sequence**. When studying **DNA**, it is useful to identify repeated sequences within th...
dolphin
convert this code from Objective-C to TypeScript: ```objective-c #import <Foundation/Foundation.h> NSArray* kthSmallestIndex(NSArray* nums, NSArray* queries) { NSMutableArray* answer = [[NSMutableArray alloc] init]; NSMutableArray* indices = [[NSMutableArray alloc] init]; for (int i = 0; i < nums.coun...
dolphin
convert this code to Lua: ``` (defun is-valid-preorder (preorder) (let ((stack '()) (lower-bound most-negative-fixnum)) (dolist (num preorder) (cond ((< num lower-bound) (return nil)) ((and stack (> num (car stack))) (loop while (and stack (> num (car stack))) ...
dolphin
Please focus on the algorithm of this problem and provide code in F#: You have a queue of integers, you need to retrieve the first unique integer in the queue. Implement the `FirstUnique` class: * `FirstUnique(int[] nums)` Initializes the object with the numbers in the queue. * `int showFirstUnique()` returns the...
dolphin
Please explain the reasoning behind the following solution and provide code in Haskell: The **array-form** of an integer `num` is an array representing its digits in left to right order. * For example, for `num = 1321`, the array form is `[1,3,2,1]`. Given `num`, the **array-form** of an integer, and an integer `k`...
dolphin
translate this code to java: ```kotlin fun findLongestPrefix(words: Array<String>): String { val set = words.toHashSet() words.sortBy { it.length } words.reverse() for (word in words) { var flag = true for (i in 1..word.length) { if (!set.contains(word.substring(0, i))) { ...
dolphin
Please explain the reasoning behind the following solution and provide code in javascript: **Run-length encoding** is a compression algorithm that allows for an integer array `nums` with many segments of **consecutive repeated** numbers to be represented by a (generally smaller) 2D array `encoded`. Each `encoded[i] = [...
dolphin
Please focus on the algorithm of this problem and provide code in c++: You are given an **integer** array `pref` of size `n`. Find and return _the array_ `arr` _of size_ `n` _that satisfies_: * `pref[i] = arr[0] ^ arr[1] ^ ... ^ arr[i]`. Note that `^` denotes the **bitwise-xor** operation. It can be proven that th...
dolphin
Please focus on the efficiency of this problem and provide code in Rust: You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in **adjacent** plots. Given an integer array `flowerbed` containing `0`'s and `1`'s, where `0` means empty and `1` means not e...
dolphin
Please focus on the efficiency of this problem and provide code in Swift: Given an array of points on the **X-Y** plane `points` where `points[i] = [xi, yi]`, return _the area of the largest triangle that can be formed by any three different points_. Answers within `10-5` of the actual answer will be accepted. **Examp...
dolphin
Please explain the following problem in detail and provide code in Rust: You are given two integers `memory1` and `memory2` representing the available memory in bits on two memory sticks. There is currently a faulty program running that consumes an increasing amount of memory every second. At the `ith` second (startin...
dolphin
Please explain the reasoning behind the following solution and provide code in Ruby: For a string `sequence`, a string `word` is **`k`\-repeating** if `word` concatenated `k` times is a substring of `sequence`. The `word`'s **maximum `k`\-repeating value** is the highest value `k` where `word` is `k`\-repeating in `seq...
dolphin
Please write the following solution using PHP: Given a **positive** integer `n`, return _the smallest positive integer that is a multiple of **both**_ `2` _and_ `n`. **Example 1:** **Input:** n = 5 **Output:** 10 **Explanation:** The smallest multiple of both 5 and 2 is 10. **Example 2:** **Input:** n = 6 **Output:...
dolphin
Please explain the reasoning behind the following solution and provide code in Object Pascal: Given an integer `x`, return `true` _if_ `x` _is a_ _**palindrome**__, and_ `false` _otherwise_. **Example 1:** **Input:** x = 121 **Output:** true **Explanation:** 121 reads as 121 from left to right and from right to left....
dolphin
Please write the following solution using Scala: You have a movie renting company consisting of `n` shops. You want to implement a renting system that supports searching for, booking, and returning movies. The system should also support generating a report of the currently rented movies. Each movie is given as a 2D in...
dolphin
Please explain the reasoning behind the following solution and provide code in ANSI C: Given an n-ary tree, return the _level order_ traversal of its nodes' values. _Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples)._ **Ex...
dolphin
translate this code to Rust: ```F# let findMissingRanges(nums: int list, lower: int, upper: int) : string list = let mutable result : string list = [] let mutable prev : int = lower - 1 for i = 0 to nums.Length do let num = if i < nums.Length then nums.[i] else upper + 1 if num - prev >= 2 ...
dolphin
Please write the following solution using Kotlin: Given an `n x n` binary matrix `image`, flip the image **horizontally**, then invert it, and return _the resulting image_. To flip an image horizontally means that each row of the image is reversed. * For example, flipping `[1,1,0]` horizontally results in `[0,1,1]`...
dolphin
Please explain the following problem in detail and provide code in TypeScript: You are given an integer matrix `isWater` of size `m x n` that represents a map of **land** and **water** cells. * If `isWater[i][j] == 0`, cell `(i, j)` is a **land** cell. * If `isWater[i][j] == 1`, cell `(i, j)` is a **water** cell. ...
dolphin
Please explain the reasoning behind the following solution and provide code in Objective-C: A [**trie**](https://en.wikipedia.org/wiki/Trie) (pronounced as "try ") or **prefix tree** is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data...
dolphin
Please explain the following problem in detail and provide code in Haskell: On an `8 x 8` chessboard, there is **exactly one** white rook `'R'` and some number of white bishops `'B'`, black pawns `'p'`, and empty squares `'.'`. When the rook moves, it chooses one of four cardinal directions (north, east, south, or wes...
dolphin
Please write the following solution using Julia: Given an array of strings `words` and an integer `k`, return _the_ `k` _most frequent strings_. Return the answer **sorted** by **the frequency** from highest to lowest. Sort the words with the same frequency by their **lexicographical order**. **Example 1:** **Input:...
dolphin
Please focus on the efficiency of this problem and provide code in Scala: Given the coordinates of four points in 2D space `p1`, `p2`, `p3` and `p4`, return `true` _if the four points construct a square_. The coordinate of a point `pi` is represented as `[xi, yi]`. The input is **not** given in any order. A **valid s...
dolphin
Please focus on the functionality of this problem and provide code in javascript: Given the `head` of a singly linked list, return _the middle node of the linked list_. If there are two middle nodes, return **the second middle** node. **Example 1:** **Input:** head = \[1,2,3,4,5\] **Output:** \[3,4,5\] **Explanation...
dolphin
convert this code from TypeScript to Julia: ```typescript function replaceSublistWithList(list1: ListNode | null, a: number, b: number, list2: ListNode | null): ListNode | null { let curr = list1; for (let i = 1; i < a; i++) { curr = curr.next; } let beforeSublist = curr; for (let i = a; i <...
dolphin
Please explain the reasoning behind the following solution and provide code in Perl: Given the `root` of a binary search tree, and an integer `k`, return _the_ `kth` _smallest value (**1-indexed**) of all the values of the nodes in the tree_. **Example 1:** **Input:** root = \[3,1,4,null,2\], k = 1 **Output:** 1 **E...
dolphin
Please explain the following problem in detail and provide code in Dart: You are given an `m x n` integer grid `accounts` where `accounts[i][j]` is the amount of money the `i​​​​​​​​​​​th​​​​` customer has in the `j​​​​​​​​​​​th`​​​​ bank. Return _the **wealth** that the richest customer has._ A customer's **wealth** ...
dolphin
translate this code from C# to Haskell: ```C# public static int LongestSquareStreak(int[] nums) { HashSet<int> numSet = new HashSet<int>(nums); int longestStreak = -1; foreach (int num in numSet) { int streak = 1; int sqrtNum = (int)Math.Floor(Math.Sqrt(num)); while (numSet.Contain...
dolphin
Please explain the following problem in detail and provide code in Erlang: You are given an integer array `nums`. Two players are playing a game with this array: player 1 and player 2. Player 1 and player 2 take turns, with player 1 starting first. Both players start the game with a score of `0`. At each turn, the pla...
dolphin
Please focus on the efficiency of this problem and provide code in Go: A **Bitset** is a data structure that compactly stores bits. Implement the `Bitset` class: * `Bitset(int size)` Initializes the Bitset with `size` bits, all of which are `0`. * `void fix(int idx)` Updates the value of the bit at the index `idx...
dolphin
Please write the following solution using Fortran: A city's **skyline** is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Given the locations and heights of all the buildings, return _the **skyline** formed by these buildings collectively_. The geometric infor...
dolphin
Please focus on the algorithm of this problem and provide code in Elixir: Given a binary array `nums`, you should delete one element from it. Return _the size of the longest non-empty subarray containing only_ `1`_'s in the resulting array_. Return `0` if there is no such subarray. **Example 1:** **Input:** nums = \...
dolphin
Please focus on the functionality of this problem and provide code in Swift: Given the `root` of a binary tree, calculate the **vertical order traversal** of the binary tree. For each node at position `(row, col)`, its left and right children will be at positions `(row + 1, col - 1)` and `(row + 1, col + 1)` respectiv...
dolphin
convert this code from SmallTalk to Julia: ``` longestCommonPrefix: strs | prefix i | prefix := strs at: 1. i := 1. (strs isEmpty) ifTrue: [^'']. [i <= prefix size] whileTrue: [ (2 to: strs size) do: [:j | ((i > (strs at: j) size) or: [(prefix at: i) ~= (strs at: j) at: i]) ifTru...
dolphin
Please focus on the functionality of this problem and provide code in javascript: You are given an `m x n` grid `grid` where: * `'.'` is an empty cell. * `'#'` is a wall. * `'@'` is the starting point. * Lowercase letters represent keys. * Uppercase letters represent locks. You start at the starting point a...
dolphin
translate this code to Dart: ```fsharp let maxScore (scores: int array) (edges: int array array) : int = let adjList = Array.init scores.Length (fun _ -> []) let mutable result = -1 for edge in edges do adjList.[edge.[0]].Add(edge.[1]) adjList.[edge.[1]].Add(edge.[0]) for edge in edges...
dolphin
port this code to Lua: ``` defmodule Solution do def spiral_order(matrix) do result = [] if matrix == [], do: result {m, n} = {length(matrix), length(matrix |> hd)} {row_start, col_start, row_end, col_end} = {0, 0, m - 1, n - 1} while row_start <= row_end and col_start <= col_end do for i <...
dolphin
Please focus on the efficiency of this problem and provide code in PHP: Given the `root` of a binary tree, return _the length of the longest path, where each node in the path has the same value_. This path may or may not pass through the root. **The length of the path** between two nodes is represented by the number o...
dolphin
port this code to Lua: ```R min_subarray <- function(nums, p) { n <- length(nums) need <- 0 cur <- 0 res <- n last_seen <- list() for (num in nums) { need <- (need + num) %% p } if (need == 0) { return(0) } last_seen[[as.character(cur)]] <- -1 for (i in 1:n) { num <- nums[i] cur...
dolphin
Please explain the following problem in detail and provide code in Ruby: You are given two arrays of positive integers, `boxes` and `warehouse`, representing the heights of some boxes of unit width and the heights of `n` rooms in a warehouse respectively. The warehouse's rooms are labeled from `0` to `n - 1` from left ...
dolphin
translate this code from Lisp to Elixir: ```lisp (defun number-of-subarrays-with-zeroes (nums) (let ((count 0) (zero-count 0)) (dolist (num nums) (if (= num 0) (progn (incf zero-count) (incf count zero-count)) (setq zero-count 0))) count)) ```
dolphin
Please write the following solution using python: Assume the following rules are for the tic-tac-toe game on an `n x n` board between two players: 1. A move is guaranteed to be valid and is placed on an empty block. 2. Once a winning condition is reached, no more moves are allowed. 3. A player who succeeds in placi...
dolphin
convert this code from Groovy to Lisp: ```groovy def palindromePairs(words) { def isPalindrome(s) { s == s.reverse() } def result = [] def map = [:] words.eachWithIndex { word, idx -> map[word.reverse()] = idx } words.eachWithIndex { word, idx -> for (int i = 0; i <= ...
dolphin
Please explain the reasoning behind the following solution and provide code in Perl: Given an array of `points` where `points[i] = [xi, yi]` represents a point on the **X-Y** plane and an integer `k`, return the `k` closest points to the origin `(0, 0)`. The distance between two points on the **X-Y** plane is the Eucl...
dolphin
Please explain the reasoning behind the following solution and provide code in Julia: There is a strange printer with the following two special properties: * The printer can only print a sequence of **the same character** each time. * At each turn, the printer can print new characters starting from and ending at a...
dolphin
convert this code from Visual Basic .NET to F#: ```vb.net Function MaxProfit(prices As Integer()) As Integer Dim minPrice As Integer = Integer.MaxValue Dim maxProfit As Integer = 0 For Each price As Integer In prices minPrice = Math.Min(minPrice, price) maxProfit = Math.Max(maxProfit, price ...
dolphin
Please explain the following problem in detail and provide code in TypeScript: You are given a string `num`, representing a large integer. Return _the **largest-valued odd** integer (as a string) that is a **non-empty substring** of_ `num`_, or an empty string_ `" "` _if no odd integer exists_. A **substring** is a co...
dolphin
translate this code from Groovy to Fortran: ```groovy class Node { int val List<Node> children Node(int val, List<Node> children) { this.val = val this.children = children } } def preorder(Node root) { List<Integer> result = [] if (root == null) { return result } ...
dolphin
Please write the following solution using TypeScript: You are given an `m x n` grid `grid` of values `0`, `1`, or `2`, where: * each `0` marks **an empty land** that you can pass by freely, * each `1` marks **a building** that you cannot pass through, and * each `2` marks **an obstacle** that you cannot pass thr...
dolphin
Please focus on the efficiency of this problem and provide code in Dart: Fruits are available at some positions on an infinite x-axis. You are given a 2D integer array `fruits` where `fruits[i] = [positioni, amounti]` depicts `amounti` fruits at the position `positioni`. `fruits` is already **sorted** by `positioni` in...
dolphin
Please explain the following problem in detail and provide code in Go: Given the `root` of a binary tree, return _**the vertical order traversal** of its nodes' values_. (i.e., from top to bottom, column by column). If two nodes are in the same row and column, the order should be from **left to right**. **Example 1:*...
dolphin
Please explain the following problem in detail and provide code in Object Pascal: You are given an integer array `nums` and an integer `k`. You may partition `nums` into one or more **subsequences** such that each element in `nums` appears in **exactly** one of the subsequences. Return _the **minimum** number of subse...
dolphin
Please focus on the efficiency of this problem and provide code in Objective-C: Given a `root` of an [N-ary tree](https://leetcode.com/articles/introduction-to-n-ary-trees/), you need to compute the length of the diameter of the tree. The diameter of an N-ary tree is the length of the **longest** path between any two ...
dolphin
Please focus on the functionality of this problem and provide code in Swift: You are given an integer array `nums`. The unique elements of an array are the elements that appear **exactly once** in the array. Return _the **sum** of all the unique elements of_ `nums`. **Example 1:** **Input:** nums = \[1,2,3,2\] **Out...
dolphin
translate this code to Go: ```groovy def shortestDistance(wordsDict, word1, word2) { def idx1 = -1, idx2 = -1, minDistance = Float.POSITIVE_INFINITY wordsDict.eachWithIndex { word, i -> if (word == word1) idx1 = i if (word == word2) idx2 = i if (idx1 != -1 && idx2 != -1) { mi...
dolphin
Please focus on the efficiency of this problem and provide code in java: You have an undirected, connected graph of `n` nodes labeled from `0` to `n - 1`. You are given an array `graph` where `graph[i]` is a list of all the nodes connected with node `i` by an edge. Return _the length of the shortest path that visits e...
dolphin
port this code from TypeScript to Fortran: ```typescript function canDetonate(bombs: number[][], i: number, j: number) { const [x1, y1, r1] = bombs[i]; const [x2, y2, r2] = bombs[j]; const distance = Math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2); return distance <= r1; } function maxDetonations(bombs: num...
dolphin
port this code to Rust: ```ruby def find_smallest_reachable_set(n, edges) in_degrees = Array.new(n, 0) queue = [] reachable = [] edges.each do |edge| to_node = edge[1] in_degrees[to_node] += 1 end (0..n-1).each do |node| queue << node if in_degrees[node] == 0 ...
dolphin
Please explain the following problem in detail and provide code in Scala: 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 you get an...
dolphin
Please write the following solution using Scheme: You are given a **0-indexed** integer array `nums` of length `n`. `nums` contains a **valid split** at index `i` if the following are true: * The sum of the first `i + 1` elements is **greater than or equal to** the sum of the last `n - i - 1` elements. * There is...
dolphin
Please explain the reasoning behind the following solution and provide code in Fortran: You are given a binary matrix `matrix` of size `m x n`, and you are allowed to rearrange the **columns** of the `matrix` in any order. Return _the area of the largest submatrix within_ `matrix` _where **every** element of the subma...
dolphin
port this code to Clojure: ```rust fn is_shortest_and_unique_supersequence(nums: Vec<i32>, sequences: Vec<Vec<i32>>) -> bool { let mut pos = std::collections::HashMap::new(); for (idx, &val) in nums.iter().enumerate() { pos.insert(val, idx); } for seq in sequences { if pos[&seq[0]] > po...
dolphin
translate this code from Elixir to Clojure: ```elixir defmodule Solution do @mod 1_000_000_007 def num_divisions(corridor) do n = String.length(corridor) count = 0 for i <- 1..(n-2) do if corridor[i-1] == ?S and corridor[i+1] == ?S and corridor[i] == ?P do left = i-1 right = i+1 ...
dolphin
port this code to Objective-C: ```fsharp let canConvertString (s : string) (t : string) (k : int) : bool = if s.Length <> t.Length then false else let count = Array.zeroCreate 26 for i = 0 to s.Length - 1 do let diff = (int t.[i] - int s.[i] + 26) % 26 if diff > 0 then co...
dolphin
Please focus on the functionality of this problem and provide code in c++: Given an `m x n` matrix `grid` containing an **odd** number of integers where each row is sorted in **non-decreasing** order, return _the **median** of the matrix_. You must solve the problem in less than `O(m * n)` time complexity. **Example ...
dolphin
Please write the following solution using Dart: We can represent a sentence as an array of words, for example, the sentence `"I am happy with leetcode "` can be represented as `arr = [ "I ", "am ",happy ", "with ", "leetcode "]`. Given two sentences `sentence1` and `sentence2` each represented as a string array and gi...
dolphin
Please explain the following problem in detail and provide code in C#: Given a string `s`, find two **disjoint palindromic subsequences** of `s` such that the **product** of their lengths is **maximized**. The two subsequences are **disjoint** if they do not both pick a character at the same index. Return _the **maxim...
dolphin
convert this code from Erlang to Scala: ```erlang min_length_after_operations(S) -> A_Count = lists:count($a, S), B_Count = lists:count($b, S), C_Count = lists:count($c, S), case A_Count rem 2 =:= B_Count rem 2 andalso B_Count rem 2 =:= C_Count rem 2 of true -> length(S) rem 2; false ->...
dolphin
translate this code to python: ```rust fn alice_wins(num: &str) -> bool { let mut left_sum = 0; let mut right_sum = 0; let mut left_q = 0; let mut right_q = 0; for (i, c) in num.chars().enumerate() { if c == '?' { if i < num.len() / 2 { left_q += 1; }...
dolphin
Please write the following solution using F#: 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 equal, except the two middle one...
dolphin
Please write the following solution using Ruby: You are given an integer array `matchsticks` where `matchsticks[i]` is the length of the `ith` matchstick. You want to use **all the matchsticks** to make one square. You **should not break** any stick, but you can link them up, and each matchstick must be used **exactly ...
dolphin
Please explain the reasoning behind the following solution and provide code in Visual Basic .NET: You are given the `root` of a binary tree where each node has a value `0` or `1`. Each root-to-leaf path represents a binary number starting with the most significant bit. * For example, if the path is `0 -> 1 -> 1 -> 0...
dolphin
Please write the following solution using Groovy: Given an integer `n`, return `true` _if and only if it is an **Armstrong number**_. The `k`\-digit number `n` is an Armstrong number if and only if the `kth` power of each digit sums to `n`. **Example 1:** **Input:** n = 153 **Output:** true **Explanation:** 153 is a...
dolphin
Please focus on the functionality of this problem and provide code in Haskell: Given an integer array `instructions`, you are asked to create a sorted array from the elements in `instructions`. You start with an empty container `nums`. For each element from **left to right** in `instructions`, insert it into `nums`. Th...
dolphin
port this code from Groovy to TypeScript: ```groovy class Node { int val List<Node> neighbors Node(int val) { this.val = val this.neighbors = [] } } def cloneGraph(node, visited = [:]) { if (!node) return null if (visited.containsKey(node)) return visited[node] def cloneN...
dolphin
convert this code from Scala to Elixir: ```scala object Solution { def minDistance(height: Int, width: Int, tree: Array[Int], squirrel: Array[Int], nuts: Array[Array[Int]]): Int = { var totalDist = 0 var minDiff = Int.MaxValue for (nut <- nuts) { val treeDist = math.abs(...
dolphin
Please write the following solution using Swift: Given a collection of numbers, `nums`, that might contain duplicates, return _all possible unique permutations **in any order**._ **Example 1:** **Input:** nums = \[1,1,2\] **Output:** \[\[1,1,2\], \[1,2,1\], \[2,1,1\]\] **Example 2:** **Input:** nums = \[1,2,3\] *...
dolphin
Please focus on the efficiency of this problem and provide code in F#: Given an unsorted array of integers `nums`, return _the length of the longest **continuous increasing subsequence** (i.e. subarray)_. The subsequence must be **strictly** increasing. A **continuous increasing subsequence** is defined by two indices...
dolphin
port this code to Objective-C: ```elixir defmodule Solution do def checkOverlap(radius, xCenter, yCenter, x1, y1, x2, y2) do xClosest = max(x1, min(xCenter, x2)) yClosest = max(y1, min(yCenter, y2)) :math.pow(xCenter - xClosest, 2) + :math.pow(yCenter - yClosest, 2) <= :math.pow(radius, 2) end end ```
dolphin
Please explain the reasoning behind the following solution and provide code in Visual Basic .NET: There is an **undirected** graph with `n` nodes, where each node is numbered between `0` and `n - 1`. You are given a 2D array `graph`, where `graph[u]` is an array of nodes that node `u` is adjacent to. More formally, for...
dolphin
convert this code from ANSI C to Scala: ```c #include <stdbool.h> /** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ bool isPalindrome(struct ListNode* head){ if (!head || !head->next) { return true; } struct ListNode *fast =...
dolphin
port this code from Object Pascal to Kotlin: ```pascal function minDeciBinary(n: string): integer; var max_digit, digit, i: integer; begin max_digit := 0; for i := 1 to length(n) do begin digit := ord(n[i]) - ord('0'); max_digit := max(max_digit, digit); end; minDeciBinary := max_digit; end; ```
dolphin
port this code to ANSI C: ```perl sub MAX_CANDIES { my ($status, $candies, $keys, $containedBoxes, $initialBoxes) = @_; my %visited_boxes; my $total_candies = 0; my @queue = @$initialBoxes; while (@queue) { my $box = shift @queue; if ($visited_boxes{$box}) { next; ...
dolphin
Please explain the following problem in detail and provide code in R: Given three integer arrays `nums1`, `nums2`, and `nums3`, return _a **distinct** array containing all the values that are present in **at least two** out of the three arrays. You may return the values in **any** order_. **Example 1:** **Input:** nu...
dolphin
convert this code from Elixir to Julia: ```elixir defmodule Solution do def max_vowels(s, k) do vowels = ['a', 'e', 'i', 'o', 'u'] max_vowels = 0 curr_vowels = 0 for i <- 0..(k-1) do if Enum.member?(vowels, String.at(s, i)) do curr_vowels = curr_vowels + 1 end end max_vowel...
dolphin
Please write the following solution using Go: We define the usage of capitals in a word to be right when one of the following cases holds: * All letters in this word are capitals, like `"USA "`. * All letters in this word are not capitals, like `"leetcode "`. * Only the first letter in this word is capital, like...
dolphin