Dataset Viewer
Auto-converted to Parquet Duplicate
id
int64
1
2.61k
slug
stringlengths
3
79
title
stringlengths
3
79
difficulty
stringclasses
3 values
content
stringlengths
230
5.69k
python
stringlengths
27
3.1k
prompt_nl
stringlengths
60
3.82k
prompt
stringlengths
99
3.95k
1,181
before-and-after-puzzle
Before and After Puzzle
Medium
Given a list of `phrases`, generate a list of Before and After puzzles. A _phrase_ is a string that consists of lowercase English letters and spaces only. No space appears in the start or the end of a phrase. There are no consecutive spaces in a phrase. _Before and After puzzles_ are phrases that are formed by mergin...
```python from collections import defaultdict def beforeAndAfterPuzzles(phrases): first_word_map = defaultdict(set) result = set() for phrase in phrases: first_word = phrase.split(' ')[0] first_word_map[first_word].add(phrase) for phrase in phrases: last_word = phrase.spl...
Given a list of `phrases`, generate a list of Before and After puzzles. A _phrase_ is a string that consists of lowercase English letters and spaces only. No space appears in the start or the end of a phrase. There are no consecutive spaces in a phrase. _Before and After puzzles_ are phrases that are formed by mergin...
Continue the following Python code: # Given a list of `phrases`, generate a list of Before and After puzzles. # # A _phrase_ is a string that consists of lowercase English letters and spaces only. No space appears in the start or the end of a phrase. There are no consecutive spaces in a phrase. # # _Before and After pu...
2,464
minimum-subarrays-in-a-valid-split
Minimum Subarrays in a Valid Split
Medium
You are given an integer array `nums`. Splitting of an integer array `nums` into **subarrays** is **valid** if: * the _greatest common divisor_ of the first and last elements of each subarray is **greater** than `1`, and * each element of `nums` belongs to exactly one subarray. Return _the **minimum** number of ...
```python from math import gcd def min_valid_subarrays(nums): count = 0 while nums: for i in range(len(nums)): if gcd(nums[i], nums[-1]) > 1: break else: count += 1 nums.pop() return count if count > 0 else -1 ``` The algorit...
You are given an integer array `nums`. Splitting of an integer array `nums` into **subarrays** is **valid** if: * the _greatest common divisor_ of the first and last elements of each subarray is **greater** than `1`, and * each element of `nums` belongs to exactly one subarray. Return _the **minimum** number of ...
Continue the following Python code: # You are given an integer array `nums`. # # Splitting of an integer array `nums` into **subarrays** is **valid** if: # # * the _greatest common divisor_ of the first and last elements of each subarray is **greater** than `1`, and # * each element of `nums` belongs to exactly one...
214
shortest-palindrome
Shortest Palindrome
Hard
You are given a string `s`. You can convert `s` to a palindrome by adding characters in front of it. Return _the shortest palindrome you can find by performing this transformation_. **Example 1:** **Input:** s = "aacecaaa" **Output:** "aaacecaaa" **Example 2:** **Input:** s = "abcd" **Output:** "dcbabcd" **Constr...
```python def shortest_palindrome(s: str) -> str: n = len(s) rev_s = s[::-1] for i in range(n): if s[:n - i] == rev_s[i:]: return rev_s[:i] + s return "" ``` 1. Take input string `s`. 2. Get string `rev_s` by reversing the input string. 3. Iterate through the char...
You are given a string `s`. You can convert `s` to a palindrome by adding characters in front of it. Return _the shortest palindrome you can find by performing this transformation_.
Continue the following Python code: # You are given a string `s`. You can convert `s` to a palindrome by adding characters in front of it. # # Return _the shortest palindrome you can find by performing this transformation_.
1,861
rotating-the-box
Rotating the Box
Medium
You are given an `m x n` matrix of characters `box` representing a side-view of a box. Each cell of the box is one of the following: * A stone `'#'` * A stationary obstacle `'*'` * Empty `'.'` The box is rotated **90 degrees clockwise**, causing some of the stones to fall due to gravity. Each stone falls down u...
```python def min_boxes_touching_floor(n): return (n + 1) // 2 ``` The algorithm is fairly simple, since the room is a perfect cube, we can place the boxes on the floor in an alternating pattern. We place a box in one corner, then skip one unit and place another box, then skip another unit and so on, ...
You are given an `m x n` matrix of characters `box` representing a side-view of a box. Each cell of the box is one of the following: * A stone `'#'` * A stationary obstacle `'*'` * Empty `'.'` The box is rotated **90 degrees clockwise**, causing some of the stones to fall due to gravity. Each stone falls down u...
Continue the following Python code: # You are given an `m x n` matrix of characters `box` representing a side-view of a box. Each cell of the box is one of the following: # # * A stone `'#'` # * A stationary obstacle `'*'` # * Empty `'.'` # # The box is rotated **90 degrees clockwise**, causing some of the stones...
1,870
minimum-speed-to-arrive-on-time
Minimum Speed to Arrive on Time
Medium
You are given a floating-point number `hour`, representing the amount of time you have to reach the office. To commute to the office, you must take `n` trains in sequential order. You are also given an integer array `dist` of length `n`, where `dist[i]` describes the distance (in kilometers) of the `ith` train ride. E...
```python from math import ceil def minSpeedOnTime(dist, hour): max_time = hour - len(dist) + 1 lower, upper = 1.0, 1e7 while upper - lower >= 1e-9: mid = (lower + upper) / 2 time_taken = sum(ceil(d / mid) - (0 if i == len(dist) - 1 else 1) for i, d in enumerate(dist)) if time_...
You are given a floating-point number `hour`, representing the amount of time you have to reach the office. To commute to the office, you must take `n` trains in sequential order. You are also given an integer array `dist` of length `n`, where `dist[i]` describes the distance (in kilometers) of the `ith` train ride. E...
Continue the following Python code: # You are given a floating-point number `hour`, representing the amount of time you have to reach the office. To commute to the office, you must take `n` trains in sequential order. You are also given an integer array `dist` of length `n`, where `dist[i]` describes the distance (in k...
1,772
sort-features-by-popularity
Sort Features by Popularity
Medium
You are given a string array `features` where `features[i]` is a single word that represents the name of a feature of the latest product you are working on. You have made a survey where users have reported which features they like. You are given a string array `responses`, where each `responses[i]` is a string containi...
```python from sortedcontainers import SortedList MOD = int(1e9) + 7 def create_sorted_array(instructions): s = SortedList() cost = 0 for i in instructions: less_than = s.bisect_left(i) greater_than = len(s) - s.bisect_right(i) cost = (cost + min(less_than, greater_than)) % M...
You are given a string array `features` where `features[i]` is a single word that represents the name of a feature of the latest product you are working on. You have made a survey where users have reported which features they like. You are given a string array `responses`, where each `responses[i]` is a string containi...
Continue the following Python code: # You are given a string array `features` where `features[i]` is a single word that represents the name of a feature of the latest product you are working on. You have made a survey where users have reported which features they like. You are given a string array `responses`, where ea...
939
minimum-area-rectangle
Minimum Area Rectangle
Medium
You are given an array of points in the **X-Y** plane `points` where `points[i] = [xi, yi]`. Return _the minimum area of a rectangle formed from these points, with sides parallel to the X and Y axes_. If there is not any such rectangle, return `0`. **Example 1:** **Input:** points = \[\[1,1\],\[1,3\],\[3,1\],\[3,3\]...
```python def find_valid_permutations(s: str) -> int: n = len(s) MOD = 1000000007 dp = [0] * (n + 2) dp[0] = 1 for c in s: new_dp = [0] * (n + 2) if c == 'I': for i in range(n): new_dp[i + 1] = (new_dp[i + 1] + dp[i]) % MOD else: ...
You are given an array of points in the **X-Y** plane `points` where `points[i] = [xi, yi]`. Return _the minimum area of a rectangle formed from these points, with sides parallel to the X and Y axes_. If there is not any such rectangle, return `0`.
Continue the following Python code: # You are given an array of points in the **X-Y** plane `points` where `points[i] = [xi, yi]`. # # Return _the minimum area of a rectangle formed from these points, with sides parallel to the X and Y axes_. If there is not any such rectangle, return `0`.
2,338
count-the-number-of-ideal-arrays
Count the Number of Ideal Arrays
Hard
You are given two integers `n` and `maxValue`, which are used to describe an **ideal** array. A **0-indexed** integer array `arr` of length `n` is considered **ideal** if the following conditions hold: * Every `arr[i]` is a value from `1` to `maxValue`, for `0 <= i < n`. * Every `arr[i]` is divisible by `arr[i - ...
```python def numOfArrays(n: int, maxValue: int) -> int: mod = 10**9 + 7 dp = [0] * (maxValue + 1) for i in range(1, maxValue + 1): dp[i] = i for i in range(1, n): for j in range(maxValue, 0, -1): dp[j] = (dp[j] + dp[j - 1]) % mod return dp...
You are given two integers `n` and `maxValue`, which are used to describe an **ideal** array. A **0-indexed** integer array `arr` of length `n` is considered **ideal** if the following conditions hold: * Every `arr[i]` is a value from `1` to `maxValue`, for `0 <= i < n`. * Every `arr[i]` is divisible by `arr[i - ...
Continue the following Python code: # You are given two integers `n` and `maxValue`, which are used to describe an **ideal** array. # # A **0-indexed** integer array `arr` of length `n` is considered **ideal** if the following conditions hold: # # * Every `arr[i]` is a value from `1` to `maxValue`, for `0 <= i < n`. ...
1,682
longest-palindromic-subsequence-ii
Longest Palindromic Subsequence II
Medium
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 ones. For example, if `s = "abcabcabb "`, then `...
```python def most_visited(n, rounds): visited = [0] * (n + 1) for i in range(1, len(rounds)): start, end = rounds[i - 1], rounds[i] while start != end: visited[start] += 1 start = (start % n) + 1 visited[rounds[-1]] += 1 max_visits = max(visited); ...
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 ones. For example, if `s = "abcabcabb "`, then `...
Continue the following Python code: # 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 on...
503
next-greater-element-ii
Next Greater Element II
Medium
Given a circular integer array `nums` (i.e., the next element of `nums[nums.length - 1]` is `nums[0]`), return _the **next greater number** for every element in_ `nums`. The **next greater number** of a number `x` is the first greater number to its traversing-order next in the array, which means you could search circu...
```python def nextGreaterElements(nums): result = [-1] * len(nums) stack = [] for i in range(len(nums) * 2): index = i % len(nums) while stack and nums[stack[-1]] < nums[index]: result[stack.pop()] = nums[index] if i < len(nums): stack.append(index) ...
Given a circular integer array `nums` (i.e., the next element of `nums[nums.length - 1]` is `nums[0]`), return _the **next greater number** for every element in_ `nums`. The **next greater number** of a number `x` is the first greater number to its traversing-order next in the array, which means you could search circu...
Continue the following Python code: # Given a circular integer array `nums` (i.e., the next element of `nums[nums.length - 1]` is `nums[0]`), return _the **next greater number** for every element in_ `nums`. # # The **next greater number** of a number `x` is the first greater number to its traversing-order next in the ...
2,536
increment-submatrices-by-one
Increment Submatrices by One
Medium
You are given a positive integer `n`, indicating that we initially have an `n x n` **0-indexed** integer matrix `mat` filled with zeroes. You are also given a 2D integer array `query`. For each `query[i] = [row1i, col1i, row2i, col2i]`, you should do the following operation: * Add `1` to **every element** in the su...
```python def apply_queries(n, queries): mat = [[0] * n for _ in range(n)] for query in queries: for i in range(query[0], query[2] + 1): for j in range(query[1], query[3] + 1): mat[i][j] += 1 return mat ``` The algorithm simply initializes an n x n matrix ...
You are given a positive integer `n`, indicating that we initially have an `n x n` **0-indexed** integer matrix `mat` filled with zeroes. You are also given a 2D integer array `query`. For each `query[i] = [row1i, col1i, row2i, col2i]`, you should do the following operation: * Add `1` to **every element** in the su...
Continue the following Python code: # You are given a positive integer `n`, indicating that we initially have an `n x n` **0-indexed** integer matrix `mat` filled with zeroes. # # You are also given a 2D integer array `query`. For each `query[i] = [row1i, col1i, row2i, col2i]`, you should do the following operation: # ...
2,185
counting-words-with-a-given-prefix
Counting Words With a Given Prefix
Easy
You are given an array of strings `words` and a string `pref`. Return _the number of strings in_ `words` _that contain_ `pref` _as a **prefix**_. A **prefix** of a string `s` is any leading contiguous substring of `s`. **Example 1:** **Input:** words = \[ "pay ", "**at**tention ", "practice ", "**at**tend "\], `pre...
```python def count_prefixes(words, pref): return sum(1 for word in words if word.startswith(pref)) ``` The algorithm iterates through the list of words and checks if the word starts with the given prefix. If it does, increment the count. Finally, return the count.
You are given an array of strings `words` and a string `pref`. Return _the number of strings in_ `words` _that contain_ `pref` _as a **prefix**_. A **prefix** of a string `s` is any leading contiguous substring of `s`.
Continue the following Python code: # You are given an array of strings `words` and a string `pref`. # # Return _the number of strings in_ `words` _that contain_ `pref` _as a **prefix**_. # # A **prefix** of a string `s` is any leading contiguous substring of `s`.
1,668
maximum-repeating-substring
Maximum Repeating Substring
Easy
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 `sequence`. If `word` is not a substring of `sequence`, `word`'s maximum `k`\-repeating v...
```python def longestAwesomeSubstring(s): n = len(s) maxLen = 0 for i in range(n): for j in range(i + 1, n + 1): substr = s[i:j] if isAwesome(substr): maxLen = max(maxLen, j - i) return maxLen def isAwesome(s): odd_count = 0 freq = [0] * 26 ...
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 `sequence`. If `word` is not a substring of `sequence`, `word`'s maximum `k`\-repeating v...
Continue the following Python code: # 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 `sequence`. If `word` is not a substring of `sequen...
1,258
synonymous-sentences
Synonymous Sentences
Medium
You are given a list of equivalent string pairs `synonyms` where `synonyms[i] = [si, ti]` indicates that `si` and `ti` are equivalent strings. You are also given a sentence `text`. Return _all possible synonymous sentences **sorted lexicographically**_. **Example 1:** **Input:** synonyms = \[\[ "happy ", "joy "\],\[...
```python from typing import List def generateSentences(synonyms: List[List[str]], text: str) -> List[str]: synonym_map = {} for s, t in synonyms: if s not in synonym_map: synonym_map[s] = {s} if t not in synonym_map: synonym_map[t] = {t} synonym_map[s].ad...
You are given a list of equivalent string pairs `synonyms` where `synonyms[i] = [si, ti]` indicates that `si` and `ti` are equivalent strings. You are also given a sentence `text`. Return _all possible synonymous sentences **sorted lexicographically**_.
Continue the following Python code: # You are given a list of equivalent string pairs `synonyms` where `synonyms[i] = [si, ti]` indicates that `si` and `ti` are equivalent strings. You are also given a sentence `text`. # # Return _all possible synonymous sentences **sorted lexicographically**_.
1,673
find-the-most-competitive-subsequence
Find the Most Competitive Subsequence
Medium
Given an integer array `nums` and a positive integer `k`, return _the most **competitive** subsequence of_ `nums` _of size_ `k`. An array's subsequence is a resulting sequence obtained by erasing some (possibly zero) elements from the array. We define that a subsequence `a` is more **competitive** than a subsequence ...
```python from collections import deque def mostCompetitive(nums, k): stack = deque() n = len(nums) for i in range(n): while stack and stack[-1] > nums[i] and len(stack) + n - i > k: stack.pop() if len(stack) < k: stack.append(nums[i]) return list(stack) ```...
Given an integer array `nums` and a positive integer `k`, return _the most **competitive** subsequence of_ `nums` _of size_ `k`. An array's subsequence is a resulting sequence obtained by erasing some (possibly zero) elements from the array. We define that a subsequence `a` is more **competitive** than a subsequence ...
Continue the following Python code: # Given an integer array `nums` and a positive integer `k`, return _the most **competitive** subsequence of_ `nums` _of size_ `k`. # # An array's subsequence is a resulting sequence obtained by erasing some (possibly zero) elements from the array. # # We define that a subsequence `a`...
2,156
find-substring-with-given-hash-value
Find Substring With Given Hash Value
Hard
The hash of a **0-indexed** string `s` of length `k`, given integers `p` and `m`, is computed using the following function: * `hash(s, p, m) = (val(s[0]) * p0 + val(s[1]) * p1 + ... + val(s[k-1]) * pk-1) mod m`. Where `val(s[i])` represents the index of `s[i]` in the alphabet from `val('a') = 1` to `val('z') = 26`....
```python def alice_wins(stones): sum_, count = 0, [0] * 3 for stone in stones: sum_ += stone count[stone % 3] += 1 if sum_ % 3: return count[sum_ % 3] % 2 == 1 return count[1] % 2 == 0 or count[2] % 2 == 0 or count[1] == 0 or count[2] == 0 ``` 1. Calculate the sum ...
The hash of a **0-indexed** string `s` of length `k`, given integers `p` and `m`, is computed using the following function: * `hash(s, p, m) = (val(s[0]) * p0 + val(s[1]) * p1 + ... + val(s[k-1]) * pk-1) mod m`. Where `val(s[i])` represents the index of `s[i]` in the alphabet from `val('a') = 1` to `val('z') = 26`....
Continue the following Python code: # The hash of a **0-indexed** string `s` of length `k`, given integers `p` and `m`, is computed using the following function: # # * `hash(s, p, m) = (val(s[0]) * p0 + val(s[1]) * p1 + ... + val(s[k-1]) * pk-1) mod m`. # # Where `val(s[i])` represents the index of `s[i]` in the alph...
694
number-of-distinct-islands
Number of Distinct Islands
Medium
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 to be the same as another if and only if one island can be translated (and ...
```python def numDistinctIslands(grid): unique_islands = set() for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j] == 1: island_shape = [] dfs(grid, i, j, i, j, island_shape) island_shape.sort() unique_is...
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 to be the same as another if and only if one island can be translated (and ...
Continue the following Python code: # 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 to be the same as another if and o...
1,660
correct-a-binary-tree
Correct a Binary Tree
Medium
You have a binary tree with a small defect. There is **exactly one** invalid node where its right child incorrectly points to another node at the **same depth** but to the **invalid node's right**. Given the root of the binary tree with this defect, `root`, return _the root of the binary tree after **removing** this i...
```python def thousand_separator(n: int) -> str: result = str(n) count = 0 for i in range(len(result) - 1, 0, -1): count += 1 if count % 3 == 0: result = result[:i] + '.' + result[i:] return result ``` The algorithm first converts the given integer `n` into a st...
You have a binary tree with a small defect. There is **exactly one** invalid node where its right child incorrectly points to another node at the **same depth** but to the **invalid node's right**. Given the root of the binary tree with this defect, `root`, return _the root of the binary tree after **removing** this i...
Continue the following Python code: # You have a binary tree with a small defect. There is **exactly one** invalid node where its right child incorrectly points to another node at the **same depth** but to the **invalid node's right**. # # Given the root of the binary tree with this defect, `root`, return _the root of ...
1,268
search-suggestions-system
Search Suggestions System
Medium
You are given an array of strings `products` and a string `searchWord`. Design a system that suggests at most three product names from `products` after each character of `searchWord` is typed. Suggested products should have common prefix with `searchWord`. If there are more than three products with a common prefix ret...
```python def suggestedProducts(products, searchWord): result = [] products.sort() for i in range(len(searchWord)): suggestions = [] for product in products: if len(product) > i and product[i] == searchWord[i]: suggestions.append(product) ...
You are given an array of strings `products` and a string `searchWord`. Design a system that suggests at most three product names from `products` after each character of `searchWord` is typed. Suggested products should have common prefix with `searchWord`. If there are more than three products with a common prefix ret...
Continue the following Python code: # You are given an array of strings `products` and a string `searchWord`. # # Design a system that suggests at most three product names from `products` after each character of `searchWord` is typed. Suggested products should have common prefix with `searchWord`. If there are more tha...
1,697
checking-existence-of-edge-length-limited-paths
Checking Existence of Edge Length Limited Paths
Hard
An undirected graph of `n` nodes is defined by `edgeList`, where `edgeList[i] = [ui, vi, disi]` denotes an edge between nodes `ui` and `vi` with distance `disi`. Note that there may be **multiple** edges between two nodes. Given an array `queries`, where `queries[j] = [pj, qj, limitj]`, your task is to determine for e...
```python from collections import defaultdict, deque def distanceLimitedPathsExist(n, edgeList, queries): graph = defaultdict(list) for u, v, dis in edgeList: graph[u].append((v, dis)) graph[v].append((u, dis)) answer = [False] * len(queries) for i, (pj, qj, limitj) in enumerate(...
An undirected graph of `n` nodes is defined by `edgeList`, where `edgeList[i] = [ui, vi, disi]` denotes an edge between nodes `ui` and `vi` with distance `disi`. Note that there may be **multiple** edges between two nodes. Given an array `queries`, where `queries[j] = [pj, qj, limitj]`, your task is to determine for e...
Continue the following Python code: # An undirected graph of `n` nodes is defined by `edgeList`, where `edgeList[i] = [ui, vi, disi]` denotes an edge between nodes `ui` and `vi` with distance `disi`. Note that there may be **multiple** edges between two nodes. # # Given an array `queries`, where `queries[j] = [pj, qj, ...
2,503
maximum-number-of-points-from-grid-queries
Maximum Number of Points From Grid Queries
Hard
You are given an `m x n` integer matrix `grid` and an array `queries` of size `k`. Find an array `answer` of size `k` such that for each integer `queries[i]` you start in the **top left** cell of the matrix and repeat the following process: * If `queries[i]` is **strictly** greater than the value of the current cel...
```python from typing import List def maxPoints(grid: List[List[int]], queries: List[int]) -> List[int]: m, n = len(grid), len(grid[0]) dx = [-1, 0, 1, 0] dy = [0, 1, 0, -1] def dfs(x: int, y: int, q: int, visited: set) -> int: if 0 <= x < m and 0 <= y < n and grid[x][y] < q and (x, y) no...
You are given an `m x n` integer matrix `grid` and an array `queries` of size `k`. Find an array `answer` of size `k` such that for each integer `queries[i]` you start in the **top left** cell of the matrix and repeat the following process: * If `queries[i]` is **strictly** greater than the value of the current cel...
Continue the following Python code: # You are given an `m x n` integer matrix `grid` and an array `queries` of size `k`. # # Find an array `answer` of size `k` such that for each integer `queries[i]` you start in the **top left** cell of the matrix and repeat the following process: # # * If `queries[i]` is **strictly...
2,322
minimum-score-after-removals-on-a-tree
Minimum Score After Removals on a Tree
Hard
There is an undirected connected tree with `n` nodes labeled from `0` to `n - 1` and `n - 1` edges. You are given a **0-indexed** integer array `nums` of length `n` where `nums[i]` represents the value of the `ith` node. You are also given a 2D integer array `edges` of length `n - 1` where `edges[i] = [ai, bi]` indica...
```python def dfs(node, parent, xor_values, tree): xor_value = xor_values[node] for child in tree[node]: if child != parent: xor_value ^= dfs(child, node, xor_values, tree) return xor_value def minimumScore(nums, edges): n = len(nums) tree = [[] for _ in range(n)] ...
There is an undirected connected tree with `n` nodes labeled from `0` to `n - 1` and `n - 1` edges. You are given a **0-indexed** integer array `nums` of length `n` where `nums[i]` represents the value of the `ith` node. You are also given a 2D integer array `edges` of length `n - 1` where `edges[i] = [ai, bi]` indica...
Continue the following Python code: # There is an undirected connected tree with `n` nodes labeled from `0` to `n - 1` and `n - 1` edges. # # You are given a **0-indexed** integer array `nums` of length `n` where `nums[i]` represents the value of the `ith` node. You are also given a 2D integer array `edges` of length `...
2,243
calculate-digit-sum-of-a-string
Calculate Digit Sum of a String
Easy
You are given a string `s` consisting of digits and an integer `k`. A **round** can be completed if the length of `s` is greater than `k`. In one round, do the following: 1. **Divide** `s` into **consecutive groups** of size `k` such that the first `k` characters are in the first group, the next `k` characters are i...
```python def is_a_only_before_b(s: str) -> bool: last_index_a = -1 for i, c in enumerate(s): if c == 'a': last_index_a = i elif c == 'b' and last_index_a > -1: return False return True ``` The algorithm iterates through each character in the given strin...
You are given a string `s` consisting of digits and an integer `k`. A **round** can be completed if the length of `s` is greater than `k`. In one round, do the following: 1. **Divide** `s` into **consecutive groups** of size `k` such that the first `k` characters are in the first group, the next `k` characters are i...
Continue the following Python code: # You are given a string `s` consisting of digits and an integer `k`. # # A **round** can be completed if the length of `s` is greater than `k`. In one round, do the following: # # 1. **Divide** `s` into **consecutive groups** of size `k` such that the first `k` characters are in th...
988
smallest-string-starting-from-leaf
Smallest String Starting From Leaf
Medium
You are given the `root` of a binary tree where each node has a value in the range `[0, 25]` representing the letters `'a'` to `'z'`. Return _the **lexicographically smallest** string that starts at a leaf of this tree and ends at the root_. As a reminder, any shorter prefix of a string is **lexicographically smaller...
```python class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def flipEquiv(root1, root2): if not root1 and not root2: return True if not root1 or not root2: return False if root1.val != root2.val: return Fals...
You are given the `root` of a binary tree where each node has a value in the range `[0, 25]` representing the letters `'a'` to `'z'`. Return _the **lexicographically smallest** string that starts at a leaf of this tree and ends at the root_. As a reminder, any shorter prefix of a string is **lexicographically smaller...
Continue the following Python code: # You are given the `root` of a binary tree where each node has a value in the range `[0, 25]` representing the letters `'a'` to `'z'`. # # Return _the **lexicographically smallest** string that starts at a leaf of this tree and ends at the root_. # # As a reminder, any shorter prefi...
1,655
distribute-repeating-integers
Distribute Repeating Integers
Hard
You are given an array of `n` integers, `nums`, where there are at most `50` unique values in the array. You are also given an array of `m` customer order quantities, `quantity`, where `quantity[i]` is the amount of integers the `ith` customer ordered. Determine if it is possible to distribute `nums` such that: * Th...
```python from collections import Counter def canDistribute(nums, quantity): counts = Counter(nums) values = list(counts.values()) quantity.sort(reverse=True) def dfs(index, values): if index == len(quantity): return True for i in range(len(values)): if val...
You are given an array of `n` integers, `nums`, where there are at most `50` unique values in the array. You are also given an array of `m` customer order quantities, `quantity`, where `quantity[i]` is the amount of integers the `ith` customer ordered. Determine if it is possible to distribute `nums` such that: * Th...
Continue the following Python code: # You are given an array of `n` integers, `nums`, where there are at most `50` unique values in the array. You are also given an array of `m` customer order quantities, `quantity`, where `quantity[i]` is the amount of integers the `ith` customer ordered. Determine if it is possible t...
850
rectangle-area-ii
Rectangle Area II
Hard
You are given a 2D array of axis-aligned `rectangles`. Each `rectangle[i] = [xi1, yi1, xi2, yi2]` denotes the `ith` rectangle where `(xi1, yi1)` are the coordinates of the **bottom-left corner**, and `(xi2, yi2)` are the coordinates of the **top-right corner**. Calculate the **total area** covered by all `rectangles` ...
```python def rectangleArea(rectangles): mod = 10**9 + 7 n = len(rectangles) X, Y = set(), set() for rect in rectangles: X.add(rect[0]) X.add(rect[2]) Y.add(rect[1]) Y.add(rect[3]) sorted_x = sorted(X) sorted_y = sorted(Y) cnt = [[0 for _ in range(len(Y) ...
You are given a 2D array of axis-aligned `rectangles`. Each `rectangle[i] = [xi1, yi1, xi2, yi2]` denotes the `ith` rectangle where `(xi1, yi1)` are the coordinates of the **bottom-left corner**, and `(xi2, yi2)` are the coordinates of the **top-right corner**. Calculate the **total area** covered by all `rectangles` ...
Continue the following Python code: # You are given a 2D array of axis-aligned `rectangles`. Each `rectangle[i] = [xi1, yi1, xi2, yi2]` denotes the `ith` rectangle where `(xi1, yi1)` are the coordinates of the **bottom-left corner**, and `(xi2, yi2)` are the coordinates of the **top-right corner**. # # Calculate the **...
2,423
remove-letter-to-equalize-frequency
Remove Letter To Equalize Frequency
Easy
You are given a **0-indexed** string `word`, consisting of lowercase English letters. You need to select **one** index and **remove** the letter at that index from `word` so that the **frequency** of every letter present in `word` is equal. Return `true` _if it is possible to remove one letter so that the frequency of...
```python def can_equal_frequency(word: str) -> bool: freq = {} for c in word: freq[c] = freq.get(c, 0) + 1 count_freq = {} for f in freq.values(): count_freq[f] = count_freq.get(f, 0) + 1 if len(count_freq) != 2: return False a, acount = next(iter(count_freq.item...
You are given a **0-indexed** string `word`, consisting of lowercase English letters. You need to select **one** index and **remove** the letter at that index from `word` so that the **frequency** of every letter present in `word` is equal. Return `true` _if it is possible to remove one letter so that the frequency of...
Continue the following Python code: # You are given a **0-indexed** string `word`, consisting of lowercase English letters. You need to select **one** index and **remove** the letter at that index from `word` so that the **frequency** of every letter present in `word` is equal. # # Return `true` _if it is possible to r...
2,285
maximum-total-importance-of-roads
Maximum Total Importance of Roads
Medium
You are given an integer `n` denoting the number of cities in a country. The cities are numbered from `0` to `n - 1`. You are also given a 2D integer array `roads` where `roads[i] = [ai, bi]` denotes that there exists a **bidirectional** road connecting cities `ai` and `bi`. You need to assign each city with an integ...
```python class BitSet: def __init__(self, size): self.bits = [0] * ((size + 31) // 32) def set(self, index): self.bits[index // 32] |= (1 << (index % 32)) def get(self, index): return (self.bits[index // 32] & (1 << (index % 32))) != 0 ``` The BitSet class stores bit...
You are given an integer `n` denoting the number of cities in a country. The cities are numbered from `0` to `n - 1`. You are also given a 2D integer array `roads` where `roads[i] = [ai, bi]` denotes that there exists a **bidirectional** road connecting cities `ai` and `bi`. You need to assign each city with an integ...
Continue the following Python code: # You are given an integer `n` denoting the number of cities in a country. The cities are numbered from `0` to `n - 1`. # # You are also given a 2D integer array `roads` where `roads[i] = [ai, bi]` denotes that there exists a **bidirectional** road connecting cities `ai` and `bi`. # ...
728
self-dividing-numbers
Self Dividing Numbers
Easy
A **self-dividing number** is a number that is divisible by every digit it contains. * For example, `128` is **a self-dividing number** because `128 % 1 == 0`, `128 % 2 == 0`, and `128 % 8 == 0`. A **self-dividing number** is not allowed to contain the digit zero. Given two integers `left` and `right`, return _a l...
```python def is_self_dividing(num): n = num while n: digit = n % 10 if digit == 0 or num % digit != 0: return False n //= 10 return True def self_dividing_numbers(left, right): return [i for i in range(left, right+1) if is_self_dividing(i)] ``` The alg...
A **self-dividing number** is a number that is divisible by every digit it contains. * For example, `128` is **a self-dividing number** because `128 % 1 == 0`, `128 % 2 == 0`, and `128 % 8 == 0`. A **self-dividing number** is not allowed to contain the digit zero. Given two integers `left` and `right`, return _a l...
Continue the following Python code: # A **self-dividing number** is a number that is divisible by every digit it contains. # # * For example, `128` is **a self-dividing number** because `128 % 1 == 0`, `128 % 2 == 0`, and `128 % 8 == 0`. # # A **self-dividing number** is not allowed to contain the digit zero. # # Giv...
1,005
maximize-sum-of-array-after-k-negations
Maximize Sum Of Array After K Negations
Easy
Given an integer array `nums` and an integer `k`, modify the array in the following way: * choose an index `i` and replace `nums[i]` with `-nums[i]`. You should apply this process exactly `k` times. You may choose the same index `i` multiple times. Return _the largest possible sum of the array after modifying it i...
```python def is_univalued(root, val=None): if not root: return True if val is None: val = root.val return root.val == val and is_univalued(root.left, val) and is_univalued(root.right, val) ``` The algorithm first checks if the root node is null, if it is, the function returns ...
Given an integer array `nums` and an integer `k`, modify the array in the following way: * choose an index `i` and replace `nums[i]` with `-nums[i]`. You should apply this process exactly `k` times. You may choose the same index `i` multiple times. Return _the largest possible sum of the array after modifying it i...
Continue the following Python code: # Given an integer array `nums` and an integer `k`, modify the array in the following way: # # * choose an index `i` and replace `nums[i]` with `-nums[i]`. # # You should apply this process exactly `k` times. You may choose the same index `i` multiple times. # # Return _the largest...
1,753
maximum-score-from-removing-stones
Maximum Score From Removing Stones
Medium
You are playing a solitaire game with **three piles** of stones of sizes `a`​​​​​​, `b`,​​​​​​ and `c`​​​​​​ respectively. Each turn you choose two **different non-empty** piles, take one stone from each, and add `1` point to your score. The game stops when there are **fewer than two non-empty** piles (meaning there ar...
```python import heapq from typing import List def minimumEffortPath(heights: List[List[int]]) -> int: directions = [(1, 0), (0, 1), (-1, 0), (0, -1)] rows = len(heights) cols = len(heights[0]) efforts = [[float('inf')] * cols for _ in range(rows)] q = [(0, 0, 0)] efforts[0][0] = 0 ...
You are playing a solitaire game with **three piles** of stones of sizes `a`​​​​​​, `b`,​​​​​​ and `c`​​​​​​ respectively. Each turn you choose two **different non-empty** piles, take one stone from each, and add `1` point to your score. The game stops when there are **fewer than two non-empty** piles (meaning there ar...
Continue the following Python code: # You are playing a solitaire game with **three piles** of stones of sizes `a`​​​​​​, `b`,​​​​​​ and `c`​​​​​​ respectively. Each turn you choose two **different non-empty** piles, take one stone from each, and add `1` point to your score. The game stops when there are **fewer than t...
438
find-all-anagrams-in-a-string
Find All Anagrams in a String
Medium
Given two strings `s` and `p`, return _an array of all the start indices of_ `p`_'s anagrams in_ `s`. You may return the answer in **any order**. An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. **Example 1:** *...
```python def find_anagrams(s, p): if len(s) < len(p): return [] s_count = [0] * 26 p_count = [0] * 26 for c in p: p_count[ord(c) - ord('a')] += 1 result = [] for i in range(len(s)): s_count[ord(s[i]) - ord('a')] += 1 if i >= len(p): s_count[ord...
Given two strings `s` and `p`, return _an array of all the start indices of_ `p`_'s anagrams in_ `s`. You may return the answer in **any order**. An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Continue the following Python code: # Given two strings `s` and `p`, return _an array of all the start indices of_ `p`_'s anagrams in_ `s`. You may return the answer in **any order**. # # An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original...
82
remove-duplicates-from-sorted-list-ii
Remove Duplicates from Sorted List II
Medium
Given the `head` of a sorted linked list, _delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list_. Return _the linked list **sorted** as well_. **Example 1:** **Input:** head = \[1,2,3,3,4,4,5\] **Output:** \[1,2,5\] **Example 2:** **Input:** head = \[1,1,1,2,3\] **Outpu...
```python class ListNode: def __init__(self, x): self.val = x self.next = None def deleteDuplicates(head): dummy = ListNode(0) dummy.next = head prev, curr = dummy, head while curr: while curr.next and curr.val == curr.next.val: curr = curr.next if p...
Given the `head` of a sorted linked list, _delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list_. Return _the linked list **sorted** as well_.
Continue the following Python code: # Given the `head` of a sorted linked list, _delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list_. Return _the linked list **sorted** as well_.
374
guess-number-higher-or-lower
Guess Number Higher or Lower
Easy
We are playing the Guess Game. The game is as follows: I pick a number from `1` to `n`. You have to guess which number I picked. Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess. You call a pre-defined API `int guess(int num)`, which returns three possible re...
```python def guessNumber(n): low, high = 1, n while low <= high: mid = low + (high - low) // 2 result = guess(mid) if result == 0: return mid elif result < 0: high = mid - 1 else: low = mid + 1 return -1 ``` The algor...
We are playing the Guess Game. The game is as follows: I pick a number from `1` to `n`. You have to guess which number I picked. Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess. You call a pre-defined API `int guess(int num)`, which returns three possible re...
Continue the following Python code: # We are playing the Guess Game. The game is as follows: # # I pick a number from `1` to `n`. You have to guess which number I picked. # # Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess. # # You call a pre-defined API `int g...
1,814
count-nice-pairs-in-an-array
Count Nice Pairs in an Array
Medium
You are given an array `nums` that consists of non-negative integers. Let us define `rev(x)` as the reverse of the non-negative integer `x`. For example, `rev(123) = 321`, and `rev(120) = 21`. A pair of indices `(i, j)` is **nice** if it satisfies all of the following conditions: * `0 <= i < j < nums.length` * `nu...
```python from collections import deque def maxResult(nums, k): n = len(nums) dq = deque() dp = [0] * n dp[0] = nums[0] dq.append(0) for i in range(1, n): while dq and dq[0] < i - k: dq.popleft() dp[i] = nums[i] + dp[dq[0]] wh...
You are given an array `nums` that consists of non-negative integers. Let us define `rev(x)` as the reverse of the non-negative integer `x`. For example, `rev(123) = 321`, and `rev(120) = 21`. A pair of indices `(i, j)` is **nice** if it satisfies all of the following conditions: * `0 <= i < j < nums.length` * `nu...
Continue the following Python code: # You are given an array `nums` that consists of non-negative integers. Let us define `rev(x)` as the reverse of the non-negative integer `x`. For example, `rev(123) = 321`, and `rev(120) = 21`. A pair of indices `(i, j)` is **nice** if it satisfies all of the following conditions: #...
322
coin-change
Coin Change
Medium
You are given an integer array `coins` representing coins of different denominations and an integer `amount` representing a total amount of money. Return _the fewest number of coins that you need to make up that amount_. If that amount of money cannot be made up by any combination of the coins, return `-1`. You may a...
```python def coinChange(coins, amount): dp = [amount + 1] * (amount + 1) dp[0] = 0 for coin in coins: for i in range(coin, amount + 1): dp[i] = min(dp[i], dp[i - coin] + 1) return dp[amount] if dp[amount] <= amount else -1 ``` The algorithm here is based on dynamic p...
You are given an integer array `coins` representing coins of different denominations and an integer `amount` representing a total amount of money. Return _the fewest number of coins that you need to make up that amount_. If that amount of money cannot be made up by any combination of the coins, return `-1`. You may a...
Continue the following Python code: # You are given an integer array `coins` representing coins of different denominations and an integer `amount` representing a total amount of money. # # Return _the fewest number of coins that you need to make up that amount_. If that amount of money cannot be made up by any combinat...
1,560
most-visited-sector-in-a-circular-track
Most Visited Sector in a Circular Track
Easy
Given an integer `n` and an integer array `rounds`. We have a circular track which consists of `n` sectors labeled from `1` to `n`. A marathon will be held on this track, the marathon consists of `m` rounds. The `ith` round starts at sector `rounds[i - 1]` and ends at sector `rounds[i]`. For example, round 1 starts at ...
```python def busy_student(start_time, end_time, query_time): count = 0 for i in range(len(start_time)): if start_time[i] <= query_time <= end_time[i]: count += 1 return count ``` The algorithm consists of iterating through the startTime and endTime arrays in parallel, by c...
Given an integer `n` and an integer array `rounds`. We have a circular track which consists of `n` sectors labeled from `1` to `n`. A marathon will be held on this track, the marathon consists of `m` rounds. The `ith` round starts at sector `rounds[i - 1]` and ends at sector `rounds[i]`. For example, round 1 starts at ...
Continue the following Python code: # Given an integer `n` and an integer array `rounds`. We have a circular track which consists of `n` sectors labeled from `1` to `n`. A marathon will be held on this track, the marathon consists of `m` rounds. The `ith` round starts at sector `rounds[i - 1]` and ends at sector `round...
2,018
check-if-word-can-be-placed-in-crossword
Check if Word Can Be Placed In Crossword
Medium
You are given an `m x n` matrix `board`, representing the **current** state of a crossword puzzle. The crossword contains lowercase English letters (from solved words), `' '` to represent any **empty** cells, and `'#'` to represent any **blocked** cells. A word can be placed **horizontally** (left to right **or** righ...
```python from bisect import bisect_right class Solution: def minWastedSpace(self, packages, boxes) -> int: MOD = 10**9 + 7 packages.sort() total_package_size = sum(packages) min_wasted_space = float('inf') for box_sizes in boxes: box_sizes.sort() ...
You are given an `m x n` matrix `board`, representing the **current** state of a crossword puzzle. The crossword contains lowercase English letters (from solved words), `' '` to represent any **empty** cells, and `'#'` to represent any **blocked** cells. A word can be placed **horizontally** (left to right **or** righ...
Continue the following Python code: # You are given an `m x n` matrix `board`, representing the **current** state of a crossword puzzle. The crossword contains lowercase English letters (from solved words), `' '` to represent any **empty** cells, and `'#'` to represent any **blocked** cells. # # A word can be placed **...
937
reorder-data-in-log-files
Reorder Data in Log Files
Medium
You are given an array of `logs`. Each log is a space-delimited string of words, where the first word is the **identifier**. There are two types of logs: * **Letter-logs**: All words (except the identifier) consist of lowercase English letters. * **Digit-logs**: All words (except the identifier) consist of digits...
```python class StockSpanner: def __init__(self): self.prices = [] self.index_stack = [] def next(self, price: int) -> int: while self.index_stack and self.prices[self.index_stack[-1]] <= price: self.index_stack.pop() span = len(self.prices) + 1 if not self.ind...
You are given an array of `logs`. Each log is a space-delimited string of words, where the first word is the **identifier**. There are two types of logs: * **Letter-logs**: All words (except the identifier) consist of lowercase English letters. * **Digit-logs**: All words (except the identifier) consist of digits...
Continue the following Python code: # You are given an array of `logs`. Each log is a space-delimited string of words, where the first word is the **identifier**. # # There are two types of logs: # # * **Letter-logs**: All words (except the identifier) consist of lowercase English letters. # * **Digit-logs**: All w...
897
increasing-order-search-tree
Increasing Order Search Tree
Easy
Given the `root` of a binary search tree, rearrange the tree in **in-order** so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only one right child. **Example 1:** **Input:** root = \[5,3,6,2,4,null,8,1,null,null,null,7,9\] **Output:** \[1,null,2,null,3,null,4,nul...
```python def is_prime(n): if n <= 1: return False i = 2 while i * i <= n: if n % i == 0: return False i += 1 return True def is_palindrome(n): return str(n) == str(n)[::-1] def prime_palindrome(n): while True: if is_prime(n) and is_palindrome(n...
Given the `root` of a binary search tree, rearrange the tree in **in-order** so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only one right child.
Continue the following Python code: # Given the `root` of a binary search tree, rearrange the tree in **in-order** so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only one right child.
312
burst-balloons
Burst Balloons
Hard
You are given `n` balloons, indexed from `0` to `n - 1`. Each balloon is painted with a number on it represented by an array `nums`. You are asked to burst all the balloons. If you burst the `ith` balloon, you will get `nums[i - 1] * nums[i] * nums[i + 1]` coins. If `i - 1` or `i + 1` goes out of bounds of the array, ...
```python def maxCoins(nums): nums = [1] + nums + [1] n = len(nums) dp = [[0] * n for _ in range(n)] for length in range(1, n - 1): for left in range(1, n - length): right = left + length - 1 for i in range(left, right + 1): dp[left][right] = max(dp[...
You are given `n` balloons, indexed from `0` to `n - 1`. Each balloon is painted with a number on it represented by an array `nums`. You are asked to burst all the balloons. If you burst the `ith` balloon, you will get `nums[i - 1] * nums[i] * nums[i + 1]` coins. If `i - 1` or `i + 1` goes out of bounds of the array, ...
Continue the following Python code: # You are given `n` balloons, indexed from `0` to `n - 1`. Each balloon is painted with a number on it represented by an array `nums`. You are asked to burst all the balloons. # # If you burst the `ith` balloon, you will get `nums[i - 1] * nums[i] * nums[i + 1]` coins. If `i - 1` or ...
1,461
check-if-a-string-contains-all-binary-codes-of-size-k
Check If a String Contains All Binary Codes of Size K
Medium
Given a binary string `s` and an integer `k`, return `true` _if every binary code of length_ `k` _is a substring of_ `s`. Otherwise, return `false`. **Example 1:** **Input:** s = "00110110 ", k = 2 **Output:** true **Explanation:** The binary codes of length 2 are "00 ", "01 ", "10 " and "11 ". They can be all f...
```python def countOrders(n: int) -> int: MOD = 10**9 + 7 ans = 1 for i in range(1, n + 1): ans = ans * (2 * i - 1) * i % MOD return ans ``` We need to arrange n pickup and n delivery services in a valid order. For the first order, we have 1 pickup and 1 delivery, i.e., 1 possible ...
Given a binary string `s` and an integer `k`, return `true` _if every binary code of length_ `k` _is a substring of_ `s`. Otherwise, return `false`.
Continue the following Python code: # Given a binary string `s` and an integer `k`, return `true` _if every binary code of length_ `k` _is a substring of_ `s`. Otherwise, return `false`.
1,732
find-the-highest-altitude
Find the Highest Altitude
Easy
There is a biker going on a road trip. The road trip consists of `n + 1` points at different altitudes. The biker starts his trip on point `0` with altitude equal `0`. You are given an integer array `gain` of length `n` where `gain[i]` is the **net gain in altitude** between points `i`​​​​​​ and `i + 1` for all (`0 <=...
```python def min_operations(n): operations = 0 while n > 0: if n % 2 == 0: n //= 2 else: n -= 1 operations += 1 return operations ``` The algorithm initializes a variable `operations` to store the number of operations taken. It then enters a loo...
There is a biker going on a road trip. The road trip consists of `n + 1` points at different altitudes. The biker starts his trip on point `0` with altitude equal `0`. You are given an integer array `gain` of length `n` where `gain[i]` is the **net gain in altitude** between points `i`​​​​​​ and `i + 1` for all (`0 <=...
Continue the following Python code: # There is a biker going on a road trip. The road trip consists of `n + 1` points at different altitudes. The biker starts his trip on point `0` with altitude equal `0`. # # You are given an integer array `gain` of length `n` where `gain[i]` is the **net gain in altitude** between po...
272
closest-binary-search-tree-value-ii
Closest Binary Search Tree Value II
Hard
Given the `root` of a binary search tree, a `target` value, and an integer `k`, return _the_ `k` _values in the BST that are closest to the_ `target`. You may return the answer in **any order**. You are **guaranteed** to have only one unique set of `k` values in the BST that are closest to the `target`. **Example 1:*...
```python from heapq import heappush, heappop class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def closestKValues(root, target, k): values = [] max_heap = [] def inorder_traverse(node): if not nod...
Given the `root` of a binary search tree, a `target` value, and an integer `k`, return _the_ `k` _values in the BST that are closest to the_ `target`. You may return the answer in **any order**. You are **guaranteed** to have only one unique set of `k` values in the BST that are closest to the `target`.
Continue the following Python code: # Given the `root` of a binary search tree, a `target` value, and an integer `k`, return _the_ `k` _values in the BST that are closest to the_ `target`. You may return the answer in **any order**. # # You are **guaranteed** to have only one unique set of `k` values in the BST that ar...
348
design-tic-tac-toe
Design Tic-Tac-Toe
Medium
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 placing `n` of their marks in a horizontal, vertical, o...
```python class TicTacToe: def __init__(self, n: int): self.rows, self.cols = [0] * n, [0] * n self.diagonal = self.anti_diagonal = self.n = n def move(self, row: int, col: int, player: int) -> int: to_add = 1 if player == 1 else -1 self.rows[row] += to_add self.co...
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 placing `n` of their marks in a horizontal, vertical, o...
Continue the following Python code: # 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 placing `n...
682
baseball-game
Baseball Game
Easy
You are keeping the scores for a baseball game with strange rules. At the beginning of the game, you start with an empty record. You are given a list of strings `operations`, where `operations[i]` is the `ith` operation you must apply to the record and is one of the following: * An integer `x`. * Record a new...
```python def calPoints(ops): record = [] for op in ops: if op == '+': record.append(record[-1] + record[-2]) elif op == 'D': record.append(record[-1] * 2) elif op == 'C': record.pop() else: record.append(int(op)) return su...
You are keeping the scores for a baseball game with strange rules. At the beginning of the game, you start with an empty record. You are given a list of strings `operations`, where `operations[i]` is the `ith` operation you must apply to the record and is one of the following: * An integer `x`. * Record a new...
Continue the following Python code: # You are keeping the scores for a baseball game with strange rules. At the beginning of the game, you start with an empty record. # # You are given a list of strings `operations`, where `operations[i]` is the `ith` operation you must apply to the record and is one of the following: ...
2,387
median-of-a-row-wise-sorted-matrix
Median of a Row Wise Sorted Matrix
Medium
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 1:** **Input:** grid = \[\[1,1,2\],\[2,3,3\],\[1,3,4\]\] **Output:** 2 **E...
```python def findMedian(grid: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) low, high = 1, 1_000_000 while low < high: mid = low + (high - low) // 2 count = sum(bisect_right(row, mid) for row in grid) if count < (m * n) // 2 + 1: low = mid + 1 el...
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.
Continue the following Python code: # 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.
1,237
find-positive-integer-solution-for-a-given-equation
Find Positive Integer Solution for a Given Equation
Medium
Given a callable function `f(x, y)` **with a hidden formula** and a value `z`, reverse engineer the formula and return _all positive integer pairs_ `x` _and_ `y` _where_ `f(x,y) == z`. You may return the pairs in any order. While the exact formula is hidden, the function is monotonically increasing, i.e.: * `f(x, y...
```python def findSolution(customfunction: 'CustomFunction', z: int) -> List[List[int]]: results = [] for x in range(1, 1001): for y in range(1, 1001): if customfunction.f(x, y) == z: results.append([x, y]) elif customfunction.f(x, y) > z: bre...
Given a callable function `f(x, y)` **with a hidden formula** and a value `z`, reverse engineer the formula and return _all positive integer pairs_ `x` _and_ `y` _where_ `f(x,y) == z`. You may return the pairs in any order. While the exact formula is hidden, the function is monotonically increasing, i.e.: * `f(x, y...
Continue the following Python code: # Given a callable function `f(x, y)` **with a hidden formula** and a value `z`, reverse engineer the formula and return _all positive integer pairs_ `x` _and_ `y` _where_ `f(x,y) == z`. You may return the pairs in any order. # # While the exact formula is hidden, the function is mon...
2,366
minimum-replacements-to-sort-the-array
Minimum Replacements to Sort the Array
Hard
You are given a **0-indexed** integer array `nums`. In one operation you can replace any element of the array with **any two** elements that **sum** to it. * For example, consider `nums = [5,6,7]`. In one operation, we can replace `nums[1]` with `2` and `4` and convert `nums` to `[5,2,4,7]`. Return _the minimum num...
```python def min_operations(nums): operations = 0 for i in range(1, len(nums)): if nums[i] <= nums[i - 1]: diff = nums[i - 1] - nums[i] + 1 operations += math.ceil(math.log2(diff)) nums[i] += diff return operations ``` We iterate through the array, ...
You are given a **0-indexed** integer array `nums`. In one operation you can replace any element of the array with **any two** elements that **sum** to it. * For example, consider `nums = [5,6,7]`. In one operation, we can replace `nums[1]` with `2` and `4` and convert `nums` to `[5,2,4,7]`. Return _the minimum num...
Continue the following Python code: # You are given a **0-indexed** integer array `nums`. In one operation you can replace any element of the array with **any two** elements that **sum** to it. # # * For example, consider `nums = [5,6,7]`. In one operation, we can replace `nums[1]` with `2` and `4` and convert `nums`...
409
longest-palindrome
Longest Palindrome
Easy
Given a string `s` which consists of lowercase or uppercase letters, return _the length of the **longest palindrome**_ that can be built with those letters. Letters are **case sensitive**, for example, `"Aa "` is not considered a palindrome here. **Example 1:** **Input:** s = "abccccdd " **Output:** 7 **Explanation...
```python def longestPalindrome(s: str) -> int: charCount = [0] * 128 result = 0 for c in s: charCount[ord(c)] += 1 for count in charCount: result += count // 2 * 2 if result % 2 == 0 and count % 2 == 1: result += 1 return result ``` 1. Create an arr...
Given a string `s` which consists of lowercase or uppercase letters, return _the length of the **longest palindrome**_ that can be built with those letters. Letters are **case sensitive**, for example, `"Aa "` is not considered a palindrome here.
Continue the following Python code: # Given a string `s` which consists of lowercase or uppercase letters, return _the length of the **longest palindrome**_ that can be built with those letters. # # Letters are **case sensitive**, for example, `"Aa "` is not considered a palindrome here.
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
-