problem_title
stringlengths 3
77
| python_solutions
stringlengths 81
8.45k
| post_href
stringlengths 64
213
| upvotes
int64 0
1.2k
| question
stringlengths 0
3.6k
| post_title
stringlengths 2
100
| views
int64 1
60.9k
| slug
stringlengths 3
77
| acceptance
float64 0.14
0.91
| user
stringlengths 3
26
| difficulty
stringclasses 3
values | __index_level_0__
int64 0
34k
| number
int64 1
2.48k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
number of distinct roll sequences | class Solution:
def distinctSequences(self, n: int) -> int:
@lru_cache
def fn(n, p0, p1):
"""Return total number of distinct sequences."""
if n == 0: return 1
ans = 0
for x in range(1, 7):
if x not in (p0, p1) and gcd(x, p0) == 1: ans += fn(n-1, x, p0)
return ans % 1_000_000_007
return fn(n, -1, -1) | https://leetcode.com/problems/number-of-distinct-roll-sequences/discuss/2196009/Python3-top-down-dp | 2 | You are given an integer n. You roll a fair 6-sided dice n times. Determine the total number of distinct sequences of rolls possible such that the following conditions are satisfied:
The greatest common divisor of any adjacent values in the sequence is equal to 1.
There is at least a gap of 2 rolls between equal valued rolls. More formally, if the value of the ith roll is equal to the value of the jth roll, then abs(i - j) > 2.
Return the total number of distinct sequences possible. Since the answer may be very large, return it modulo 109 + 7.
Two sequences are considered distinct if at least one element is different.
Example 1:
Input: n = 4
Output: 184
Explanation: Some of the possible sequences are (1, 2, 3, 4), (6, 1, 2, 3), (1, 2, 3, 1), etc.
Some invalid sequences are (1, 2, 1, 3), (1, 2, 3, 6).
(1, 2, 1, 3) is invalid since the first and third roll have an equal value and abs(1 - 3) = 2 (i and j are 1-indexed).
(1, 2, 3, 6) is invalid since the greatest common divisor of 3 and 6 = 3.
There are a total of 184 distinct sequences possible, so we return 184.
Example 2:
Input: n = 2
Output: 22
Explanation: Some of the possible sequences are (1, 2), (2, 1), (3, 2).
Some invalid sequences are (3, 6), (2, 4) since the greatest common divisor is not equal to 1.
There are a total of 22 distinct sequences possible, so we return 22.
Constraints:
1 <= n <= 104 | [Python3] top-down dp | 48 | number-of-distinct-roll-sequences | 0.562 | ye15 | Hard | 31,929 | 2,318 |
check if matrix is x matrix | class Solution:
def checkXMatrix(self, grid: List[List[int]]) -> bool:
a=0
j=len(grid)-1
for i in range(0,len(grid)):
if grid[i][i]==0 or grid[i][j]==0:
return False
else:
if i!=j:
a=grid[i][i]+grid[i][j]
elif i==j:
a=grid[i][i]
if a!=sum(grid[i]):
return False
j-=1
return True | https://leetcode.com/problems/check-if-matrix-is-x-matrix/discuss/2368873/Easiest-Python-solution-you-will-find.......-Single-loop | 1 | A square matrix is said to be an X-Matrix if both of the following conditions hold:
All the elements in the diagonals of the matrix are non-zero.
All other elements are 0.
Given a 2D integer array grid of size n x n representing a square matrix, return true if grid is an X-Matrix. Otherwise, return false.
Example 1:
Input: grid = [[2,0,0,1],[0,3,1,0],[0,5,2,0],[4,0,0,2]]
Output: true
Explanation: Refer to the diagram above.
An X-Matrix should have the green elements (diagonals) be non-zero and the red elements be 0.
Thus, grid is an X-Matrix.
Example 2:
Input: grid = [[5,7,0],[0,3,1],[0,5,0]]
Output: false
Explanation: Refer to the diagram above.
An X-Matrix should have the green elements (diagonals) be non-zero and the red elements be 0.
Thus, grid is not an X-Matrix.
Constraints:
n == grid.length == grid[i].length
3 <= n <= 100
0 <= grid[i][j] <= 105 | Easiest Python solution you will find....... Single loop | 46 | check-if-matrix-is-x-matrix | 0.673 | guneet100 | Easy | 31,934 | 2,319 |
count number of ways to place houses | class Solution:
def countHousePlacements(self, n: int) -> int:
pre,ppre = 2,1
if n==1:
return 4
for i in range(1,n):
temp = pre+ppre
ppre = pre
pre = temp
return ((pre)**2)%((10**9) + 7) | https://leetcode.com/problems/count-number-of-ways-to-place-houses/discuss/2198265/Python-Simple-Solution-or-O(n)-time-complexity-or-Basic-Approach-or-DP | 2 | There is a street with n * 2 plots, where there are n plots on each side of the street. The plots on each side are numbered from 1 to n. On each plot, a house can be placed.
Return the number of ways houses can be placed such that no two houses are adjacent to each other on the same side of the street. Since the answer may be very large, return it modulo 109 + 7.
Note that if a house is placed on the ith plot on one side of the street, a house can also be placed on the ith plot on the other side of the street.
Example 1:
Input: n = 1
Output: 4
Explanation:
Possible arrangements:
1. All plots are empty.
2. A house is placed on one side of the street.
3. A house is placed on the other side of the street.
4. Two houses are placed, one on each side of the street.
Example 2:
Input: n = 2
Output: 9
Explanation: The 9 possible arrangements are shown in the diagram above.
Constraints:
1 <= n <= 104 | Python Simple Solution | O(n) time complexity | Basic Approach | DP | 95 | count-number-of-ways-to-place-houses | 0.401 | AkashHooda | Medium | 31,953 | 2,320 |
maximum score of spliced array | class Solution:
def maximumsSplicedArray(self, nums1: List[int], nums2: List[int]) -> int:
# create a difference array between nums1 and nums2
# idea: find two subarray(elements are contiguous) in the diff
# one is the subarray that have the minimum negative sum
# another one is the subarray that have the maximum positive sum
# so there are four candidates for maximum score:
# 1. original_sum1
# 2. original_sum
# 3. original_sum1 - min_negative_sum
# 4. original_sum2 + max_positive_sum
original_sum1 = sum(nums1)
original_sum2 = sum(nums2)
diff = [num1 - num2 for num1, num2 in zip(nums1, nums2)]
min_negative_sum = float('inf')
max_positive_sum = - float('inf')
cur_negative_sum = 0
cur_positive_sum = 0
for val in diff:
cur_negative_sum += val
if cur_negative_sum > 0:
cur_negative_sum = 0
cur_positive_sum += val
if cur_positive_sum < 0:
cur_positive_sum = 0
min_negative_sum = min(min_negative_sum, cur_negative_sum)
max_positive_sum = max(max_positive_sum, cur_positive_sum)
return max(original_sum1 - min_negative_sum, original_sum2 + max_positive_sum, original_sum2, original_sum1) | https://leetcode.com/problems/maximum-score-of-spliced-array/discuss/2198195/Python-or-Easy-to-Understand-or-With-Explanation-or-No-Kadane | 2 | You are given two 0-indexed integer arrays nums1 and nums2, both of length n.
You can choose two integers left and right where 0 <= left <= right < n and swap the subarray nums1[left...right] with the subarray nums2[left...right].
For example, if nums1 = [1,2,3,4,5] and nums2 = [11,12,13,14,15] and you choose left = 1 and right = 2, nums1 becomes [1,12,13,4,5] and nums2 becomes [11,2,3,14,15].
You may choose to apply the mentioned operation once or not do anything.
The score of the arrays is the maximum of sum(nums1) and sum(nums2), where sum(arr) is the sum of all the elements in the array arr.
Return the maximum possible score.
A subarray is a contiguous sequence of elements within an array. arr[left...right] denotes the subarray that contains the elements of nums between indices left and right (inclusive).
Example 1:
Input: nums1 = [60,60,60], nums2 = [10,90,10]
Output: 210
Explanation: Choosing left = 1 and right = 1, we have nums1 = [60,90,60] and nums2 = [10,60,10].
The score is max(sum(nums1), sum(nums2)) = max(210, 80) = 210.
Example 2:
Input: nums1 = [20,40,20,70,30], nums2 = [50,20,50,40,20]
Output: 220
Explanation: Choosing left = 3, right = 4, we have nums1 = [20,40,20,40,20] and nums2 = [50,20,50,70,30].
The score is max(sum(nums1), sum(nums2)) = max(140, 220) = 220.
Example 3:
Input: nums1 = [7,11,13], nums2 = [1,1,1]
Output: 31
Explanation: We choose not to swap any subarray.
The score is max(sum(nums1), sum(nums2)) = max(31, 3) = 31.
Constraints:
n == nums1.length == nums2.length
1 <= n <= 105
1 <= nums1[i], nums2[i] <= 104 | Python | Easy to Understand | With Explanation | No Kadane | 150 | maximum-score-of-spliced-array | 0.554 | Mikey98 | Hard | 31,968 | 2,321 |
minimum score after removals on a tree | class Solution:
def minimumScore(self, nums: List[int], edges: List[List[int]]) -> int:
n = len(nums)
graph = [[] for _ in range(n)]
for u, v in edges:
graph[u].append(v)
graph[v].append(u)
def fn(u):
score[u] = nums[u]
child[u] = {u}
for v in graph[u]:
if seen[v] == 0:
seen[v] = 1
fn(v)
score[u] ^= score[v]
child[u] |= child[v]
seen = [1] + [0]*(n-1)
score = [0]*n
child = [set() for _ in range(n)]
fn(0)
ans = inf
for u in range(1, n):
for v in range(u+1, n):
if u in child[v]:
uu = score[u]
vv = score[v] ^ score[u]
xx = score[0] ^ score[v]
elif v in child[u]:
uu = score[u] ^ score[v]
vv = score[v]
xx = score[0] ^ score[u]
else:
uu = score[u]
vv = score[v]
xx = score[0] ^ score[u] ^ score[v]
ans = min(ans, max(uu, vv, xx) - min(uu, vv, xx))
return ans | https://leetcode.com/problems/minimum-score-after-removals-on-a-tree/discuss/2198386/Python3-dfs | 6 | 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] indicates that there is an edge between nodes ai and bi in the tree.
Remove two distinct edges of the tree to form three connected components. For a pair of removed edges, the following steps are defined:
Get the XOR of all the values of the nodes for each of the three components respectively.
The difference between the largest XOR value and the smallest XOR value is the score of the pair.
For example, say the three components have the node values: [4,5,7], [1,9], and [3,3,3]. The three XOR values are 4 ^ 5 ^ 7 = 6, 1 ^ 9 = 8, and 3 ^ 3 ^ 3 = 3. The largest XOR value is 8 and the smallest XOR value is 3. The score is then 8 - 3 = 5.
Return the minimum score of any possible pair of edge removals on the given tree.
Example 1:
Input: nums = [1,5,5,4,11], edges = [[0,1],[1,2],[1,3],[3,4]]
Output: 9
Explanation: The diagram above shows a way to make a pair of removals.
- The 1st component has nodes [1,3,4] with values [5,4,11]. Its XOR value is 5 ^ 4 ^ 11 = 10.
- The 2nd component has node [0] with value [1]. Its XOR value is 1 = 1.
- The 3rd component has node [2] with value [5]. Its XOR value is 5 = 5.
The score is the difference between the largest and smallest XOR value which is 10 - 1 = 9.
It can be shown that no other pair of removals will obtain a smaller score than 9.
Example 2:
Input: nums = [5,5,2,4,4,2], edges = [[0,1],[1,2],[5,2],[4,3],[1,3]]
Output: 0
Explanation: The diagram above shows a way to make a pair of removals.
- The 1st component has nodes [3,4] with values [4,4]. Its XOR value is 4 ^ 4 = 0.
- The 2nd component has nodes [1,0] with values [5,5]. Its XOR value is 5 ^ 5 = 0.
- The 3rd component has nodes [2,5] with values [2,2]. Its XOR value is 2 ^ 2 = 0.
The score is the difference between the largest and smallest XOR value which is 0 - 0 = 0.
We cannot obtain a smaller score than 0.
Constraints:
n == nums.length
3 <= n <= 1000
1 <= nums[i] <= 108
edges.length == n - 1
edges[i].length == 2
0 <= ai, bi < n
ai != bi
edges represents a valid tree. | [Python3] dfs | 241 | minimum-score-after-removals-on-a-tree | 0.506 | ye15 | Hard | 31,980 | 2,322 |
decode the message | class Solution:
def decodeMessage(self, key: str, message: str) -> str:
mapping = {' ': ' '}
i = 0
res = ''
letters = 'abcdefghijklmnopqrstuvwxyz'
for char in key:
if char not in mapping:
mapping[char] = letters[i]
i += 1
for char in message:
res += mapping[char]
return res | https://leetcode.com/problems/decode-the-message/discuss/2229844/Easy-Python-solution-using-Hashing | 23 | You are given the strings key and message, which represent a cipher key and a secret message, respectively. The steps to decode message are as follows:
Use the first appearance of all 26 lowercase English letters in key as the order of the substitution table.
Align the substitution table with the regular English alphabet.
Each letter in message is then substituted using the table.
Spaces ' ' are transformed to themselves.
For example, given key = "happy boy" (actual key would have at least one instance of each letter in the alphabet), we have the partial substitution table of ('h' -> 'a', 'a' -> 'b', 'p' -> 'c', 'y' -> 'd', 'b' -> 'e', 'o' -> 'f').
Return the decoded message.
Example 1:
Input: key = "the quick brown fox jumps over the lazy dog", message = "vkbs bs t suepuv"
Output: "this is a secret"
Explanation: The diagram above shows the substitution table.
It is obtained by taking the first appearance of each letter in "the quick brown fox jumps over the lazy dog".
Example 2:
Input: key = "eljuxhpwnyrdgtqkviszcfmabo", message = "zwx hnfx lqantp mnoeius ycgk vcnjrdb"
Output: "the five boxing wizards jump quickly"
Explanation: The diagram above shows the substitution table.
It is obtained by taking the first appearance of each letter in "eljuxhpwnyrdgtqkviszcfmabo".
Constraints:
26 <= key.length <= 2000
key consists of lowercase English letters and ' '.
key contains every letter in the English alphabet ('a' to 'z') at least once.
1 <= message.length <= 2000
message consists of lowercase English letters and ' '. | Easy Python solution using Hashing | 1,400 | decode-the-message | 0.848 | MiKueen | Easy | 31,986 | 2,325 |
spiral matrix iv | class Solution:
def spiralMatrix(self, m: int, n: int, head: Optional[ListNode]) -> List[List[int]]:
matrix = [[-1]*n for i in range(m)]
current = head
direction = 1
i, j = 0, -1
while current:
for _ in range(n):
if current:
j += direction
matrix[i][j] = current.val
current = current.next
m -= 1
for _ in range(m):
if current:
i += direction
matrix[i][j] = current.val
current = current.next
n -= 1
direction *= -1
return matrix | https://leetcode.com/problems/spiral-matrix-iv/discuss/2230251/Python-easy-solution-using-direction-variable | 1 | You are given two integers m and n, which represent the dimensions of a matrix.
You are also given the head of a linked list of integers.
Generate an m x n matrix that contains the integers in the linked list presented in spiral order (clockwise), starting from the top-left of the matrix. If there are remaining empty spaces, fill them with -1.
Return the generated matrix.
Example 1:
Input: m = 3, n = 5, head = [3,0,2,6,8,1,7,9,4,2,5,5,0]
Output: [[3,0,2,6,8],[5,0,-1,-1,1],[5,2,4,9,7]]
Explanation: The diagram above shows how the values are printed in the matrix.
Note that the remaining spaces in the matrix are filled with -1.
Example 2:
Input: m = 1, n = 4, head = [0,1,2]
Output: [[0,1,2,-1]]
Explanation: The diagram above shows how the values are printed from left to right in the matrix.
The last space in the matrix is set to -1.
Constraints:
1 <= m, n <= 105
1 <= m * n <= 105
The number of nodes in the list is in the range [1, m * n].
0 <= Node.val <= 1000 | Python easy solution using direction variable | 36 | spiral-matrix-iv | 0.745 | HunkWhoCodes | Medium | 32,017 | 2,326 |
number of people aware of a secret | class Solution:
def peopleAwareOfSecret(self, n: int, d: int, f: int) -> int:
dp, md = [1] + [0] * (f - 1), 10**9 + 7
for i in range(1, n):
dp[i % f] = (md + dp[(i + f - d) % f] - dp[i % f] + (0 if i == 1 else dp[(i - 1) % f])) % md
return sum(dp) % md | https://leetcode.com/problems/number-of-people-aware-of-a-secret/discuss/2229808/Two-Queues-or-Rolling-Array | 53 | On day 1, one person discovers a secret.
You are given an integer delay, which means that each person will share the secret with a new person every day, starting from delay days after discovering the secret. You are also given an integer forget, which means that each person will forget the secret forget days after discovering it. A person cannot share the secret on the same day they forgot it, or on any day afterwards.
Given an integer n, return the number of people who know the secret at the end of day n. Since the answer may be very large, return it modulo 109 + 7.
Example 1:
Input: n = 6, delay = 2, forget = 4
Output: 5
Explanation:
Day 1: Suppose the first person is named A. (1 person)
Day 2: A is the only person who knows the secret. (1 person)
Day 3: A shares the secret with a new person, B. (2 people)
Day 4: A shares the secret with a new person, C. (3 people)
Day 5: A forgets the secret, and B shares the secret with a new person, D. (3 people)
Day 6: B shares the secret with E, and C shares the secret with F. (5 people)
Example 2:
Input: n = 4, delay = 1, forget = 3
Output: 6
Explanation:
Day 1: The first person is named A. (1 person)
Day 2: A shares the secret with B. (2 people)
Day 3: A and B share the secret with 2 new people, C and D. (4 people)
Day 4: A forgets the secret. B, C, and D share the secret with 3 new people. (6 people)
Constraints:
2 <= n <= 1000
1 <= delay < forget <= n | Two Queues or Rolling Array | 3,300 | number-of-people-aware-of-a-secret | 0.445 | votrubac | Medium | 32,025 | 2,327 |
number of increasing paths in a grid | class Solution:
def countPaths(self, grid: List[List[int]]) -> int:
rows, cols = len(grid), len(grid[0])
dp = {}
mod = (10 ** 9) + 7
def dfs(r, c, prev):
if r < 0 or c < 0 or r >= rows or c >= cols or grid[r][c] <= prev:
return 0
if (r, c) in dp:
return dp[(r, c)]
pathLength = 1
pathLength += (dfs(r + 1, c, grid[r][c]) + dfs(r - 1, c, grid[r][c]) +
dfs(r, c + 1, grid[r][c]) + dfs(r, c - 1, grid[r][c]))
dp[(r, c)] = pathLength
return pathLength
count = 0
for r in range(rows):
for c in range(cols):
count += dfs(r, c, 0)
return count % mod | https://leetcode.com/problems/number-of-increasing-paths-in-a-grid/discuss/2691096/Python-(Faster-than-94)-or-DFS-%2B-DP-O(N*M)-solution | 0 | You are given an m x n integer matrix grid, where you can move from a cell to any adjacent cell in all 4 directions.
Return the number of strictly increasing paths in the grid such that you can start from any cell and end at any cell. Since the answer may be very large, return it modulo 109 + 7.
Two paths are considered different if they do not have exactly the same sequence of visited cells.
Example 1:
Input: grid = [[1,1],[3,4]]
Output: 8
Explanation: The strictly increasing paths are:
- Paths with length 1: [1], [1], [3], [4].
- Paths with length 2: [1 -> 3], [1 -> 4], [3 -> 4].
- Paths with length 3: [1 -> 3 -> 4].
The total number of paths is 4 + 3 + 1 = 8.
Example 2:
Input: grid = [[1],[2]]
Output: 3
Explanation: The strictly increasing paths are:
- Paths with length 1: [1], [2].
- Paths with length 2: [1 -> 2].
The total number of paths is 2 + 1 = 3.
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 1000
1 <= m * n <= 105
1 <= grid[i][j] <= 105 | Python (Faster than 94%) | DFS + DP O(N*M) solution | 3 | number-of-increasing-paths-in-a-grid | 0.476 | KevinJM17 | Hard | 32,038 | 2,328 |
evaluate boolean binary tree | class Solution:
def evaluateTree(self, root: Optional[TreeNode]) -> bool:
if root.val==0 or root.val==1:
return root.val
if root.val==2:
return self.evaluateTree(root.left) or self.evaluateTree(root.right)
if root.val==3:
return self.evaluateTree(root.left) and self.evaluateTree(root.right) | https://leetcode.com/problems/evaluate-boolean-binary-tree/discuss/2566445/Easy-python-6-line-solution | 6 | You are given the root of a full binary tree with the following properties:
Leaf nodes have either the value 0 or 1, where 0 represents False and 1 represents True.
Non-leaf nodes have either the value 2 or 3, where 2 represents the boolean OR and 3 represents the boolean AND.
The evaluation of a node is as follows:
If the node is a leaf node, the evaluation is the value of the node, i.e. True or False.
Otherwise, evaluate the node's two children and apply the boolean operation of its value with the children's evaluations.
Return the boolean result of evaluating the root node.
A full binary tree is a binary tree where each node has either 0 or 2 children.
A leaf node is a node that has zero children.
Example 1:
Input: root = [2,1,3,null,null,0,1]
Output: true
Explanation: The above diagram illustrates the evaluation process.
The AND node evaluates to False AND True = False.
The OR node evaluates to True OR False = True.
The root node evaluates to True, so we return true.
Example 2:
Input: root = [0]
Output: false
Explanation: The root node is a leaf node and it evaluates to false, so we return false.
Constraints:
The number of nodes in the tree is in the range [1, 1000].
0 <= Node.val <= 3
Every node has either 0 or 2 children.
Leaf nodes have a value of 0 or 1.
Non-leaf nodes have a value of 2 or 3. | Easy python 6 line solution | 282 | evaluate-boolean-binary-tree | 0.791 | shubham_1307 | Easy | 32,044 | 2,331 |
the latest time to catch a bus | class Solution:
def latestTimeCatchTheBus(self, buses: List[int], passengers: List[int], capacity: int) -> int:
buses.sort()
passengers.sort()
passenger = 0
for bus in buses:
maxed_out = False
cap = capacity
while passenger < len(passengers) and passengers[passenger] <= bus and cap != 0:
passenger += 1
cap -= 1
if cap == 0:
maxed_out = True
if maxed_out:
max_seat = passengers[passenger - 1]
else:
max_seat = buses[-1]
booked = set(passengers)
for seat in range(max_seat, 0, -1):
if seat not in booked:
return seat | https://leetcode.com/problems/the-latest-time-to-catch-a-bus/discuss/2259189/Clean-and-Concise-Greedy-with-Intuitive-Explanation | 5 | You are given a 0-indexed integer array buses of length n, where buses[i] represents the departure time of the ith bus. You are also given a 0-indexed integer array passengers of length m, where passengers[j] represents the arrival time of the jth passenger. All bus departure times are unique. All passenger arrival times are unique.
You are given an integer capacity, which represents the maximum number of passengers that can get on each bus.
When a passenger arrives, they will wait in line for the next available bus. You can get on a bus that departs at x minutes if you arrive at y minutes where y <= x, and the bus is not full. Passengers with the earliest arrival times get on the bus first.
More formally when a bus arrives, either:
If capacity or fewer passengers are waiting for a bus, they will all get on the bus, or
The capacity passengers with the earliest arrival times will get on the bus.
Return the latest time you may arrive at the bus station to catch a bus. You cannot arrive at the same time as another passenger.
Note: The arrays buses and passengers are not necessarily sorted.
Example 1:
Input: buses = [10,20], passengers = [2,17,18,19], capacity = 2
Output: 16
Explanation: Suppose you arrive at time 16.
At time 10, the first bus departs with the 0th passenger.
At time 20, the second bus departs with you and the 1st passenger.
Note that you may not arrive at the same time as another passenger, which is why you must arrive before the 1st passenger to catch the bus.
Example 2:
Input: buses = [20,30,10], passengers = [19,13,26,4,25,11,21], capacity = 2
Output: 20
Explanation: Suppose you arrive at time 20.
At time 10, the first bus departs with the 3rd passenger.
At time 20, the second bus departs with the 5th and 1st passengers.
At time 30, the third bus departs with the 0th passenger and you.
Notice if you had arrived any later, then the 6th passenger would have taken your seat on the third bus.
Constraints:
n == buses.length
m == passengers.length
1 <= n, m, capacity <= 105
2 <= buses[i], passengers[i] <= 109
Each element in buses is unique.
Each element in passengers is unique. | Clean and Concise Greedy with Intuitive Explanation | 472 | the-latest-time-to-catch-a-bus | 0.229 | wickedmishra | Medium | 32,058 | 2,332 |
minimum sum of squared difference | class Solution:
def minSumSquareDiff(self, nums1: List[int], nums2: List[int], k1: int, k2: int) -> int:
n = len(nums1)
k = k1+k2 # can combine k's because items can be turned negative
diffs = sorted((abs(x - y) for x, y in zip(nums1, nums2)))
# First binary search to find our new max for our diffs array
l, r = 0, max(diffs)
while l < r:
mid = (l+r)//2
# steps needed to reduce all nums greater than newMax
steps = sum(max(0, num-mid) for num in diffs)
if steps <= k:
r = mid
else:
l = mid+1
newMax = l
k -= sum(max(0, num-newMax) for num in diffs) # remove used k
# Second binary search to find first index to replace with max val
l, r = 0, n-1
while l < r:
mid = (l+r)//2
if diffs[mid] < newMax:
l = mid+1
else:
r = mid
# Replace items at index >= l with newMax
diffs = diffs[:l]+[newMax]*(n-l)
# Use remaining steps to reduce overall score
for i in range(len(diffs)-1,-1,-1):
if k == 0 or diffs[i] == 0: break
diffs[i] -= 1
k -= 1
return sum(diff*diff for diff in diffs) | https://leetcode.com/problems/minimum-sum-of-squared-difference/discuss/2259712/Python-Easy-to-understand-binary-search-solution | 1 | You are given two positive 0-indexed integer arrays nums1 and nums2, both of length n.
The sum of squared difference of arrays nums1 and nums2 is defined as the sum of (nums1[i] - nums2[i])2 for each 0 <= i < n.
You are also given two positive integers k1 and k2. You can modify any of the elements of nums1 by +1 or -1 at most k1 times. Similarly, you can modify any of the elements of nums2 by +1 or -1 at most k2 times.
Return the minimum sum of squared difference after modifying array nums1 at most k1 times and modifying array nums2 at most k2 times.
Note: You are allowed to modify the array elements to become negative integers.
Example 1:
Input: nums1 = [1,2,3,4], nums2 = [2,10,20,19], k1 = 0, k2 = 0
Output: 579
Explanation: The elements in nums1 and nums2 cannot be modified because k1 = 0 and k2 = 0.
The sum of square difference will be: (1 - 2)2 + (2 - 10)2 + (3 - 20)2 + (4 - 19)2 = 579.
Example 2:
Input: nums1 = [1,4,10,12], nums2 = [5,8,6,9], k1 = 1, k2 = 1
Output: 43
Explanation: One way to obtain the minimum sum of square difference is:
- Increase nums1[0] once.
- Increase nums2[2] once.
The minimum of the sum of square difference will be:
(2 - 5)2 + (4 - 8)2 + (10 - 7)2 + (12 - 9)2 = 43.
Note that, there are other ways to obtain the minimum of the sum of square difference, but there is no way to obtain a sum smaller than 43.
Constraints:
n == nums1.length == nums2.length
1 <= n <= 105
0 <= nums1[i], nums2[i] <= 105
0 <= k1, k2 <= 109 | [Python] Easy to understand binary search solution | 106 | minimum-sum-of-squared-difference | 0.255 | fomiee | Medium | 32,063 | 2,333 |
subarray with elements greater than varying threshold | class Solution:
def validSubarraySize(self, nums: List[int], threshold: int) -> int:
# Stack elements are the array's indices idx, and montonic with respect to nums[idx].
# When the index of the nearest smaller value to nums[idx] comes to the top of the
# stack, we check whether the threshold criterion is satisfied. If so, we are done.
# If not, we continue. Return -1 if we reach the end of nums without a winner.
nums.append(0)
stack = deque()
for idx in range(len(nums)):
while stack and nums[idx] <= nums[stack[-1]]:
n = nums[stack.pop()] # n is the next smaller value for nums[idx]
k = idx if not stack else idx - stack[-1] -1
if n > threshold //k: return k # threshold criterion. if n passes, all
# elements of the interval pass
stack.append(idx)
return -1 | https://leetcode.com/problems/subarray-with-elements-greater-than-varying-threshold/discuss/2260689/Python3.-oror-Stack-9-lines-oror-TM-%3A-986-ms28-MB | 7 | You are given an integer array nums and an integer threshold.
Find any subarray of nums of length k such that every element in the subarray is greater than threshold / k.
Return the size of any such subarray. If there is no such subarray, return -1.
A subarray is a contiguous non-empty sequence of elements within an array.
Example 1:
Input: nums = [1,3,4,3,1], threshold = 6
Output: 3
Explanation: The subarray [3,4,3] has a size of 3, and every element is greater than 6 / 3 = 2.
Note that this is the only valid subarray.
Example 2:
Input: nums = [6,5,6,5,8], threshold = 7
Output: 1
Explanation: The subarray [8] has a size of 1, and 8 > 7 / 1 = 7. So 1 is returned.
Note that the subarray [6,5] has a size of 2, and every element is greater than 7 / 2 = 3.5.
Similarly, the subarrays [6,5,6], [6,5,6,5], [6,5,6,5,8] also satisfy the given conditions.
Therefore, 2, 3, 4, or 5 may also be returned.
Constraints:
1 <= nums.length <= 105
1 <= nums[i], threshold <= 109 | Python3. || Stack, 9 lines || T/M : 986 ms/28 MB | 101 | subarray-with-elements-greater-than-varying-threshold | 0.404 | warrenruud | Hard | 32,070 | 2,334 |
minimum amount of time to fill cups | class Solution:
def fillCups(self, amount: List[int]) -> int:
pq = [-q for q in amount if q != 0]
heapq.heapify(pq)
ret = 0
while len(pq) > 1:
first = heapq.heappop(pq)
second = heapq.heappop(pq)
first += 1
second += 1
ret += 1
if first:
heapq.heappush(pq, first)
if second:
heapq.heappush(pq, second)
if pq:
return ret - pq[0]
else:
return ret | https://leetcode.com/problems/minimum-amount-of-time-to-fill-cups/discuss/2262041/Python-or-Straightforward-MaxHeap-Solution | 7 | You have a water dispenser that can dispense cold, warm, and hot water. Every second, you can either fill up 2 cups with different types of water, or 1 cup of any type of water.
You are given a 0-indexed integer array amount of length 3 where amount[0], amount[1], and amount[2] denote the number of cold, warm, and hot water cups you need to fill respectively. Return the minimum number of seconds needed to fill up all the cups.
Example 1:
Input: amount = [1,4,2]
Output: 4
Explanation: One way to fill up the cups is:
Second 1: Fill up a cold cup and a warm cup.
Second 2: Fill up a warm cup and a hot cup.
Second 3: Fill up a warm cup and a hot cup.
Second 4: Fill up a warm cup.
It can be proven that 4 is the minimum number of seconds needed.
Example 2:
Input: amount = [5,4,4]
Output: 7
Explanation: One way to fill up the cups is:
Second 1: Fill up a cold cup, and a hot cup.
Second 2: Fill up a cold cup, and a warm cup.
Second 3: Fill up a cold cup, and a warm cup.
Second 4: Fill up a warm cup, and a hot cup.
Second 5: Fill up a cold cup, and a hot cup.
Second 6: Fill up a cold cup, and a warm cup.
Second 7: Fill up a hot cup.
Example 3:
Input: amount = [5,0,0]
Output: 5
Explanation: Every second, we fill up a cold cup.
Constraints:
amount.length == 3
0 <= amount[i] <= 100 | Python | Straightforward MaxHeap Solution | 563 | minimum-amount-of-time-to-fill-cups | 0.555 | lukefall425 | Easy | 32,075 | 2,335 |
move pieces to obtain a string | class Solution:
# Criteria for a valid transormation:
# 1) The # of Ls, # of Rs , and # of _s must be equal between the two strings
#
# 2) The ordering of Ls and Rs in the two strings must be the same.
#
# 3) Ls can only move left and Rs can only move right, so each L in start
# cannot be to the left of its corresponding L in target, and each R cannot
# be to the right of its corresponding R in target.
def canChange(self, start: str, target: str) -> bool:
if (len(start) != len(target) or
start.count('_') != target.count('_')): return False # <-- Criterion 1
s = [(ch,i) for i, ch in enumerate(start ) if ch != '_']
t = [(ch,i) for i, ch in enumerate(target) if ch != '_']
for i in range(len(s)):
(sc, si), (tc,ti) = s[i], t[i]
if sc != tc: return False # <-- Criteria 1 & 2
if sc == 'L' and si < ti: return False # <-- Criterion 3
if sc == 'R' and si > ti: return False # <--/
return True # <-- It's a winner! | https://leetcode.com/problems/move-pieces-to-obtain-a-string/discuss/2274805/Python3-oror-10-lines-w-explanation-oror-TM%3A-96-44 | 3 | You are given two strings start and target, both of length n. Each string consists only of the characters 'L', 'R', and '_' where:
The characters 'L' and 'R' represent pieces, where a piece 'L' can move to the left only if there is a blank space directly to its left, and a piece 'R' can move to the right only if there is a blank space directly to its right.
The character '_' represents a blank space that can be occupied by any of the 'L' or 'R' pieces.
Return true if it is possible to obtain the string target by moving the pieces of the string start any number of times. Otherwise, return false.
Example 1:
Input: start = "_L__R__R_", target = "L______RR"
Output: true
Explanation: We can obtain the string target from start by doing the following moves:
- Move the first piece one step to the left, start becomes equal to "L___R__R_".
- Move the last piece one step to the right, start becomes equal to "L___R___R".
- Move the second piece three steps to the right, start becomes equal to "L______RR".
Since it is possible to get the string target from start, we return true.
Example 2:
Input: start = "R_L_", target = "__LR"
Output: false
Explanation: The 'R' piece in the string start can move one step to the right to obtain "_RL_".
After that, no pieces can move anymore, so it is impossible to obtain the string target from start.
Example 3:
Input: start = "_R", target = "R_"
Output: false
Explanation: The piece in the string start can move only to the right, so it is impossible to obtain the string target from start.
Constraints:
n == start.length == target.length
1 <= n <= 105
start and target consist of the characters 'L', 'R', and '_'. | Python3 || 10 lines, w/ explanation || T/M: 96%/ 44% | 127 | move-pieces-to-obtain-a-string | 0.481 | warrenruud | Medium | 32,090 | 2,337 |
count the number of ideal arrays | class Solution:
def idealArrays(self, n: int, maxValue: int) -> int:
ans = maxValue
freq = {x : 1 for x in range(1, maxValue+1)}
for k in range(1, n):
temp = Counter()
for x in freq:
for m in range(2, maxValue//x+1):
ans += comb(n-1, k)*freq[x]
temp[m*x] += freq[x]
freq = temp
ans %= 1_000_000_007
return ans | https://leetcode.com/problems/count-the-number-of-ideal-arrays/discuss/2261351/Python3-freq-table | 26 | 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 - 1], for 0 < i < n.
Return the number of distinct ideal arrays of length n. Since the answer may be very large, return it modulo 109 + 7.
Example 1:
Input: n = 2, maxValue = 5
Output: 10
Explanation: The following are the possible ideal arrays:
- Arrays starting with the value 1 (5 arrays): [1,1], [1,2], [1,3], [1,4], [1,5]
- Arrays starting with the value 2 (2 arrays): [2,2], [2,4]
- Arrays starting with the value 3 (1 array): [3,3]
- Arrays starting with the value 4 (1 array): [4,4]
- Arrays starting with the value 5 (1 array): [5,5]
There are a total of 5 + 2 + 1 + 1 + 1 = 10 distinct ideal arrays.
Example 2:
Input: n = 5, maxValue = 3
Output: 11
Explanation: The following are the possible ideal arrays:
- Arrays starting with the value 1 (9 arrays):
- With no other distinct values (1 array): [1,1,1,1,1]
- With 2nd distinct value 2 (4 arrays): [1,1,1,1,2], [1,1,1,2,2], [1,1,2,2,2], [1,2,2,2,2]
- With 2nd distinct value 3 (4 arrays): [1,1,1,1,3], [1,1,1,3,3], [1,1,3,3,3], [1,3,3,3,3]
- Arrays starting with the value 2 (1 array): [2,2,2,2,2]
- Arrays starting with the value 3 (1 array): [3,3,3,3,3]
There are a total of 9 + 1 + 1 = 11 distinct ideal arrays.
Constraints:
2 <= n <= 104
1 <= maxValue <= 104 | [Python3] freq table | 1,500 | count-the-number-of-ideal-arrays | 0.255 | ye15 | Hard | 32,101 | 2,338 |
maximum number of pairs in array | class Solution:
"""
Time: O(n)
Memory: O(n)
"""
def numberOfPairs(self, nums: List[int]) -> List[int]:
pairs = sum(cnt // 2 for cnt in Counter(nums).values())
return [pairs, len(nums) - 2 * pairs] | https://leetcode.com/problems/maximum-number-of-pairs-in-array/discuss/2472693/Python-Elegant-and-Short-or-Two-lines-or-99.91-faster-or-Counter | 5 | You are given a 0-indexed integer array nums. In one operation, you may do the following:
Choose two integers in nums that are equal.
Remove both integers from nums, forming a pair.
The operation is done on nums as many times as possible.
Return a 0-indexed integer array answer of size 2 where answer[0] is the number of pairs that are formed and answer[1] is the number of leftover integers in nums after doing the operation as many times as possible.
Example 1:
Input: nums = [1,3,2,1,3,2,2]
Output: [3,1]
Explanation:
Form a pair with nums[0] and nums[3] and remove them from nums. Now, nums = [3,2,3,2,2].
Form a pair with nums[0] and nums[2] and remove them from nums. Now, nums = [2,2,2].
Form a pair with nums[0] and nums[1] and remove them from nums. Now, nums = [2].
No more pairs can be formed. A total of 3 pairs have been formed, and there is 1 number leftover in nums.
Example 2:
Input: nums = [1,1]
Output: [1,0]
Explanation: Form a pair with nums[0] and nums[1] and remove them from nums. Now, nums = [].
No more pairs can be formed. A total of 1 pair has been formed, and there are 0 numbers leftover in nums.
Example 3:
Input: nums = [0]
Output: [0,1]
Explanation: No pairs can be formed, and there is 1 number leftover in nums.
Constraints:
1 <= nums.length <= 100
0 <= nums[i] <= 100 | Python Elegant & Short | Two lines | 99.91% faster | Counter | 171 | maximum-number-of-pairs-in-array | 0.766 | Kyrylo-Ktl | Easy | 32,106 | 2,341 |
max sum of a pair with equal sum of digits | class Solution: # The plan here is to:
#
# • sort the elements of nums into a dict of maxheaps,
# according to sum-of-digits.
#
# • For each key, determine whether there are at least two
# elements in that key's values, and if so, compute the
# product of the greatest two elements.
#
# • return the the greatest such product as the answer.
# For example:
# nums = [6,15,13,12,24,21] –> {3:[12,21], 4:[13], 6:[6,15,24]}
# Only two keys qualify, 3 and 6, for which the greatest two elements
# are 12,21 and 15,24, respectively. 12+21 = 33 and 15+24 = 39,
# so the answer is 39.
def maximumSum(self, nums: List[int]) -> int:
d, mx = defaultdict(list), -1
digits = lambda x: sum(map(int, list(str(x)))) # <-- sum-of-digits function
for n in nums: # <-- construct max-heaps
heappush(d[digits(n)],-n) # (note "-n")
for i in d: # <-- pop the two greatest values off
if len(d[i]) > 1: # each maxheap (when possible) and
mx= max(mx, -heappop(d[i])-heappop(d[i])) # compare with current max value.
return mx | https://leetcode.com/problems/max-sum-of-a-pair-with-equal-sum-of-digits/discuss/2297244/Python3-oror-dict(heaps)-8-lines-w-explanation-oror-TM%3A-1300ms27MB | 3 | You are given a 0-indexed array nums consisting of positive integers. You can choose two indices i and j, such that i != j, and the sum of digits of the number nums[i] is equal to that of nums[j].
Return the maximum value of nums[i] + nums[j] that you can obtain over all possible indices i and j that satisfy the conditions.
Example 1:
Input: nums = [18,43,36,13,7]
Output: 54
Explanation: The pairs (i, j) that satisfy the conditions are:
- (0, 2), both numbers have a sum of digits equal to 9, and their sum is 18 + 36 = 54.
- (1, 4), both numbers have a sum of digits equal to 7, and their sum is 43 + 7 = 50.
So the maximum sum that we can obtain is 54.
Example 2:
Input: nums = [10,12,19,14]
Output: -1
Explanation: There are no two numbers that satisfy the conditions, so we return -1.
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 109 | Python3 || dict(heaps), 8 lines, w/ explanation || T/M: 1300ms/27MB | 111 | max-sum-of-a-pair-with-equal-sum-of-digits | 0.532 | warrenruud | Medium | 32,140 | 2,342 |
query kth smallest trimmed number | class Solution:
def smallestTrimmedNumbers(self, nums: List[str], queries: List[List[int]]) -> List[int]:
def countingSort(indices, pos):
count = [0] * 10
for idx in indices:
count[ord(nums[idx][pos]) - ord('0')] += 1
start_pos = list(accumulate([0] + count, add))
result = [None] * len(indices)
for idx in indices:
digit = ord(nums[idx][pos]) - ord('0')
result[start_pos[digit]] = idx
start_pos[digit] += 1
return result
n = len(nums)
m = len(nums[0])
suffix_ordered = [list(range(n))]
for i in range(m - 1, -1, -1):
suffix_ordered.append(countingSort(suffix_ordered[-1], i))
return [suffix_ordered[t][k-1] for k, t in queries] | https://leetcode.com/problems/query-kth-smallest-trimmed-number/discuss/2296143/Python-O(m-*-n)-solution-based-on-O(m)-counting-sort | 2 | You are given a 0-indexed array of strings nums, where each string is of equal length and consists of only digits.
You are also given a 0-indexed 2D integer array queries where queries[i] = [ki, trimi]. For each queries[i], you need to:
Trim each number in nums to its rightmost trimi digits.
Determine the index of the kith smallest trimmed number in nums. If two trimmed numbers are equal, the number with the lower index is considered to be smaller.
Reset each number in nums to its original length.
Return an array answer of the same length as queries, where answer[i] is the answer to the ith query.
Note:
To trim to the rightmost x digits means to keep removing the leftmost digit, until only x digits remain.
Strings in nums may contain leading zeros.
Example 1:
Input: nums = ["102","473","251","814"], queries = [[1,1],[2,3],[4,2],[1,2]]
Output: [2,2,1,0]
Explanation:
1. After trimming to the last digit, nums = ["2","3","1","4"]. The smallest number is 1 at index 2.
2. Trimmed to the last 3 digits, nums is unchanged. The 2nd smallest number is 251 at index 2.
3. Trimmed to the last 2 digits, nums = ["02","73","51","14"]. The 4th smallest number is 73.
4. Trimmed to the last 2 digits, the smallest number is 2 at index 0.
Note that the trimmed number "02" is evaluated as 2.
Example 2:
Input: nums = ["24","37","96","04"], queries = [[2,1],[2,2]]
Output: [3,0]
Explanation:
1. Trimmed to the last digit, nums = ["4","7","6","4"]. The 2nd smallest number is 4 at index 3.
There are two occurrences of 4, but the one at index 0 is considered smaller than the one at index 3.
2. Trimmed to the last 2 digits, nums is unchanged. The 2nd smallest number is 24.
Constraints:
1 <= nums.length <= 100
1 <= nums[i].length <= 100
nums[i] consists of only digits.
All nums[i].length are equal.
1 <= queries.length <= 100
queries[i].length == 2
1 <= ki <= nums.length
1 <= trimi <= nums[i].length
Follow up: Could you use the Radix Sort Algorithm to solve this problem? What will be the complexity of that solution? | Python O(m * n) solution based on O(m) counting sort | 99 | query-kth-smallest-trimmed-number | 0.408 | lifuh | Medium | 32,159 | 2,343 |
minimum deletions to make array divisible | class Solution:
# From number theory, we know that an integer num divides each
# integer in a list if and only if num divides the list's gcd.
#
# Our plan here is to:
# • find the gcd of numDivide
# • heapify(nums) and count the popped elements that do not
# divide the gcd.
# • return that count when and if a popped element eventually
# divides the gcd. If that never happens, return -1
def minOperations(self, nums: List[int], numsDivide: List[int]) -> int:
g, ans = gcd(*numsDivide), 0 # <-- find gcd (using * operator)
heapify(nums) # <-- create heap
while nums: # <-- pop and count
if not g%heappop(nums): return ans # <-- found a divisor? return count
else: ans+= 1 # <-- if not, increment the count
return -1 # <-- no divisors found
#--------------------------------------------------
class Solution: # version w/o heap. Seems to run slower
def minOperations(self, nums: List[int], numsDivide: List[int]) -> int:
g = gcd(*numsDivide)
nums.sort()
for i,num in enumerate(nums):
if not g%num: return i
return -1 | https://leetcode.com/problems/minimum-deletions-to-make-array-divisible/discuss/2296334/Python3-oror-GCD-and-heap-6-lines-w-explanation-oror-TM%3A-56100 | 3 | You are given two positive integer arrays nums and numsDivide. You can delete any number of elements from nums.
Return the minimum number of deletions such that the smallest element in nums divides all the elements of numsDivide. If this is not possible, return -1.
Note that an integer x divides y if y % x == 0.
Example 1:
Input: nums = [2,3,2,4,3], numsDivide = [9,6,9,3,15]
Output: 2
Explanation:
The smallest element in [2,3,2,4,3] is 2, which does not divide all the elements of numsDivide.
We use 2 deletions to delete the elements in nums that are equal to 2 which makes nums = [3,4,3].
The smallest element in [3,4,3] is 3, which divides all the elements of numsDivide.
It can be shown that 2 is the minimum number of deletions needed.
Example 2:
Input: nums = [4,3,6], numsDivide = [8,2,6,10]
Output: -1
Explanation:
We want the smallest element in nums to divide all the elements of numsDivide.
There is no way to delete elements from nums to allow this.
Constraints:
1 <= nums.length, numsDivide.length <= 105
1 <= nums[i], numsDivide[i] <= 109 | Python3 || GCD and heap, 6 lines, w/ explanation || T/M: 56%/100% | 37 | minimum-deletions-to-make-array-divisible | 0.57 | warrenruud | Hard | 32,177 | 2,344 |
best poker hand | class Solution:
def bestHand(self, ranks: List[int], suits: List[str]) -> str:
dictRanks = {}
dictSuits = {}
for key in ranks:
dictRanks[key] = dictRanks.get(key, 0) + 1
for key in suits:
dictSuits[key] = dictSuits.get(key, 0) + 1
maxRanks = max(dictRanks.values())
maxSuits = max(dictSuits.values())
if maxSuits == 5:
return "Flush"
if maxRanks >= 3:
return "Three of a Kind"
if maxRanks >= 2:
return "Pair"
return "High Card" | https://leetcode.com/problems/best-poker-hand/discuss/2322411/Python-oror-Easy-Approach | 3 | You are given an integer array ranks and a character array suits. You have 5 cards where the ith card has a rank of ranks[i] and a suit of suits[i].
The following are the types of poker hands you can make from best to worst:
"Flush": Five cards of the same suit.
"Three of a Kind": Three cards of the same rank.
"Pair": Two cards of the same rank.
"High Card": Any single card.
Return a string representing the best type of poker hand you can make with the given cards.
Note that the return values are case-sensitive.
Example 1:
Input: ranks = [13,2,3,1,9], suits = ["a","a","a","a","a"]
Output: "Flush"
Explanation: The hand with all the cards consists of 5 cards with the same suit, so we have a "Flush".
Example 2:
Input: ranks = [4,4,2,4,4], suits = ["d","a","a","b","c"]
Output: "Three of a Kind"
Explanation: The hand with the first, second, and fourth card consists of 3 cards with the same rank, so we have a "Three of a Kind".
Note that we could also make a "Pair" hand but "Three of a Kind" is a better hand.
Also note that other cards could be used to make the "Three of a Kind" hand.
Example 3:
Input: ranks = [10,10,2,12,9], suits = ["a","b","c","a","d"]
Output: "Pair"
Explanation: The hand with the first and second card consists of 2 cards with the same rank, so we have a "Pair".
Note that we cannot make a "Flush" or a "Three of a Kind".
Constraints:
ranks.length == suits.length == 5
1 <= ranks[i] <= 13
'a' <= suits[i] <= 'd'
No two cards have the same rank and suit. | ✅Python || Easy Approach | 116 | best-poker-hand | 0.606 | chuhonghao01 | Easy | 32,188 | 2,347 |
number of zero filled subarrays | class Solution:
def zeroFilledSubarray(self, nums: List[int]) -> int:
n = len(nums)
ans = 0
i, j = 0, 0
while i <= n - 1:
j = 0
if nums[i] == 0:
while i + j <= n - 1 and nums[i + j] == 0:
j += 1
ans += (j + 1) * j // 2
i = i + j + 1
return ans | https://leetcode.com/problems/number-of-zero-filled-subarrays/discuss/2322455/Python-oror-Two-pointers-oror-Easy-Approach | 2 | Given an integer array nums, return the number of subarrays filled with 0.
A subarray is a contiguous non-empty sequence of elements within an array.
Example 1:
Input: nums = [1,3,0,0,2,0,0,4]
Output: 6
Explanation:
There are 4 occurrences of [0] as a subarray.
There are 2 occurrences of [0,0] as a subarray.
There is no occurrence of a subarray with a size more than 2 filled with 0. Therefore, we return 6.
Example 2:
Input: nums = [0,0,0,2,0,0]
Output: 9
Explanation:
There are 5 occurrences of [0] as a subarray.
There are 3 occurrences of [0,0] as a subarray.
There is 1 occurrence of [0,0,0] as a subarray.
There is no occurrence of a subarray with a size more than 3 filled with 0. Therefore, we return 9.
Example 3:
Input: nums = [2,10,2019]
Output: 0
Explanation: There is no subarray filled with 0. Therefore, we return 0.
Constraints:
1 <= nums.length <= 105
-109 <= nums[i] <= 109 | ✅Python || Two-pointers || Easy Approach | 72 | number-of-zero-filled-subarrays | 0.571 | chuhonghao01 | Medium | 32,201 | 2,348 |
shortest impossible sequence of rolls | class Solution:
def shortestSequence(self, rolls: List[int], k: int) -> int:
ans = 0
seen = set()
for x in rolls:
seen.add(x)
if len(seen) == k:
ans += 1
seen.clear()
return ans+1 | https://leetcode.com/problems/shortest-impossible-sequence-of-rolls/discuss/2351553/100-faster-at-my-time-or-easy-python3-solution | 1 | You are given an integer array rolls of length n and an integer k. You roll a k sided dice numbered from 1 to k, n times, where the result of the ith roll is rolls[i].
Return the length of the shortest sequence of rolls that cannot be taken from rolls.
A sequence of rolls of length len is the result of rolling a k sided dice len times.
Note that the sequence taken does not have to be consecutive as long as it is in order.
Example 1:
Input: rolls = [4,2,1,2,3,3,2,4,1], k = 4
Output: 3
Explanation: Every sequence of rolls of length 1, [1], [2], [3], [4], can be taken from rolls.
Every sequence of rolls of length 2, [1, 1], [1, 2], ..., [4, 4], can be taken from rolls.
The sequence [1, 4, 2] cannot be taken from rolls, so we return 3.
Note that there are other sequences that cannot be taken from rolls.
Example 2:
Input: rolls = [1,1,2,2], k = 2
Output: 2
Explanation: Every sequence of rolls of length 1, [1], [2], can be taken from rolls.
The sequence [2, 1] cannot be taken from rolls, so we return 2.
Note that there are other sequences that cannot be taken from rolls but [2, 1] is the shortest.
Example 3:
Input: rolls = [1,1,3,2,2,2,3,3], k = 4
Output: 1
Explanation: The sequence [4] cannot be taken from rolls, so we return 1.
Note that there are other sequences that cannot be taken from rolls but [4] is the shortest.
Constraints:
n == rolls.length
1 <= n <= 105
1 <= rolls[i] <= k <= 105 | 100% faster at my time | easy python3 solution | 40 | shortest-impossible-sequence-of-rolls | 0.684 | vimla_kushwaha | Hard | 32,214 | 2,350 |
first letter to appear twice | class Solution:
def repeatedCharacter(self, s: str) -> str:
setS = set()
for x in s:
if x in setS:
return x
else:
setS.add(x) | https://leetcode.com/problems/first-letter-to-appear-twice/discuss/2324754/Python-oror-Map-oror-Easy-Approach | 17 | Given a string s consisting of lowercase English letters, return the first letter to appear twice.
Note:
A letter a appears twice before another letter b if the second occurrence of a is before the second occurrence of b.
s will contain at least one letter that appears twice.
Example 1:
Input: s = "abccbaacz"
Output: "c"
Explanation:
The letter 'a' appears on the indexes 0, 5 and 6.
The letter 'b' appears on the indexes 1 and 4.
The letter 'c' appears on the indexes 2, 3 and 7.
The letter 'z' appears on the index 8.
The letter 'c' is the first letter to appear twice, because out of all the letters the index of its second occurrence is the smallest.
Example 2:
Input: s = "abcdd"
Output: "d"
Explanation:
The only letter that appears twice is 'd' so we return 'd'.
Constraints:
2 <= s.length <= 100
s consists of lowercase English letters.
s has at least one repeated letter. | ✅Python || Map || Easy Approach | 1,100 | first-letter-to-appear-twice | 0.76 | chuhonghao01 | Easy | 32,219 | 2,351 |
equal row and column pairs | class Solution: # Consider this grid for an example:
# grid = [[1,2,1,9]
# [2,8,9,2]
# [1,2,1,9]
# [9,2,6,3]]
# Here's the plan:
# • Determine tpse, the transpose of grid (using zip(*grid)):
# tspe = [[1,2,1,9]
# [2,8,2,2]
# [1,9,1,6]
# [9,2,9,3]]
# The problem now is to determine the pairs of
# identical rows, one row in tpse and the other in grid.
# • We hash grid and tspe:
#
# Counter(tuple(grid)):
# {(1,2,1,9): 2, (2,8,9,2): 1, (9,2,6,3): 1}
#
# Counter(zip(*grid)):
# {(1,2,1,9): 1, (2,8,2,2): 1, (1,9,1,6): 1, (9,2,9,3): 1}
#
# • We determine the number of pairs:
# (1,2,1,9): 2 and (1,2,1,9): 1 => 2x1 = 2
def equalPairs(self, grid: List[List[int]]) -> int:
tpse = Counter(zip(*grid)) # <-- determine the transpose
# and hash the rows
grid = Counter(map(tuple,grid)) # <-- hash the rows of grid. (Note the tuple-map, so
# we can compare apples w/ apples in next step.)
return sum(tpse[t]*grid[t] for t in tpse) # <-- compute the number of identical pairs
# https://leetcode.com/submissions/detail/755717162/ | https://leetcode.com/problems/equal-row-and-column-pairs/discuss/2328910/Python3-oror-3-lines-transpose-Ctr-w-explanation-oror-TM%3A-100100 | 12 | Given a 0-indexed n x n integer matrix grid, return the number of pairs (ri, cj) such that row ri and column cj are equal.
A row and column pair is considered equal if they contain the same elements in the same order (i.e., an equal array).
Example 1:
Input: grid = [[3,2,1],[1,7,6],[2,7,7]]
Output: 1
Explanation: There is 1 equal row and column pair:
- (Row 2, Column 1): [2,7,7]
Example 2:
Input: grid = [[3,1,2,2],[1,4,4,5],[2,4,2,2],[2,4,2,2]]
Output: 3
Explanation: There are 3 equal row and column pairs:
- (Row 0, Column 0): [3,1,2,2]
- (Row 2, Column 2): [2,4,2,2]
- (Row 3, Column 2): [2,4,2,2]
Constraints:
n == grid.length == grid[i].length
1 <= n <= 200
1 <= grid[i][j] <= 105 | Python3 || 3 lines, transpose, Ctr w/ explanation || T/M: 100%/100% | 443 | equal-row-and-column-pairs | 0.71 | warrenruud | Medium | 32,258 | 2,352 |
number of excellent pairs | class Solution:
def countExcellentPairs(self, nums: List[int], k: int) -> int:
hamming = sorted([self.hammingWeight(num) for num in set(nums)])
ans = 0
for h in hamming:
ans += len(hamming) - bisect.bisect_left(hamming, k - h)
return ans
def hammingWeight(self, n):
ans = 0
while n:
n &= (n - 1)
ans += 1
return ans | https://leetcode.com/problems/number-of-excellent-pairs/discuss/2324641/Python3-Sorting-Hamming-Weights-%2B-Binary-Search-With-Detailed-Explanations | 20 | You are given a 0-indexed positive integer array nums and a positive integer k.
A pair of numbers (num1, num2) is called excellent if the following conditions are satisfied:
Both the numbers num1 and num2 exist in the array nums.
The sum of the number of set bits in num1 OR num2 and num1 AND num2 is greater than or equal to k, where OR is the bitwise OR operation and AND is the bitwise AND operation.
Return the number of distinct excellent pairs.
Two pairs (a, b) and (c, d) are considered distinct if either a != c or b != d. For example, (1, 2) and (2, 1) are distinct.
Note that a pair (num1, num2) such that num1 == num2 can also be excellent if you have at least one occurrence of num1 in the array.
Example 1:
Input: nums = [1,2,3,1], k = 3
Output: 5
Explanation: The excellent pairs are the following:
- (3, 3). (3 AND 3) and (3 OR 3) are both equal to (11) in binary. The total number of set bits is 2 + 2 = 4, which is greater than or equal to k = 3.
- (2, 3) and (3, 2). (2 AND 3) is equal to (10) in binary, and (2 OR 3) is equal to (11) in binary. The total number of set bits is 1 + 2 = 3.
- (1, 3) and (3, 1). (1 AND 3) is equal to (01) in binary, and (1 OR 3) is equal to (11) in binary. The total number of set bits is 1 + 2 = 3.
So the number of excellent pairs is 5.
Example 2:
Input: nums = [5,1,1], k = 10
Output: 0
Explanation: There are no excellent pairs for this array.
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 109
1 <= k <= 60 | [Python3] Sorting Hamming Weights + Binary Search With Detailed Explanations | 674 | number-of-excellent-pairs | 0.458 | xil899 | Hard | 32,283 | 2,354 |
make array zero by subtracting equal amounts | class Solution:
def minimumOperations(self, nums: List[int]) -> int:
return len(set(nums) - {0}) | https://leetcode.com/problems/make-array-zero-by-subtracting-equal-amounts/discuss/2357747/Set | 17 | You are given a non-negative integer array nums. In one operation, you must:
Choose a positive integer x such that x is less than or equal to the smallest non-zero element in nums.
Subtract x from every positive element in nums.
Return the minimum number of operations to make every element in nums equal to 0.
Example 1:
Input: nums = [1,5,0,3,5]
Output: 3
Explanation:
In the first operation, choose x = 1. Now, nums = [0,4,0,2,4].
In the second operation, choose x = 2. Now, nums = [0,2,0,0,2].
In the third operation, choose x = 2. Now, nums = [0,0,0,0,0].
Example 2:
Input: nums = [0]
Output: 0
Explanation: Each element in nums is already 0 so no operations are needed.
Constraints:
1 <= nums.length <= 100
0 <= nums[i] <= 100 | Set | 1,500 | make-array-zero-by-subtracting-equal-amounts | 0.727 | votrubac | Easy | 32,291 | 2,357 |
maximum number of groups entering a competition | class Solution:
def maximumGroups(self, grades: List[int]) -> int:
x = len(grades)
n = 0.5 * ((8 * x + 1) ** 0.5 - 1)
ans = int(n)
return ans | https://leetcode.com/problems/maximum-number-of-groups-entering-a-competition/discuss/2358259/Python-oror-Math-oror-Two-Easy-Approaches | 4 | You are given a positive integer array grades which represents the grades of students in a university. You would like to enter all these students into a competition in ordered non-empty groups, such that the ordering meets the following conditions:
The sum of the grades of students in the ith group is less than the sum of the grades of students in the (i + 1)th group, for all groups (except the last).
The total number of students in the ith group is less than the total number of students in the (i + 1)th group, for all groups (except the last).
Return the maximum number of groups that can be formed.
Example 1:
Input: grades = [10,6,12,7,3,5]
Output: 3
Explanation: The following is a possible way to form 3 groups of students:
- 1st group has the students with grades = [12]. Sum of grades: 12. Student count: 1
- 2nd group has the students with grades = [6,7]. Sum of grades: 6 + 7 = 13. Student count: 2
- 3rd group has the students with grades = [10,3,5]. Sum of grades: 10 + 3 + 5 = 18. Student count: 3
It can be shown that it is not possible to form more than 3 groups.
Example 2:
Input: grades = [8,8]
Output: 1
Explanation: We can only form 1 group, since forming 2 groups would lead to an equal number of students in both groups.
Constraints:
1 <= grades.length <= 105
1 <= grades[i] <= 105 | ✅Python || Math || Two Easy Approaches | 155 | maximum-number-of-groups-entering-a-competition | 0.675 | chuhonghao01 | Medium | 32,325 | 2,358 |
find closest node to given two nodes | class Solution:
def get_neighbors(self, start: int) -> Dict[int, int]:
distances = defaultdict(lambda: math.inf)
queue = deque([start])
level = 0
while queue:
for _ in range(len(queue)):
curr = queue.popleft()
if distances[curr] <= level:
continue
distances[curr] = level
for neighbor in graph[curr]:
queue.append(neighbor)
level += 1
return distances
def closestMeetingNode(self, edges: List[int], node1: int, node2: int) -> int:
n = len(edges)
graph = [[] for _ in range(n)]
for _from, to in enumerate(edges):
if to != -1:
graph[_from].append(to)
a = self.get_neighbors(node1)
b = self.get_neighbors(node2)
options = []
for idx in range(n):
if a[idx] != math.inf and b[idx] != math.inf:
options.append((max(a[idx], b[idx]), idx))
if not options:
return -1
return min(options)[1] | https://leetcode.com/problems/find-closest-node-to-given-two-nodes/discuss/2357692/Simple-Breadth-First-Search-with-Explanation | 2 | You are given a directed graph of n nodes numbered from 0 to n - 1, where each node has at most one outgoing edge.
The graph is represented with a given 0-indexed array edges of size n, indicating that there is a directed edge from node i to node edges[i]. If there is no outgoing edge from i, then edges[i] == -1.
You are also given two integers node1 and node2.
Return the index of the node that can be reached from both node1 and node2, such that the maximum between the distance from node1 to that node, and from node2 to that node is minimized. If there are multiple answers, return the node with the smallest index, and if no possible answer exists, return -1.
Note that edges may contain cycles.
Example 1:
Input: edges = [2,2,3,-1], node1 = 0, node2 = 1
Output: 2
Explanation: The distance from node 0 to node 2 is 1, and the distance from node 1 to node 2 is 1.
The maximum of those two distances is 1. It can be proven that we cannot get a node with a smaller maximum distance than 1, so we return node 2.
Example 2:
Input: edges = [1,2,-1], node1 = 0, node2 = 2
Output: 2
Explanation: The distance from node 0 to node 2 is 2, and the distance from node 2 to itself is 0.
The maximum of those two distances is 2. It can be proven that we cannot get a node with a smaller maximum distance than 2, so we return node 2.
Constraints:
n == edges.length
2 <= n <= 105
-1 <= edges[i] < n
edges[i] != i
0 <= node1, node2 < n | Simple Breadth First Search with Explanation | 137 | find-closest-node-to-given-two-nodes | 0.342 | wickedmishra | Medium | 32,334 | 2,359 |
longest cycle in a graph | class Solution:
def longestCycle(self, edges: List[int]) -> int:
in_d = set()
out_d = set()
for i, j in enumerate(edges):
if j != -1:
in_d.add(j)
out_d.add(i)
potential = in_d & out_d
visited = set()
self.ans = -1
def dfs(node, curr, v):
visited.add(node)
v[node] = curr
nei = edges[node]
if nei in v:
self.ans = max(self.ans, curr - v[nei] + 1)
visited.add(nei)
return
if nei not in visited and nei in potential:
dfs(nei, curr + 1, v)
for node in potential:
dfs(node, 1, {})
return self.ans | https://leetcode.com/problems/longest-cycle-in-a-graph/discuss/2357772/Python3-One-pass-dfs | 5 | You are given a directed graph of n nodes numbered from 0 to n - 1, where each node has at most one outgoing edge.
The graph is represented with a given 0-indexed array edges of size n, indicating that there is a directed edge from node i to node edges[i]. If there is no outgoing edge from node i, then edges[i] == -1.
Return the length of the longest cycle in the graph. If no cycle exists, return -1.
A cycle is a path that starts and ends at the same node.
Example 1:
Input: edges = [3,3,4,2,3]
Output: 3
Explanation: The longest cycle in the graph is the cycle: 2 -> 4 -> 3 -> 2.
The length of this cycle is 3, so 3 is returned.
Example 2:
Input: edges = [2,-1,3,1]
Output: -1
Explanation: There are no cycles in this graph.
Constraints:
n == edges.length
2 <= n <= 105
-1 <= edges[i] < n
edges[i] != i | [Python3] One pass dfs | 257 | longest-cycle-in-a-graph | 0.386 | Remineva | Hard | 32,340 | 2,360 |
merge similar items | class Solution:
def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:
merge_item = items1 + items2
d = defaultdict(int)
for i in merge_item:
value,weight = i
d[value] = d[value] + weight
result = []
for j in sorted(d):
result.append([j,d[j]])
return result | https://leetcode.com/problems/merge-similar-items/discuss/2388802/Python-Simple-Python-Solution-Using-HashMap | 8 | You are given two 2D integer arrays, items1 and items2, representing two sets of items. Each array items has the following properties:
items[i] = [valuei, weighti] where valuei represents the value and weighti represents the weight of the ith item.
The value of each item in items is unique.
Return a 2D integer array ret where ret[i] = [valuei, weighti], with weighti being the sum of weights of all items with value valuei.
Note: ret should be returned in ascending order by value.
Example 1:
Input: items1 = [[1,1],[4,5],[3,8]], items2 = [[3,1],[1,5]]
Output: [[1,6],[3,9],[4,5]]
Explanation:
The item with value = 1 occurs in items1 with weight = 1 and in items2 with weight = 5, total weight = 1 + 5 = 6.
The item with value = 3 occurs in items1 with weight = 8 and in items2 with weight = 1, total weight = 8 + 1 = 9.
The item with value = 4 occurs in items1 with weight = 5, total weight = 5.
Therefore, we return [[1,6],[3,9],[4,5]].
Example 2:
Input: items1 = [[1,1],[3,2],[2,3]], items2 = [[2,1],[3,2],[1,3]]
Output: [[1,4],[2,4],[3,4]]
Explanation:
The item with value = 1 occurs in items1 with weight = 1 and in items2 with weight = 3, total weight = 1 + 3 = 4.
The item with value = 2 occurs in items1 with weight = 3 and in items2 with weight = 1, total weight = 3 + 1 = 4.
The item with value = 3 occurs in items1 with weight = 2 and in items2 with weight = 2, total weight = 2 + 2 = 4.
Therefore, we return [[1,4],[2,4],[3,4]].
Example 3:
Input: items1 = [[1,3],[2,2]], items2 = [[7,1],[2,2],[1,4]]
Output: [[1,7],[2,4],[7,1]]
Explanation:
The item with value = 1 occurs in items1 with weight = 3 and in items2 with weight = 4, total weight = 3 + 4 = 7.
The item with value = 2 occurs in items1 with weight = 2 and in items2 with weight = 2, total weight = 2 + 2 = 4.
The item with value = 7 occurs in items2 with weight = 1, total weight = 1.
Therefore, we return [[1,7],[2,4],[7,1]].
Constraints:
1 <= items1.length, items2.length <= 1000
items1[i].length == items2[i].length == 2
1 <= valuei, weighti <= 1000
Each valuei in items1 is unique.
Each valuei in items2 is unique. | [ Python ] ✅✅ Simple Python Solution Using HashMap 🥳✌👍 | 393 | merge-similar-items | 0.753 | ASHOK_KUMAR_MEGHVANSHI | Easy | 32,354 | 2,363 |
count number of bad pairs | class Solution:
def countBadPairs(self, nums: List[int]) -> int:
nums_len = len(nums)
count_dict = dict()
for i in range(nums_len):
nums[i] -= i
if nums[i] not in count_dict:
count_dict[nums[i]] = 0
count_dict[nums[i]] += 1
count = 0
for key in count_dict:
count += math.comb(count_dict[key], 2)
return math.comb(nums_len, 2) - count | https://leetcode.com/problems/count-number-of-bad-pairs/discuss/2388687/Python-oror-Detailed-Explanation-oror-Faster-Than-100-oror-Less-than-100-oror-Simple-oror-MATH | 32 | You are given a 0-indexed integer array nums. A pair of indices (i, j) is a bad pair if i < j and j - i != nums[j] - nums[i].
Return the total number of bad pairs in nums.
Example 1:
Input: nums = [4,1,3,3]
Output: 5
Explanation: The pair (0, 1) is a bad pair since 1 - 0 != 1 - 4.
The pair (0, 2) is a bad pair since 2 - 0 != 3 - 4, 2 != -1.
The pair (0, 3) is a bad pair since 3 - 0 != 3 - 4, 3 != -1.
The pair (1, 2) is a bad pair since 2 - 1 != 3 - 1, 1 != 2.
The pair (2, 3) is a bad pair since 3 - 2 != 3 - 3, 1 != 0.
There are a total of 5 bad pairs, so we return 5.
Example 2:
Input: nums = [1,2,3,4,5]
Output: 0
Explanation: There are no bad pairs.
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 109 | 🔥 Python || Detailed Explanation ✅ || Faster Than 100% ✅|| Less than 100% ✅ || Simple || MATH | 648 | count-number-of-bad-pairs | 0.408 | wingskh | Medium | 32,380 | 2,364 |
task scheduler ii | class Solution:
def taskSchedulerII(self, tasks: List[int], space: int) -> int:
ans = 0
hashset = {}
n = len(tasks)
for x in set(tasks):
hashset[x] = 0
i = 0
while i <= n - 1:
flag = ans - hashset[tasks[i]]
if flag >= 0:
ans += 1
hashset[tasks[i]] = ans + space
i += 1
else:
ans += -flag
return ans | https://leetcode.com/problems/task-scheduler-ii/discuss/2388355/Python-oror-Easy-Approach | 2 | You are given a 0-indexed array of positive integers tasks, representing tasks that need to be completed in order, where tasks[i] represents the type of the ith task.
You are also given a positive integer space, which represents the minimum number of days that must pass after the completion of a task before another task of the same type can be performed.
Each day, until all tasks have been completed, you must either:
Complete the next task from tasks, or
Take a break.
Return the minimum number of days needed to complete all tasks.
Example 1:
Input: tasks = [1,2,1,2,3,1], space = 3
Output: 9
Explanation:
One way to complete all tasks in 9 days is as follows:
Day 1: Complete the 0th task.
Day 2: Complete the 1st task.
Day 3: Take a break.
Day 4: Take a break.
Day 5: Complete the 2nd task.
Day 6: Complete the 3rd task.
Day 7: Take a break.
Day 8: Complete the 4th task.
Day 9: Complete the 5th task.
It can be shown that the tasks cannot be completed in less than 9 days.
Example 2:
Input: tasks = [5,8,8,5], space = 2
Output: 6
Explanation:
One way to complete all tasks in 6 days is as follows:
Day 1: Complete the 0th task.
Day 2: Complete the 1st task.
Day 3: Take a break.
Day 4: Take a break.
Day 5: Complete the 2nd task.
Day 6: Complete the 3rd task.
It can be shown that the tasks cannot be completed in less than 6 days.
Constraints:
1 <= tasks.length <= 105
1 <= tasks[i] <= 109
1 <= space <= tasks.length | ✅Python || Easy Approach | 75 | task-scheduler-ii | 0.462 | chuhonghao01 | Medium | 32,391 | 2,365 |
minimum replacements to sort the array | class Solution:
def minimumReplacement(self, nums: List[int]) -> int:
n = len(nums)
k = nums[n - 1]
ans = 0
for i in reversed(range(n - 1)):
if nums[i] > k:
l = nums[i] / k
if l == int(l):
ans += int(l) - 1
k = nums[i] / int(l)
else:
ans += int(l)
k = int(nums[i] / (int(l) + 1))
else:
k = nums[i]
return ans | https://leetcode.com/problems/minimum-replacements-to-sort-the-array/discuss/2388550/Python-oror-One-reversed-pass-oror-Easy-Approaches | 2 | 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 number of operations to make an array that is sorted in non-decreasing order.
Example 1:
Input: nums = [3,9,3]
Output: 2
Explanation: Here are the steps to sort the array in non-decreasing order:
- From [3,9,3], replace the 9 with 3 and 6 so the array becomes [3,3,6,3]
- From [3,3,6,3], replace the 6 with 3 and 3 so the array becomes [3,3,3,3,3]
There are 2 steps to sort the array in non-decreasing order. Therefore, we return 2.
Example 2:
Input: nums = [1,2,3,4,5]
Output: 0
Explanation: The array is already in non-decreasing order. Therefore, we return 0.
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 109 | ✅Python || One reversed pass || Easy Approaches | 84 | minimum-replacements-to-sort-the-array | 0.399 | chuhonghao01 | Hard | 32,402 | 2,366 |
number of arithmetic triplets | class Solution:
def arithmeticTriplets(self, nums: List[int], diff: int) -> int:
ans = 0
n = len(nums)
for i in range(n):
if nums[i] + diff in nums and nums[i] + 2 * diff in nums:
ans += 1
return ans | https://leetcode.com/problems/number-of-arithmetic-triplets/discuss/2395275/Python-oror-Easy-Approach | 19 | You are given a 0-indexed, strictly increasing integer array nums and a positive integer diff. A triplet (i, j, k) is an arithmetic triplet if the following conditions are met:
i < j < k,
nums[j] - nums[i] == diff, and
nums[k] - nums[j] == diff.
Return the number of unique arithmetic triplets.
Example 1:
Input: nums = [0,1,4,6,7,10], diff = 3
Output: 2
Explanation:
(1, 2, 4) is an arithmetic triplet because both 7 - 4 == 3 and 4 - 1 == 3.
(2, 4, 5) is an arithmetic triplet because both 10 - 7 == 3 and 7 - 4 == 3.
Example 2:
Input: nums = [4,5,6,7,8,9], diff = 2
Output: 2
Explanation:
(0, 2, 4) is an arithmetic triplet because both 8 - 6 == 2 and 6 - 4 == 2.
(1, 3, 5) is an arithmetic triplet because both 9 - 7 == 2 and 7 - 5 == 2.
Constraints:
3 <= nums.length <= 200
0 <= nums[i] <= 200
1 <= diff <= 50
nums is strictly increasing. | ✅Python || Easy Approach | 1,200 | number-of-arithmetic-triplets | 0.837 | chuhonghao01 | Easy | 32,409 | 2,367 |
reachable nodes with restrictions | class Solution:
def reachableNodes(self, n: int, edges: List[List[int]], restricted: List[int]) -> int:
restrictedSet = set(restricted)
uf = UnionFindSet(n)
for edge in edges:
if edge[0] in restrictedSet or edge[1] in restrictedSet:
continue
else:
uf.union(edge[0], edge[1])
ans = 1
rootNode = uf.find(0)
for i in range(1, n):
if uf.find(i) == rootNode:
ans += 1
return ans
class UnionFindSet:
def __init__(self, size):
self.root = [i for i in range(size)]
# Use a rank array to record the height of each vertex, i.e., the "rank" of each vertex.
# The initial "rank" of each vertex is 1, because each of them is
# a standalone vertex with no connection to other vertices.
self.rank = [1] * size
# The find function here is the same as that in the disjoint set with path compression.
def find(self, x):
if x == self.root[x]:
return x
self.root[x] = self.find(self.root[x])
return self.root[x]
# The union function with union by rank
def union(self, x, y):
rootX = self.find(x)
rootY = self.find(y)
if rootX != rootY:
if self.rank[rootX] > self.rank[rootY]:
self.root[rootY] = rootX
elif self.rank[rootX] < self.rank[rootY]:
self.root[rootX] = rootY
else:
self.root[rootY] = rootX | https://leetcode.com/problems/reachable-nodes-with-restrictions/discuss/2395280/Python-oror-Graph-oror-UnionFind-oror-Easy-Approach | 3 | There is an undirected tree with n nodes labeled from 0 to n - 1 and n - 1 edges.
You are given a 2D integer array edges of length n - 1 where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree. You are also given an integer array restricted which represents restricted nodes.
Return the maximum number of nodes you can reach from node 0 without visiting a restricted node.
Note that node 0 will not be a restricted node.
Example 1:
Input: n = 7, edges = [[0,1],[1,2],[3,1],[4,0],[0,5],[5,6]], restricted = [4,5]
Output: 4
Explanation: The diagram above shows the tree.
We have that [0,1,2,3] are the only nodes that can be reached from node 0 without visiting a restricted node.
Example 2:
Input: n = 7, edges = [[0,1],[0,2],[0,5],[0,4],[3,2],[6,5]], restricted = [4,2,1]
Output: 3
Explanation: The diagram above shows the tree.
We have that [0,5,6] are the only nodes that can be reached from node 0 without visiting a restricted node.
Constraints:
2 <= n <= 105
edges.length == n - 1
edges[i].length == 2
0 <= ai, bi < n
ai != bi
edges represents a valid tree.
1 <= restricted.length < n
1 <= restricted[i] < n
All the values of restricted are unique. | ✅Python || Graph || UnionFind || Easy Approach | 152 | reachable-nodes-with-restrictions | 0.574 | chuhonghao01 | Medium | 32,438 | 2,368 |
check if there is a valid partition for the array | class Solution:
def validPartition(self, nums: List[int]) -> bool:
idxs = defaultdict(list)
n = len(nums)
#Find all doubles
for idx in range(1, n):
if nums[idx] == nums[idx - 1]:
idxs[idx - 1].append(idx + 1)
#Find all triples
for idx in range(2, n):
if nums[idx] == nums[idx - 1] == nums[idx - 2]:
idxs[idx - 2].append(idx + 1)
#Find all triple increments
for idx in range(2, n):
if nums[idx] == nums[idx - 1] + 1 == nums[idx - 2] + 2:
idxs[idx - 2].append(idx + 1)
#DFS
seen = set()
stack = [0]
while stack:
node = stack.pop()
if node not in seen:
if node == n:
return True
seen.add(node)
for adj in idxs[node]:
if adj not in seen:
stack.append(adj)
return False | https://leetcode.com/problems/check-if-there-is-a-valid-partition-for-the-array/discuss/2390552/Python3-Iterative-DFS | 2 | You are given a 0-indexed integer array nums. You have to partition the array into one or more contiguous subarrays.
We call a partition of the array valid if each of the obtained subarrays satisfies one of the following conditions:
The subarray consists of exactly 2, equal elements. For example, the subarray [2,2] is good.
The subarray consists of exactly 3, equal elements. For example, the subarray [4,4,4] is good.
The subarray consists of exactly 3 consecutive increasing elements, that is, the difference between adjacent elements is 1. For example, the subarray [3,4,5] is good, but the subarray [1,3,5] is not.
Return true if the array has at least one valid partition. Otherwise, return false.
Example 1:
Input: nums = [4,4,4,5,6]
Output: true
Explanation: The array can be partitioned into the subarrays [4,4] and [4,5,6].
This partition is valid, so we return true.
Example 2:
Input: nums = [1,1,1,2]
Output: false
Explanation: There is no valid partition for this array.
Constraints:
2 <= nums.length <= 105
1 <= nums[i] <= 106 | [Python3] Iterative DFS | 106 | check-if-there-is-a-valid-partition-for-the-array | 0.401 | 0xRoxas | Medium | 32,454 | 2,369 |
longest ideal subsequence | class Solution:
def longestIdealString(self, s: str, k: int) -> int:
dp = [0] * 26
for ch in s:
i = ord(ch) - ord("a")
dp[i] = 1 + max(dp[max(0, i - k) : min(26, i + k + 1)])
return max(dp) | https://leetcode.com/problems/longest-ideal-subsequence/discuss/2390471/DP | 34 | You are given a string s consisting of lowercase letters and an integer k. We call a string t ideal if the following conditions are satisfied:
t is a subsequence of the string s.
The absolute difference in the alphabet order of every two adjacent letters in t is less than or equal to k.
Return the length of the longest ideal string.
A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.
Note that the alphabet order is not cyclic. For example, the absolute difference in the alphabet order of 'a' and 'z' is 25, not 1.
Example 1:
Input: s = "acfgbd", k = 2
Output: 4
Explanation: The longest ideal string is "acbd". The length of this string is 4, so 4 is returned.
Note that "acfgbd" is not ideal because 'c' and 'f' have a difference of 3 in alphabet order.
Example 2:
Input: s = "abcd", k = 3
Output: 4
Explanation: The longest ideal string is "abcd". The length of this string is 4, so 4 is returned.
Constraints:
1 <= s.length <= 105
0 <= k <= 25
s consists of lowercase English letters. | DP | 2,300 | longest-ideal-subsequence | 0.379 | votrubac | Medium | 32,461 | 2,370 |
largest local values in a matrix | class Solution:
def largestLocal(self, grid: List[List[int]]) -> List[List[int]]:
n = len(grid)
ans = [[0]*(n-2) for _ in range(n-2)]
for i in range(n-2):
for j in range(n-2):
ans[i][j] = max(grid[ii][jj] for ii in range(i, i+3) for jj in range(j, j+3))
return ans | https://leetcode.com/problems/largest-local-values-in-a-matrix/discuss/2422191/Python3-simulation | 14 | You are given an n x n integer matrix grid.
Generate an integer matrix maxLocal of size (n - 2) x (n - 2) such that:
maxLocal[i][j] is equal to the largest value of the 3 x 3 matrix in grid centered around row i + 1 and column j + 1.
In other words, we want to find the largest value in every contiguous 3 x 3 matrix in grid.
Return the generated matrix.
Example 1:
Input: grid = [[9,9,8,1],[5,6,2,6],[8,2,6,4],[6,2,2,2]]
Output: [[9,9],[8,6]]
Explanation: The diagram above shows the original matrix and the generated matrix.
Notice that each value in the generated matrix corresponds to the largest value of a contiguous 3 x 3 matrix in grid.
Example 2:
Input: grid = [[1,1,1,1,1],[1,1,1,1,1],[1,1,2,1,1],[1,1,1,1,1],[1,1,1,1,1]]
Output: [[2,2,2],[2,2,2],[2,2,2]]
Explanation: Notice that the 2 is contained within every contiguous 3 x 3 matrix in grid.
Constraints:
n == grid.length == grid[i].length
3 <= n <= 100
1 <= grid[i][j] <= 100 | [Python3] simulation | 1,200 | largest-local-values-in-a-matrix | 0.839 | ye15 | Easy | 32,470 | 2,373 |
node with highest edge score | class Solution:
def edgeScore(self, edges: List[int]) -> int:
n = len(edges)
cnt = defaultdict(int)
ans = 0
// we have the key stores the node edges[i], and the value indicates the edge score.
for i in range(n):
cnt[edges[i]] += i
m = max(cnt.values())
// In the second iteration, i is also the index of the node. So the first one meets == m, is the smallest index.
for i in range(n):
if cnt[i] == m:
ans = i
break
return ans | https://leetcode.com/problems/node-with-highest-edge-score/discuss/2422372/Python-oror-Easy-Approach-oror-Hashmap | 4 | You are given a directed graph with n nodes labeled from 0 to n - 1, where each node has exactly one outgoing edge.
The graph is represented by a given 0-indexed integer array edges of length n, where edges[i] indicates that there is a directed edge from node i to node edges[i].
The edge score of a node i is defined as the sum of the labels of all the nodes that have an edge pointing to i.
Return the node with the highest edge score. If multiple nodes have the same edge score, return the node with the smallest index.
Example 1:
Input: edges = [1,0,0,0,0,7,7,5]
Output: 7
Explanation:
- The nodes 1, 2, 3 and 4 have an edge pointing to node 0. The edge score of node 0 is 1 + 2 + 3 + 4 = 10.
- The node 0 has an edge pointing to node 1. The edge score of node 1 is 0.
- The node 7 has an edge pointing to node 5. The edge score of node 5 is 7.
- The nodes 5 and 6 have an edge pointing to node 7. The edge score of node 7 is 5 + 6 = 11.
Node 7 has the highest edge score so return 7.
Example 2:
Input: edges = [2,0,0,2]
Output: 0
Explanation:
- The nodes 1 and 2 have an edge pointing to node 0. The edge score of node 0 is 1 + 2 = 3.
- The nodes 0 and 3 have an edge pointing to node 2. The edge score of node 2 is 0 + 3 = 3.
Nodes 0 and 2 both have an edge score of 3. Since node 0 has a smaller index, we return 0.
Constraints:
n == edges.length
2 <= n <= 105
0 <= edges[i] < n
edges[i] != i | ✅Python || Easy Approach || Hashmap | 226 | node-with-highest-edge-score | 0.462 | chuhonghao01 | Medium | 32,500 | 2,374 |
construct smallest number from di string | class Solution:
def smallestNumber(self, pattern: str) -> str:
ans = [1]
for ch in pattern:
if ch == 'I':
m = ans[-1]+1
while m in ans: m += 1
ans.append(m)
else:
ans.append(ans[-1])
for i in range(len(ans)-1, 0, -1):
if ans[i-1] == ans[i]: ans[i-1] += 1
return ''.join(map(str, ans)) | https://leetcode.com/problems/construct-smallest-number-from-di-string/discuss/2422249/Python3-greedy | 22 | You are given a 0-indexed string pattern of length n consisting of the characters 'I' meaning increasing and 'D' meaning decreasing.
A 0-indexed string num of length n + 1 is created using the following conditions:
num consists of the digits '1' to '9', where each digit is used at most once.
If pattern[i] == 'I', then num[i] < num[i + 1].
If pattern[i] == 'D', then num[i] > num[i + 1].
Return the lexicographically smallest possible string num that meets the conditions.
Example 1:
Input: pattern = "IIIDIDDD"
Output: "123549876"
Explanation:
At indices 0, 1, 2, and 4 we must have that num[i] < num[i+1].
At indices 3, 5, 6, and 7 we must have that num[i] > num[i+1].
Some possible values of num are "245639871", "135749862", and "123849765".
It can be proven that "123549876" is the smallest possible num that meets the conditions.
Note that "123414321" is not possible because the digit '1' is used more than once.
Example 2:
Input: pattern = "DDD"
Output: "4321"
Explanation:
Some possible values of num are "9876", "7321", and "8742".
It can be proven that "4321" is the smallest possible num that meets the conditions.
Constraints:
1 <= pattern.length <= 8
pattern consists of only the letters 'I' and 'D'. | [Python3] greedy | 994 | construct-smallest-number-from-di-string | 0.739 | ye15 | Medium | 32,515 | 2,375 |
count special integers | class Solution:
def countSpecialNumbers(self, n: int) -> int:
vals = list(map(int, str(n)))
@cache
def fn(i, m, on):
"""Return count at index i with mask m and profile flag (True/False)"""
ans = 0
if i == len(vals): return 1
for v in range(vals[i] if on else 10 ):
if m & 1<<v == 0:
if m or v: ans += fn(i+1, m ^ 1<<v, False)
else: ans += fn(i+1, m, False)
if on and m & 1<<vals[i] == 0: ans += fn(i+1, m ^ 1<<vals[i], True)
return ans
return fn(0, 0, True)-1 | https://leetcode.com/problems/count-special-integers/discuss/2422258/Python3-dp | 5 | We call a positive integer special if all of its digits are distinct.
Given a positive integer n, return the number of special integers that belong to the interval [1, n].
Example 1:
Input: n = 20
Output: 19
Explanation: All the integers from 1 to 20, except 11, are special. Thus, there are 19 special integers.
Example 2:
Input: n = 5
Output: 5
Explanation: All the integers from 1 to 5 are special.
Example 3:
Input: n = 135
Output: 110
Explanation: There are 110 integers from 1 to 135 that are special.
Some of the integers that are not special are: 22, 114, and 131.
Constraints:
1 <= n <= 2 * 109 | [Python3] dp | 466 | count-special-integers | 0.363 | ye15 | Hard | 32,533 | 2,376 |
minimum recolors to get k consecutive black blocks | class Solution:
def minimumRecolors(self, blocks: str, k: int) -> int:
ans = 0
res = 0
for i in range(len(blocks) - k + 1):
res = blocks.count('B', i, i + k)
ans = max(res, ans)
ans = k - ans
return ans | https://leetcode.com/problems/minimum-recolors-to-get-k-consecutive-black-blocks/discuss/2454458/Python-oror-Easy-Approach-oror-Sliding-Window-oror-Count | 3 | You are given a 0-indexed string blocks of length n, where blocks[i] is either 'W' or 'B', representing the color of the ith block. The characters 'W' and 'B' denote the colors white and black, respectively.
You are also given an integer k, which is the desired number of consecutive black blocks.
In one operation, you can recolor a white block such that it becomes a black block.
Return the minimum number of operations needed such that there is at least one occurrence of k consecutive black blocks.
Example 1:
Input: blocks = "WBBWWBBWBW", k = 7
Output: 3
Explanation:
One way to achieve 7 consecutive black blocks is to recolor the 0th, 3rd, and 4th blocks
so that blocks = "BBBBBBBWBW".
It can be shown that there is no way to achieve 7 consecutive black blocks in less than 3 operations.
Therefore, we return 3.
Example 2:
Input: blocks = "WBWBBBW", k = 2
Output: 0
Explanation:
No changes need to be made, since 2 consecutive black blocks already exist.
Therefore, we return 0.
Constraints:
n == blocks.length
1 <= n <= 100
blocks[i] is either 'W' or 'B'.
1 <= k <= n | ✅Python || Easy Approach || Sliding Window || Count | 318 | minimum-recolors-to-get-k-consecutive-black-blocks | 0.568 | chuhonghao01 | Easy | 32,534 | 2,379 |
time needed to rearrange a binary string | class Solution:
def secondsToRemoveOccurrences(self, s: str) -> int:
ans = prefix = prev = 0
for i, ch in enumerate(s):
if ch == '1':
ans = max(prev, i - prefix)
prefix += 1
if ans: prev = ans+1
return ans | https://leetcode.com/problems/time-needed-to-rearrange-a-binary-string/discuss/2454195/Python3-O(N)-dp-approach | 49 | You are given a binary string s. In one second, all occurrences of "01" are simultaneously replaced with "10". This process repeats until no occurrences of "01" exist.
Return the number of seconds needed to complete this process.
Example 1:
Input: s = "0110101"
Output: 4
Explanation:
After one second, s becomes "1011010".
After another second, s becomes "1101100".
After the third second, s becomes "1110100".
After the fourth second, s becomes "1111000".
No occurrence of "01" exists any longer, and the process needed 4 seconds to complete,
so we return 4.
Example 2:
Input: s = "11100"
Output: 0
Explanation:
No occurrence of "01" exists in s, and the processes needed 0 seconds to complete,
so we return 0.
Constraints:
1 <= s.length <= 1000
s[i] is either '0' or '1'.
Follow up:
Can you solve this problem in O(n) time complexity? | [Python3] O(N) dp approach | 2,200 | time-needed-to-rearrange-a-binary-string | 0.482 | ye15 | Medium | 32,566 | 2,380 |
shifting letters ii | class Solution:
def shiftingLetters(self, s: str, shifts: List[List[int]]) -> str:
cum_shifts = [0 for _ in range(len(s)+1)]
for st, end, d in shifts:
if d == 0:
cum_shifts[st] -= 1
cum_shifts[end+1] += 1
else:
cum_shifts[st] += 1
cum_shifts[end+1] -= 1
cum_sum = 0
for i in range(len(s)):
cum_sum += cum_shifts[i]
new_code = (((ord(s[i]) + cum_sum) - 97) % 26) + 97
s = s[:i] + chr(new_code) + s[i+1:]
return s | https://leetcode.com/problems/shifting-letters-ii/discuss/2454404/Python-Cumulative-Sum-oror-Easy-Solution | 15 | You are given a string s of lowercase English letters and a 2D integer array shifts where shifts[i] = [starti, endi, directioni]. For every i, shift the characters in s from the index starti to the index endi (inclusive) forward if directioni = 1, or shift the characters backward if directioni = 0.
Shifting a character forward means replacing it with the next letter in the alphabet (wrapping around so that 'z' becomes 'a'). Similarly, shifting a character backward means replacing it with the previous letter in the alphabet (wrapping around so that 'a' becomes 'z').
Return the final string after all such shifts to s are applied.
Example 1:
Input: s = "abc", shifts = [[0,1,0],[1,2,1],[0,2,1]]
Output: "ace"
Explanation: Firstly, shift the characters from index 0 to index 1 backward. Now s = "zac".
Secondly, shift the characters from index 1 to index 2 forward. Now s = "zbd".
Finally, shift the characters from index 0 to index 2 forward. Now s = "ace".
Example 2:
Input: s = "dztz", shifts = [[0,0,0],[1,1,1]]
Output: "catz"
Explanation: Firstly, shift the characters from index 0 to index 0 backward. Now s = "cztz".
Finally, shift the characters from index 1 to index 1 forward. Now s = "catz".
Constraints:
1 <= s.length, shifts.length <= 5 * 104
shifts[i].length == 3
0 <= starti <= endi < s.length
0 <= directioni <= 1
s consists of lowercase English letters. | ✅ Python Cumulative Sum || Easy Solution | 850 | shifting-letters-ii | 0.342 | idntk | Medium | 32,578 | 2,381 |
maximum segment sum after removals | class Solution:
def maximumSegmentSum(self, nums: List[int], removeQueries: List[int]) -> List[int]:
mp, cur, res = {}, 0, []
for q in reversed(removeQueries[1:]):
mp[q] = (nums[q], 1)
rv, rLen = mp.get(q+1, (0, 0))
lv, lLen = mp.get(q-1, (0, 0))
total = nums[q] + rv + lv
mp[q+rLen] = (total, lLen + rLen + 1)
mp[q-lLen] = (total, lLen + rLen + 1)
cur = max(cur, total)
res.append(cur)
return res[::-1] + [0] | https://leetcode.com/problems/maximum-segment-sum-after-removals/discuss/2454397/Do-it-backwards-O(N) | 29 | You are given two 0-indexed integer arrays nums and removeQueries, both of length n. For the ith query, the element in nums at the index removeQueries[i] is removed, splitting nums into different segments.
A segment is a contiguous sequence of positive integers in nums. A segment sum is the sum of every element in a segment.
Return an integer array answer, of length n, where answer[i] is the maximum segment sum after applying the ith removal.
Note: The same index will not be removed more than once.
Example 1:
Input: nums = [1,2,5,6,1], removeQueries = [0,3,2,4,1]
Output: [14,7,2,2,0]
Explanation: Using 0 to indicate a removed element, the answer is as follows:
Query 1: Remove the 0th element, nums becomes [0,2,5,6,1] and the maximum segment sum is 14 for segment [2,5,6,1].
Query 2: Remove the 3rd element, nums becomes [0,2,5,0,1] and the maximum segment sum is 7 for segment [2,5].
Query 3: Remove the 2nd element, nums becomes [0,2,0,0,1] and the maximum segment sum is 2 for segment [2].
Query 4: Remove the 4th element, nums becomes [0,2,0,0,0] and the maximum segment sum is 2 for segment [2].
Query 5: Remove the 1st element, nums becomes [0,0,0,0,0] and the maximum segment sum is 0, since there are no segments.
Finally, we return [14,7,2,2,0].
Example 2:
Input: nums = [3,2,11,1], removeQueries = [3,2,1,0]
Output: [16,5,3,0]
Explanation: Using 0 to indicate a removed element, the answer is as follows:
Query 1: Remove the 3rd element, nums becomes [3,2,11,0] and the maximum segment sum is 16 for segment [3,2,11].
Query 2: Remove the 2nd element, nums becomes [3,2,0,0] and the maximum segment sum is 5 for segment [3,2].
Query 3: Remove the 1st element, nums becomes [3,0,0,0] and the maximum segment sum is 3 for segment [3].
Query 4: Remove the 0th element, nums becomes [0,0,0,0] and the maximum segment sum is 0, since there are no segments.
Finally, we return [16,5,3,0].
Constraints:
n == nums.length == removeQueries.length
1 <= n <= 105
1 <= nums[i] <= 109
0 <= removeQueries[i] < n
All the values of removeQueries are unique. | Do it backwards O(N) | 1,100 | maximum-segment-sum-after-removals | 0.476 | user9591 | Hard | 32,591 | 2,382 |
minimum hours of training to win a competition | class Solution:
def minNumberOfHours(self, initialEnergy: int, initialExperience: int, energy: List[int], experience: List[int]) -> int:
ans = 0
n = len(energy)
for i in range(n):
while initialEnergy <= energy[i] or initialExperience <= experience[i]:
if initialEnergy <= energy[i]:
initialEnergy += 1
ans += 1
if initialExperience <= experience[i]:
initialExperience += 1
ans += 1
initialEnergy -= energy[i]
initialExperience += experience[i]
return ans | https://leetcode.com/problems/minimum-hours-of-training-to-win-a-competition/discuss/2456759/Python-oror-Easy-Approach | 6 | You are entering a competition, and are given two positive integers initialEnergy and initialExperience denoting your initial energy and initial experience respectively.
You are also given two 0-indexed integer arrays energy and experience, both of length n.
You will face n opponents in order. The energy and experience of the ith opponent is denoted by energy[i] and experience[i] respectively. When you face an opponent, you need to have both strictly greater experience and energy to defeat them and move to the next opponent if available.
Defeating the ith opponent increases your experience by experience[i], but decreases your energy by energy[i].
Before starting the competition, you can train for some number of hours. After each hour of training, you can either choose to increase your initial experience by one, or increase your initial energy by one.
Return the minimum number of training hours required to defeat all n opponents.
Example 1:
Input: initialEnergy = 5, initialExperience = 3, energy = [1,4,3,2], experience = [2,6,3,1]
Output: 8
Explanation: You can increase your energy to 11 after 6 hours of training, and your experience to 5 after 2 hours of training.
You face the opponents in the following order:
- You have more energy and experience than the 0th opponent so you win.
Your energy becomes 11 - 1 = 10, and your experience becomes 5 + 2 = 7.
- You have more energy and experience than the 1st opponent so you win.
Your energy becomes 10 - 4 = 6, and your experience becomes 7 + 6 = 13.
- You have more energy and experience than the 2nd opponent so you win.
Your energy becomes 6 - 3 = 3, and your experience becomes 13 + 3 = 16.
- You have more energy and experience than the 3rd opponent so you win.
Your energy becomes 3 - 2 = 1, and your experience becomes 16 + 1 = 17.
You did a total of 6 + 2 = 8 hours of training before the competition, so we return 8.
It can be proven that no smaller answer exists.
Example 2:
Input: initialEnergy = 2, initialExperience = 4, energy = [1], experience = [3]
Output: 0
Explanation: You do not need any additional energy or experience to win the competition, so we return 0.
Constraints:
n == energy.length == experience.length
1 <= n <= 100
1 <= initialEnergy, initialExperience, energy[i], experience[i] <= 100 | ✅Python || Easy Approach | 460 | minimum-hours-of-training-to-win-a-competition | 0.41 | chuhonghao01 | Easy | 32,595 | 2,383 |
largest palindromic number | class Solution:
def largestPalindromic(self, num: str) -> str:
ans = []
b = [str(x) for x in range(9, -1, -1)]
from collections import defaultdict
a = defaultdict(int)
for x in num:
a[x] += 1
for x in b:
n = len(ans)
if n % 2 == 0:
if a[x] > 0:
ans = ans[:n // 2] + [x] * a[x] + ans[n // 2:]
else:
if x == '0':
if len(ans) != 1:
ans = ans[:n // 2] + [x] * (a[x] // 2) + [ans[n // 2]] + [x] * (a[x] // 2) + ans[n // 2 + 1:]
else:
if a[x] >= 2:
ans = ans[:n // 2] + [x] * (a[x] // 2) + [ans[n // 2]] + [x] * (a[x] // 2) + ans[n // 2 + 1:]
res = "".join(ans)
return str(int(res)) | https://leetcode.com/problems/largest-palindromic-number/discuss/2456725/Python-oror-Easy-Approach-oror-Hashmap | 4 | You are given a string num consisting of digits only.
Return the largest palindromic integer (in the form of a string) that can be formed using digits taken from num. It should not contain leading zeroes.
Notes:
You do not need to use all the digits of num, but you must use at least one digit.
The digits can be reordered.
Example 1:
Input: num = "444947137"
Output: "7449447"
Explanation:
Use the digits "4449477" from "444947137" to form the palindromic integer "7449447".
It can be shown that "7449447" is the largest palindromic integer that can be formed.
Example 2:
Input: num = "00009"
Output: "9"
Explanation:
It can be shown that "9" is the largest palindromic integer that can be formed.
Note that the integer returned should not contain leading zeroes.
Constraints:
1 <= num.length <= 105
num consists of digits. | ✅Python || Easy Approach || Hashmap | 178 | largest-palindromic-number | 0.306 | chuhonghao01 | Medium | 32,617 | 2,384 |
amount of time for binary tree to be infected | class Solution:
def amountOfTime(self, root: Optional[TreeNode], start: int) -> int:
graph = defaultdict(list)
stack = [(root, None)]
while stack:
n, p = stack.pop()
if p:
graph[p.val].append(n.val)
graph[n.val].append(p.val)
if n.left: stack.append((n.left, n))
if n.right: stack.append((n.right, n))
ans = -1
seen = {start}
queue = deque([start])
while queue:
for _ in range(len(queue)):
u = queue.popleft()
for v in graph[u]:
if v not in seen:
seen.add(v)
queue.append(v)
ans += 1
return ans | https://leetcode.com/problems/amount-of-time-for-binary-tree-to-be-infected/discuss/2456656/Python3-bfs | 33 | You are given the root of a binary tree with unique values, and an integer start. At minute 0, an infection starts from the node with value start.
Each minute, a node becomes infected if:
The node is currently uninfected.
The node is adjacent to an infected node.
Return the number of minutes needed for the entire tree to be infected.
Example 1:
Input: root = [1,5,3,null,4,10,6,9,2], start = 3
Output: 4
Explanation: The following nodes are infected during:
- Minute 0: Node 3
- Minute 1: Nodes 1, 10 and 6
- Minute 2: Node 5
- Minute 3: Node 4
- Minute 4: Nodes 9 and 2
It takes 4 minutes for the whole tree to be infected so we return 4.
Example 2:
Input: root = [1], start = 1
Output: 0
Explanation: At minute 0, the only node in the tree is infected so we return 0.
Constraints:
The number of nodes in the tree is in the range [1, 105].
1 <= Node.val <= 105
Each node has a unique value.
A node with a value of start exists in the tree. | [Python3] bfs | 1,400 | amount-of-time-for-binary-tree-to-be-infected | 0.562 | ye15 | Medium | 32,627 | 2,385 |
find the k sum of an array | class Solution:
def kSum(self, nums: List[int], k: int) -> int:
maxSum = sum([max(0, num) for num in nums])
absNums = sorted([abs(num) for num in nums])
maxHeap = [(-maxSum + absNums[0], 0)]
ans = [maxSum]
while len(ans) < k:
nextSum, i = heapq.heappop(maxHeap)
heapq.heappush(ans, -nextSum)
if i + 1 < len(absNums):
heapq.heappush(maxHeap, (nextSum - absNums[i] + absNums[i + 1], i + 1))
heapq.heappush(maxHeap, (nextSum + absNums[i + 1], i + 1))
return ans[0] | https://leetcode.com/problems/find-the-k-sum-of-an-array/discuss/2456716/Python3-HeapPriority-Queue-O(NlogN-%2B-klogk) | 82 | You are given an integer array nums and a positive integer k. You can choose any subsequence of the array and sum all of its elements together.
We define the K-Sum of the array as the kth largest subsequence sum that can be obtained (not necessarily distinct).
Return the K-Sum of the array.
A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
Note that the empty subsequence is considered to have a sum of 0.
Example 1:
Input: nums = [2,4,-2], k = 5
Output: 2
Explanation: All the possible subsequence sums that we can obtain are the following sorted in decreasing order:
- 6, 4, 4, 2, 2, 0, 0, -2.
The 5-Sum of the array is 2.
Example 2:
Input: nums = [1,-2,3,4,-10,12], k = 16
Output: 10
Explanation: The 16-Sum of the array is 10.
Constraints:
n == nums.length
1 <= n <= 105
-109 <= nums[i] <= 109
1 <= k <= min(2000, 2n) | [Python3] Heap/Priority Queue, O(NlogN + klogk) | 5,300 | find-the-k-sum-of-an-array | 0.377 | xil899 | Hard | 32,635 | 2,386 |
longest subsequence with limited sum | class Solution:
def answerQueries(self, nums: List[int], queries: List[int]) -> List[int]:
nums = list(accumulate(sorted(nums)))
return [bisect_right(nums, q) for q in queries] | https://leetcode.com/problems/longest-subsequence-with-limited-sum/discuss/2492737/Prefix-Sum | 9 | You are given an integer array nums of length n, and an integer array queries of length m.
Return an array answer of length m where answer[i] is the maximum size of a subsequence that you can take from nums such that the sum of its elements is less than or equal to queries[i].
A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
Example 1:
Input: nums = [4,5,2,1], queries = [3,10,21]
Output: [2,3,4]
Explanation: We answer the queries as follows:
- The subsequence [2,1] has a sum less than or equal to 3. It can be proven that 2 is the maximum size of such a subsequence, so answer[0] = 2.
- The subsequence [4,5,1] has a sum less than or equal to 10. It can be proven that 3 is the maximum size of such a subsequence, so answer[1] = 3.
- The subsequence [4,5,2,1] has a sum less than or equal to 21. It can be proven that 4 is the maximum size of such a subsequence, so answer[2] = 4.
Example 2:
Input: nums = [2,3,4,5], queries = [1]
Output: [0]
Explanation: The empty subsequence is the only subsequence that has a sum less than or equal to 1, so answer[0] = 0.
Constraints:
n == nums.length
m == queries.length
1 <= n, m <= 1000
1 <= nums[i], queries[i] <= 106 | Prefix Sum | 1,200 | longest-subsequence-with-limited-sum | 0.648 | votrubac | Easy | 32,638 | 2,389 |
removing stars from a string | class Solution:
def removeStars(self, s: str) -> str:
stack = []
for ch in s:
if ch == '*': stack.pop()
else: stack.append(ch)
return ''.join(stack) | https://leetcode.com/problems/removing-stars-from-a-string/discuss/2492763/Python3-stack | 3 | You are given a string s, which contains stars *.
In one operation, you can:
Choose a star in s.
Remove the closest non-star character to its left, as well as remove the star itself.
Return the string after all stars have been removed.
Note:
The input will be generated such that the operation is always possible.
It can be shown that the resulting string will always be unique.
Example 1:
Input: s = "leet**cod*e"
Output: "lecoe"
Explanation: Performing the removals from left to right:
- The closest character to the 1st star is 't' in "leet**cod*e". s becomes "lee*cod*e".
- The closest character to the 2nd star is 'e' in "lee*cod*e". s becomes "lecod*e".
- The closest character to the 3rd star is 'd' in "lecod*e". s becomes "lecoe".
There are no more stars, so we return "lecoe".
Example 2:
Input: s = "erase*****"
Output: ""
Explanation: The entire string is removed, so we return an empty string.
Constraints:
1 <= s.length <= 105
s consists of lowercase English letters and stars *.
The operation above can be performed on s. | [Python3] stack | 46 | removing-stars-from-a-string | 0.64 | ye15 | Medium | 32,655 | 2,390 |
minimum amount of time to collect garbage | class Solution:
def garbageCollection(self, garbage: List[str], travel: List[int]) -> int:
ans = sum(map(len, garbage))
prefix = list(accumulate(travel, initial=0))
for ch in "MPG":
ii = 0
for i, s in enumerate(garbage):
if ch in s: ii = i
ans += prefix[ii]
return ans | https://leetcode.com/problems/minimum-amount-of-time-to-collect-garbage/discuss/2492802/Python3-simulation | 4 | You are given a 0-indexed array of strings garbage where garbage[i] represents the assortment of garbage at the ith house. garbage[i] consists only of the characters 'M', 'P' and 'G' representing one unit of metal, paper and glass garbage respectively. Picking up one unit of any type of garbage takes 1 minute.
You are also given a 0-indexed integer array travel where travel[i] is the number of minutes needed to go from house i to house i + 1.
There are three garbage trucks in the city, each responsible for picking up one type of garbage. Each garbage truck starts at house 0 and must visit each house in order; however, they do not need to visit every house.
Only one garbage truck may be used at any given moment. While one truck is driving or picking up garbage, the other two trucks cannot do anything.
Return the minimum number of minutes needed to pick up all the garbage.
Example 1:
Input: garbage = ["G","P","GP","GG"], travel = [2,4,3]
Output: 21
Explanation:
The paper garbage truck:
1. Travels from house 0 to house 1
2. Collects the paper garbage at house 1
3. Travels from house 1 to house 2
4. Collects the paper garbage at house 2
Altogether, it takes 8 minutes to pick up all the paper garbage.
The glass garbage truck:
1. Collects the glass garbage at house 0
2. Travels from house 0 to house 1
3. Travels from house 1 to house 2
4. Collects the glass garbage at house 2
5. Travels from house 2 to house 3
6. Collects the glass garbage at house 3
Altogether, it takes 13 minutes to pick up all the glass garbage.
Since there is no metal garbage, we do not need to consider the metal garbage truck.
Therefore, it takes a total of 8 + 13 = 21 minutes to collect all the garbage.
Example 2:
Input: garbage = ["MMM","PGM","GP"], travel = [3,10]
Output: 37
Explanation:
The metal garbage truck takes 7 minutes to pick up all the metal garbage.
The paper garbage truck takes 15 minutes to pick up all the paper garbage.
The glass garbage truck takes 15 minutes to pick up all the glass garbage.
It takes a total of 7 + 15 + 15 = 37 minutes to collect all the garbage.
Constraints:
2 <= garbage.length <= 105
garbage[i] consists of only the letters 'M', 'P', and 'G'.
1 <= garbage[i].length <= 10
travel.length == garbage.length - 1
1 <= travel[i] <= 100 | [Python3] simulation | 48 | minimum-amount-of-time-to-collect-garbage | 0.851 | ye15 | Medium | 32,682 | 2,391 |
build a matrix with conditions | class Solution:
def buildMatrix(self, k: int, rowConditions: List[List[int]], colConditions: List[List[int]]) -> List[List[int]]:
def fn(cond):
"""Return topological sort"""
graph = [[] for _ in range(k)]
indeg = [0]*k
for u, v in cond:
graph[u-1].append(v-1)
indeg[v-1] += 1
queue = deque(u for u, x in enumerate(indeg) if x == 0)
ans = []
while queue:
u = queue.popleft()
ans.append(u+1)
for v in graph[u]:
indeg[v] -= 1
if indeg[v] == 0: queue.append(v)
return ans
row = fn(rowConditions)
col = fn(colConditions)
if len(row) < k or len(col) < k: return []
ans = [[0]*k for _ in range(k)]
row = {x : i for i, x in enumerate(row)}
col = {x : j for j, x in enumerate(col)}
for x in range(1, k+1): ans[row[x]][col[x]] = x
return ans | https://leetcode.com/problems/build-a-matrix-with-conditions/discuss/2492822/Python3-topological-sort | 12 | You are given a positive integer k. You are also given:
a 2D integer array rowConditions of size n where rowConditions[i] = [abovei, belowi], and
a 2D integer array colConditions of size m where colConditions[i] = [lefti, righti].
The two arrays contain integers from 1 to k.
You have to build a k x k matrix that contains each of the numbers from 1 to k exactly once. The remaining cells should have the value 0.
The matrix should also satisfy the following conditions:
The number abovei should appear in a row that is strictly above the row at which the number belowi appears for all i from 0 to n - 1.
The number lefti should appear in a column that is strictly left of the column at which the number righti appears for all i from 0 to m - 1.
Return any matrix that satisfies the conditions. If no answer exists, return an empty matrix.
Example 1:
Input: k = 3, rowConditions = [[1,2],[3,2]], colConditions = [[2,1],[3,2]]
Output: [[3,0,0],[0,0,1],[0,2,0]]
Explanation: The diagram above shows a valid example of a matrix that satisfies all the conditions.
The row conditions are the following:
- Number 1 is in row 1, and number 2 is in row 2, so 1 is above 2 in the matrix.
- Number 3 is in row 0, and number 2 is in row 2, so 3 is above 2 in the matrix.
The column conditions are the following:
- Number 2 is in column 1, and number 1 is in column 2, so 2 is left of 1 in the matrix.
- Number 3 is in column 0, and number 2 is in column 1, so 3 is left of 2 in the matrix.
Note that there may be multiple correct answers.
Example 2:
Input: k = 3, rowConditions = [[1,2],[2,3],[3,1],[2,3]], colConditions = [[2,1]]
Output: []
Explanation: From the first two conditions, 3 has to be below 1 but the third conditions needs 3 to be above 1 to be satisfied.
No matrix can satisfy all the conditions, so we return the empty matrix.
Constraints:
2 <= k <= 400
1 <= rowConditions.length, colConditions.length <= 104
rowConditions[i].length == colConditions[i].length == 2
1 <= abovei, belowi, lefti, righti <= k
abovei != belowi
lefti != righti | [Python3] topological sort | 339 | build-a-matrix-with-conditions | 0.592 | ye15 | Hard | 32,704 | 2,392 |
find subarrays with equal sum | class Solution:
def findSubarrays(self, nums: List[int]) -> bool:
"""
Bruteforce approch
"""
# for i in range(len(nums)-2):
# summ1 = nums[i] + nums[i+1]
# # for j in range(i+1,len(nums)):
# for j in range(i+1,len(nums)-1):
# summ = nums[j] + nums[j+1]
# if summ == summ1:
# return True
# return False
"""
Sliding Window
"""
one ,two = len(nums)-2,len(nums)-1 // at end of list
dic = {}
while one >= 0:
# print(one,two)
summ = nums[one] + nums[two]
if summ in dic:
return True // if already there then there is 2 pairs
else:
dic[summ] = 1 // add summ in of window in dictonary
one -=1
two -=1
return False | https://leetcode.com/problems/find-subarrays-with-equal-sum/discuss/2525818/Python-oror-Sliding-window-oror-Bruteforce | 4 | Given a 0-indexed integer array nums, determine whether there exist two subarrays of length 2 with equal sum. Note that the two subarrays must begin at different indices.
Return true if these subarrays exist, and false otherwise.
A subarray is a contiguous non-empty sequence of elements within an array.
Example 1:
Input: nums = [4,2,4]
Output: true
Explanation: The subarrays with elements [4,2] and [2,4] have the same sum of 6.
Example 2:
Input: nums = [1,2,3,4,5]
Output: false
Explanation: No two subarrays of size 2 have the same sum.
Example 3:
Input: nums = [0,0,0]
Output: true
Explanation: The subarrays [nums[0],nums[1]] and [nums[1],nums[2]] have the same sum of 0.
Note that even though the subarrays have the same content, the two subarrays are considered different because they are in different positions in the original array.
Constraints:
2 <= nums.length <= 1000
-109 <= nums[i] <= 109 | Python || Sliding window || Bruteforce | 85 | find-subarrays-with-equal-sum | 0.639 | 1md3nd | Easy | 32,713 | 2,395 |
strictly palindromic number | class Solution:
def isStrictlyPalindromic(self, n: int) -> bool:
def int2base(n,b):
r=""
while n>0:
r+=str(n%b)
n//=b
return int(r[-1::-1])
for i in range(2,n-1):
if int2base(n,i)!=n:
return False
return True | https://leetcode.com/problems/strictly-palindromic-number/discuss/2801453/Python-oror-95.34-Faster-oror-Easy-and-Actual-Solution-oror-O(n)-Solution | 2 | An integer n is strictly palindromic if, for every base b between 2 and n - 2 (inclusive), the string representation of the integer n in base b is palindromic.
Given an integer n, return true if n is strictly palindromic and false otherwise.
A string is palindromic if it reads the same forward and backward.
Example 1:
Input: n = 9
Output: false
Explanation: In base 2: 9 = 1001 (base 2), which is palindromic.
In base 3: 9 = 100 (base 3), which is not palindromic.
Therefore, 9 is not strictly palindromic so we return false.
Note that in bases 4, 5, 6, and 7, n = 9 is also not palindromic.
Example 2:
Input: n = 4
Output: false
Explanation: We only consider base 2: 4 = 100 (base 2), which is not palindromic.
Therefore, we return false.
Constraints:
4 <= n <= 105 | Python || 95.34% Faster || Easy and Actual Solution || O(n) Solution | 186 | strictly-palindromic-number | 0.877 | DareDevil_007 | Medium | 32,729 | 2,396 |
maximum rows covered by columns | class Solution:
def maximumRows(self, mat: List[List[int]], cols: int) -> int:
n,m = len(mat),len(mat[0])
ans = 0
def check(state,row,rowIncludedCount):
nonlocal ans
if row==n:
if sum(state)<=cols:
ans = max(ans,rowIncludedCount)
return
check(state[::],row+1,rowIncludedCount)
for j in range(m):
if mat[row][j]==1:
state[j] = 1
check(state,row+1,rowIncludedCount+1)
check([0]*m,0,0)
return ans | https://leetcode.com/problems/maximum-rows-covered-by-columns/discuss/2524746/Python-Simple-Solution | 4 | You are given a 0-indexed m x n binary matrix matrix and an integer numSelect, which denotes the number of distinct columns you must select from matrix.
Let us consider s = {c1, c2, ...., cnumSelect} as the set of columns selected by you. A row row is covered by s if:
For each cell matrix[row][col] (0 <= col <= n - 1) where matrix[row][col] == 1, col is present in s or,
No cell in row has a value of 1.
You need to choose numSelect columns such that the number of rows that are covered is maximized.
Return the maximum number of rows that can be covered by a set of numSelect columns.
Example 1:
Input: matrix = [[0,0,0],[1,0,1],[0,1,1],[0,0,1]], numSelect = 2
Output: 3
Explanation: One possible way to cover 3 rows is shown in the diagram above.
We choose s = {0, 2}.
- Row 0 is covered because it has no occurrences of 1.
- Row 1 is covered because the columns with value 1, i.e. 0 and 2 are present in s.
- Row 2 is not covered because matrix[2][1] == 1 but 1 is not present in s.
- Row 3 is covered because matrix[2][2] == 1 and 2 is present in s.
Thus, we can cover three rows.
Note that s = {1, 2} will also cover 3 rows, but it can be shown that no more than three rows can be covered.
Example 2:
Input: matrix = [[1],[0]], numSelect = 1
Output: 2
Explanation: Selecting the only column will result in both rows being covered since the entire matrix is selected.
Therefore, we return 2.
Constraints:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 12
matrix[i][j] is either 0 or 1.
1 <= numSelect <= n | Python Simple Solution | 431 | maximum-rows-covered-by-columns | 0.525 | RedHeadphone | Medium | 32,744 | 2,397 |
maximum number of robots within budget | class Solution:
def maximumRobots(self, chargeTimes: List[int], runningCosts: List[int], budget: int) -> int:
n=len(chargeTimes)
start=0
runningsum=0
max_consecutive=0
max_so_far=0
secondmax=0
for end in range(n):
runningsum+=runningCosts[end]
if max_so_far<=chargeTimes[end]:
secondmax=max_so_far
max_so_far=chargeTimes[end]
k=end-start+1
currentbudget=max_so_far+(k*runningsum)
if currentbudget>budget:
runningsum-=runningCosts[start]
max_so_far=secondmax if chargeTimes[start]==max_so_far else max_so_far
start+=1
max_consecutive=max(max_consecutive,end-start+1)
return max_consecutive | https://leetcode.com/problems/maximum-number-of-robots-within-budget/discuss/2526141/Python3-Intuition-Explained-or-Sliding-Window-or-Similar-Problems-Link | 1 | You have n robots. You are given two 0-indexed integer arrays, chargeTimes and runningCosts, both of length n. The ith robot costs chargeTimes[i] units to charge and costs runningCosts[i] units to run. You are also given an integer budget.
The total cost of running k chosen robots is equal to max(chargeTimes) + k * sum(runningCosts), where max(chargeTimes) is the largest charge cost among the k robots and sum(runningCosts) is the sum of running costs among the k robots.
Return the maximum number of consecutive robots you can run such that the total cost does not exceed budget.
Example 1:
Input: chargeTimes = [3,6,1,3,4], runningCosts = [2,1,3,4,5], budget = 25
Output: 3
Explanation:
It is possible to run all individual and consecutive pairs of robots within budget.
To obtain answer 3, consider the first 3 robots. The total cost will be max(3,6,1) + 3 * sum(2,1,3) = 6 + 3 * 6 = 24 which is less than 25.
It can be shown that it is not possible to run more than 3 consecutive robots within budget, so we return 3.
Example 2:
Input: chargeTimes = [11,12,19], runningCosts = [10,8,7], budget = 19
Output: 0
Explanation: No robot can be run that does not exceed the budget, so we return 0.
Constraints:
chargeTimes.length == runningCosts.length == n
1 <= n <= 5 * 104
1 <= chargeTimes[i], runningCosts[i] <= 105
1 <= budget <= 1015 | [Python3] Intuition Explained 🔥 | Sliding Window | Similar Problems Link 🚀 | 61 | maximum-number-of-robots-within-budget | 0.322 | glimloop | Hard | 32,755 | 2,398 |
check distances between same letters | class Solution: # Pretty much explains itself.
def checkDistances(self, s: str, distance: List[int]) -> bool:
d = defaultdict(list)
for i, ch in enumerate(s):
d[ch].append(i)
return all(b-a-1 == distance[ord(ch)-97] for ch, (a,b) in d.items()) | https://leetcode.com/problems/check-distances-between-same-letters/discuss/2531135/Python3-oror-3-lines-TM%3A-36ms13.8MB | 8 | You are given a 0-indexed string s consisting of only lowercase English letters, where each letter in s appears exactly twice. You are also given a 0-indexed integer array distance of length 26.
Each letter in the alphabet is numbered from 0 to 25 (i.e. 'a' -> 0, 'b' -> 1, 'c' -> 2, ... , 'z' -> 25).
In a well-spaced string, the number of letters between the two occurrences of the ith letter is distance[i]. If the ith letter does not appear in s, then distance[i] can be ignored.
Return true if s is a well-spaced string, otherwise return false.
Example 1:
Input: s = "abaccb", distance = [1,3,0,5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
Output: true
Explanation:
- 'a' appears at indices 0 and 2 so it satisfies distance[0] = 1.
- 'b' appears at indices 1 and 5 so it satisfies distance[1] = 3.
- 'c' appears at indices 3 and 4 so it satisfies distance[2] = 0.
Note that distance[3] = 5, but since 'd' does not appear in s, it can be ignored.
Return true because s is a well-spaced string.
Example 2:
Input: s = "aa", distance = [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
Output: false
Explanation:
- 'a' appears at indices 0 and 1 so there are zero letters between them.
Because distance[0] = 1, s is not a well-spaced string.
Constraints:
2 <= s.length <= 52
s consists only of lowercase English letters.
Each letter appears in s exactly twice.
distance.length == 26
0 <= distance[i] <= 50 | Python3 || 3 lines, T/M: 36ms/13.8MB | 596 | check-distances-between-same-letters | 0.704 | warrenruud | Easy | 32,763 | 2,399 |
number of ways to reach a position after exactly k steps | class Solution: # A few points on the problem:
# • The start and end is a "red herring." The answer to the problem
# depends only on the distance (dist = end-start) and k.
#
# • A little thought will convince one that theres no paths possible
# if k%2 != dist%2 or if abs(dist) > k.
# • The problem is equivalent to:
# Determine the count of distinct lists of length k with sum = dist
# and elements 1 and -1, in which the counts of 1s and -1s in each
# list differ by dist.
#
# • The count of the lists is equal to the number of ways the combination
# C((k, (dist+k)//2)). For example, if dist = 1 and k = 5. the count of 1s
#. is (5+1)//2 = 3, and C(5,3) = 10.
# (Note that if dist= -1 in this example, (5-1)//2 = 2, and C(5,2) = 10)
def numberOfWays(self, startPos: int, endPos: int, k: int) -> int:
dist = endPos-startPos
if k%2 != dist%2 or abs(dist) > k: return 0
return comb(k, (dist+k)//2) %1000000007 | https://leetcode.com/problems/number-of-ways-to-reach-a-position-after-exactly-k-steps/discuss/2554923/Python3-oror-3-lines-combs-w-explanation-oror-TM%3A-9692 | 3 | You are given two positive integers startPos and endPos. Initially, you are standing at position startPos on an infinite number line. With one step, you can move either one position to the left, or one position to the right.
Given a positive integer k, return the number of different ways to reach the position endPos starting from startPos, such that you perform exactly k steps. Since the answer may be very large, return it modulo 109 + 7.
Two ways are considered different if the order of the steps made is not exactly the same.
Note that the number line includes negative integers.
Example 1:
Input: startPos = 1, endPos = 2, k = 3
Output: 3
Explanation: We can reach position 2 from 1 in exactly 3 steps in three ways:
- 1 -> 2 -> 3 -> 2.
- 1 -> 2 -> 1 -> 2.
- 1 -> 0 -> 1 -> 2.
It can be proven that no other way is possible, so we return 3.
Example 2:
Input: startPos = 2, endPos = 5, k = 10
Output: 0
Explanation: It is impossible to reach position 5 from position 2 in exactly 10 steps.
Constraints:
1 <= startPos, endPos, k <= 1000 | Python3 || 3 lines, combs, w/ explanation || T/M: 96%/92% | 157 | number-of-ways-to-reach-a-position-after-exactly-k-steps | 0.323 | warrenruud | Medium | 32,781 | 2,400 |
longest nice subarray | class Solution:
def longestNiceSubarray(self, nums: List[int]) -> int:
maximum_length = 1
n = len(nums)
current_group = 0
left = 0
for right in range(n):
# If the number at the right point is safe to include, include it in the group and update the maximum length.
if nums[right] & current_group == 0:
current_group |=nums[right]
maximum_length = max(maximum_length, right - left + 1)
continue
# Shrink the window until the number at the right pointer is safe to include.
while left < right and nums[right] & current_group != 0:
current_group &= (~nums[left])
left += 1
# Include the number at the right pointer in the group.
current_group |= nums[right]
return maximum_length | https://leetcode.com/problems/longest-nice-subarray/discuss/2527285/Bit-Magic-with-Explanation-and-Complexities | 19 | You are given an array nums consisting of positive integers.
We call a subarray of nums nice if the bitwise AND of every pair of elements that are in different positions in the subarray is equal to 0.
Return the length of the longest nice subarray.
A subarray is a contiguous part of an array.
Note that subarrays of length 1 are always considered nice.
Example 1:
Input: nums = [1,3,8,48,10]
Output: 3
Explanation: The longest nice subarray is [3,8,48]. This subarray satisfies the conditions:
- 3 AND 8 = 0.
- 3 AND 48 = 0.
- 8 AND 48 = 0.
It can be proven that no longer nice subarray can be obtained, so we return 3.
Example 2:
Input: nums = [3,1,5,11,13]
Output: 1
Explanation: The length of the longest nice subarray is 1. Any subarray of length 1 can be chosen.
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 109 | Bit Magic with Explanation and Complexities | 488 | longest-nice-subarray | 0.48 | wickedmishra | Medium | 32,799 | 2,401 |
meeting rooms iii | class Solution:
def mostBooked(self, n: int, meetings: List[List[int]]) -> int:
meetings.sort() # make sure start times are sorted!!
meetingCount = [0 for _ in range(n)]
availableRooms = list(range(n)); heapify(availableRooms)
occupiedRooms = []
for start, end in meetings:
while occupiedRooms and start >= occupiedRooms[0][0]:
heappush(availableRooms, heappop(occupiedRooms)[1]) # frees room and makes it available
if availableRooms:
roomNumber = heappop(availableRooms) # assigns next available room
else:
freedEnd, roomNumber = heappop(occupiedRooms) # waits until the next room that would be available gets free
end += freedEnd - start
heappush(occupiedRooms, (end,roomNumber)) # make note that the ruom is occupied and when the assigned meeting ends
meetingCount[roomNumber] += 1 # update meeting counter
return sorted([(count, i) for i, count in enumerate(meetingCount)], key = lambda x: (-x[0], x[1]))[0][1] # find room with most meetings | https://leetcode.com/problems/meeting-rooms-iii/discuss/2527343/Python-or-More-heap-extravaganza | 1 | You are given an integer n. There are n rooms numbered from 0 to n - 1.
You are given a 2D integer array meetings where meetings[i] = [starti, endi] means that a meeting will be held during the half-closed time interval [starti, endi). All the values of starti are unique.
Meetings are allocated to rooms in the following manner:
Each meeting will take place in the unused room with the lowest number.
If there are no available rooms, the meeting will be delayed until a room becomes free. The delayed meeting should have the same duration as the original meeting.
When a room becomes unused, meetings that have an earlier original start time should be given the room.
Return the number of the room that held the most meetings. If there are multiple rooms, return the room with the lowest number.
A half-closed interval [a, b) is the interval between a and b including a and not including b.
Example 1:
Input: n = 2, meetings = [[0,10],[1,5],[2,7],[3,4]]
Output: 0
Explanation:
- At time 0, both rooms are not being used. The first meeting starts in room 0.
- At time 1, only room 1 is not being used. The second meeting starts in room 1.
- At time 2, both rooms are being used. The third meeting is delayed.
- At time 3, both rooms are being used. The fourth meeting is delayed.
- At time 5, the meeting in room 1 finishes. The third meeting starts in room 1 for the time period [5,10).
- At time 10, the meetings in both rooms finish. The fourth meeting starts in room 0 for the time period [10,11).
Both rooms 0 and 1 held 2 meetings, so we return 0.
Example 2:
Input: n = 3, meetings = [[1,20],[2,10],[3,5],[4,9],[6,8]]
Output: 1
Explanation:
- At time 1, all three rooms are not being used. The first meeting starts in room 0.
- At time 2, rooms 1 and 2 are not being used. The second meeting starts in room 1.
- At time 3, only room 2 is not being used. The third meeting starts in room 2.
- At time 4, all three rooms are being used. The fourth meeting is delayed.
- At time 5, the meeting in room 2 finishes. The fourth meeting starts in room 2 for the time period [5,10).
- At time 6, all three rooms are being used. The fifth meeting is delayed.
- At time 10, the meetings in rooms 1 and 2 finish. The fifth meeting starts in room 1 for the time period [10,12).
Room 0 held 1 meeting while rooms 1 and 2 each held 2 meetings, so we return 1.
Constraints:
1 <= n <= 100
1 <= meetings.length <= 105
meetings[i].length == 2
0 <= starti < endi <= 5 * 105
All the values of starti are unique. | Python | More heap extravaganza | 41 | meeting-rooms-iii | 0.332 | sr_vrd | Hard | 32,809 | 2,402 |
most frequent even element | class Solution:
def mostFrequentEven(self, nums: List[int]) -> int:
ctr = Counter(nums)
return max([c for c in ctr if not c%2], key = lambda x:(ctr[x], -x), default = -1) | https://leetcode.com/problems/most-frequent-even-element/discuss/2581151/Python-3-oror-2-lines-Counter-oror-TM%3A-9586 | 6 | Given an integer array nums, return the most frequent even element.
If there is a tie, return the smallest one. If there is no such element, return -1.
Example 1:
Input: nums = [0,1,2,2,4,4,1]
Output: 2
Explanation:
The even elements are 0, 2, and 4. Of these, 2 and 4 appear the most.
We return the smallest one, which is 2.
Example 2:
Input: nums = [4,4,4,9,2,4]
Output: 4
Explanation: 4 is the even element appears the most.
Example 3:
Input: nums = [29,47,21,41,13,37,25,7]
Output: -1
Explanation: There is no even element.
Constraints:
1 <= nums.length <= 2000
0 <= nums[i] <= 105 | Python 3 || 2 lines, Counter || T/M: 95%/86% | 268 | most-frequent-even-element | 0.516 | warrenruud | Easy | 32,816 | 2,404 |
optimal partition of string | class Solution:
def partitionString(self, s: str) -> int:
cur = set()
res = 1
for c in s:
if c in cur:
cur = set()
res += 1
cur.add(c)
return res | https://leetcode.com/problems/optimal-partition-of-string/discuss/2560044/Python3-Greedy | 9 | Given a string s, partition the string into one or more substrings such that the characters in each substring are unique. That is, no letter appears in a single substring more than once.
Return the minimum number of substrings in such a partition.
Note that each character should belong to exactly one substring in a partition.
Example 1:
Input: s = "abacaba"
Output: 4
Explanation:
Two possible partitions are ("a","ba","cab","a") and ("ab","a","ca","ba").
It can be shown that 4 is the minimum number of substrings needed.
Example 2:
Input: s = "ssssss"
Output: 6
Explanation:
The only valid partition is ("s","s","s","s","s","s").
Constraints:
1 <= s.length <= 105
s consists of only English lowercase letters. | [Python3] Greedy | 547 | optimal-partition-of-string | 0.744 | 0xRoxas | Medium | 32,844 | 2,405 |
divide intervals into minimum number of groups | class Solution:
def minGroups(self, intervals: List[List[int]]) -> int:
pq = []
for left, right in sorted(intervals):
if pq and pq[0] < left:
heappop(pq)
heappush(pq, right)
return len(pq) | https://leetcode.com/problems/divide-intervals-into-minimum-number-of-groups/discuss/2560020/Min-Heap | 227 | You are given a 2D integer array intervals where intervals[i] = [lefti, righti] represents the inclusive interval [lefti, righti].
You have to divide the intervals into one or more groups such that each interval is in exactly one group, and no two intervals that are in the same group intersect each other.
Return the minimum number of groups you need to make.
Two intervals intersect if there is at least one common number between them. For example, the intervals [1, 5] and [5, 8] intersect.
Example 1:
Input: intervals = [[5,10],[6,8],[1,5],[2,3],[1,10]]
Output: 3
Explanation: We can divide the intervals into the following groups:
- Group 1: [1, 5], [6, 8].
- Group 2: [2, 3], [5, 10].
- Group 3: [1, 10].
It can be proven that it is not possible to divide the intervals into fewer than 3 groups.
Example 2:
Input: intervals = [[1,3],[5,6],[8,10],[11,13]]
Output: 1
Explanation: None of the intervals overlap, so we can put all of them in one group.
Constraints:
1 <= intervals.length <= 105
intervals[i].length == 2
1 <= lefti <= righti <= 106 | Min Heap | 5,600 | divide-intervals-into-minimum-number-of-groups | 0.454 | votrubac | Medium | 32,873 | 2,406 |
longest increasing subsequence ii | class Solution:
def getmax(self, st, start, end):
maxi = 0
while start < end:
if start%2:#odd
maxi = max(maxi, st[start])
start += 1
if end%2:#odd
end -= 1
maxi = max(maxi, st[end])
start //= 2
end //= 2
return maxi
def update(self, st, maxi, n):
st[n] = maxi
while n > 1:
n //= 2
st[n] = max(st[2*n], st[2*n+1])
def lengthOfLIS(self, nums: List[int], k: int) -> int:
ans = 1
length = max(nums)
st = [0]*length*2
for n in nums:
n -= 1
maxi = self.getmax(st, max(0, n-k)+length, n+length) + 1
self.update(st, maxi, n+length)
ans = max(maxi, ans)
return ans | https://leetcode.com/problems/longest-increasing-subsequence-ii/discuss/2591153/Python-runtime-O(n-logn)-memory-O(n) | 0 | You are given an integer array nums and an integer k.
Find the longest subsequence of nums that meets the following requirements:
The subsequence is strictly increasing and
The difference between adjacent elements in the subsequence is at most k.
Return the length of the longest subsequence that meets the requirements.
A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
Example 1:
Input: nums = [4,2,1,4,3,4,5,8,15], k = 3
Output: 5
Explanation:
The longest subsequence that meets the requirements is [1,3,4,5,8].
The subsequence has a length of 5, so we return 5.
Note that the subsequence [1,3,4,5,8,15] does not meet the requirements because 15 - 8 = 7 is larger than 3.
Example 2:
Input: nums = [7,4,5,1,8,12,4,7], k = 5
Output: 4
Explanation:
The longest subsequence that meets the requirements is [4,5,8,12].
The subsequence has a length of 4, so we return 4.
Example 3:
Input: nums = [1,5], k = 1
Output: 1
Explanation:
The longest subsequence that meets the requirements is [1].
The subsequence has a length of 1, so we return 1.
Constraints:
1 <= nums.length <= 105
1 <= nums[i], k <= 105 | Python, runtime O(n logn), memory O(n) | 114 | longest-increasing-subsequence-ii | 0.209 | tsai00150 | Hard | 32,886 | 2,407 |
count days spent together | class Solution:
def countDaysTogether(self, arAl: str, lAl: str, arBo: str, lBo: str) -> int:
months = [-1, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
start = max(arAl, arBo)
end = min(lAl, lBo)
startDay = int(start[3:])
startMonth = int(start[:2])
endDay = int(end[3:])
endMonth = int(end[:2])
if start > end:
return 0
if startMonth == endMonth:
return endDay-startDay+1
elif startMonth < endMonth:
return months[startMonth]-startDay + endDay + 1 + sum(months[m] for m in range(startMonth+1, endMonth)) | https://leetcode.com/problems/count-days-spent-together/discuss/2601983/Very-Easy-Question-or-Visual-Explanation-or-100 | 3 | Alice and Bob are traveling to Rome for separate business meetings.
You are given 4 strings arriveAlice, leaveAlice, arriveBob, and leaveBob. Alice will be in the city from the dates arriveAlice to leaveAlice (inclusive), while Bob will be in the city from the dates arriveBob to leaveBob (inclusive). Each will be a 5-character string in the format "MM-DD", corresponding to the month and day of the date.
Return the total number of days that Alice and Bob are in Rome together.
You can assume that all dates occur in the same calendar year, which is not a leap year. Note that the number of days per month can be represented as: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31].
Example 1:
Input: arriveAlice = "08-15", leaveAlice = "08-18", arriveBob = "08-16", leaveBob = "08-19"
Output: 3
Explanation: Alice will be in Rome from August 15 to August 18. Bob will be in Rome from August 16 to August 19. They are both in Rome together on August 16th, 17th, and 18th, so the answer is 3.
Example 2:
Input: arriveAlice = "10-01", leaveAlice = "10-31", arriveBob = "11-01", leaveBob = "12-31"
Output: 0
Explanation: There is no day when Alice and Bob are in Rome together, so we return 0.
Constraints:
All dates are provided in the format "MM-DD".
Alice and Bob's arrival dates are earlier than or equal to their leaving dates.
The given dates are valid dates of a non-leap year. | Very Easy Question | Visual Explanation | 100% | 78 | count-days-spent-together | 0.428 | leet_satyam | Easy | 32,888 | 2,409 |
maximum matching of players with trainers | class Solution:
def matchPlayersAndTrainers(self, players: List[int], trainers: List[int]) -> int:
n = len(players)
m = len(trainers)
players.sort()
trainers.sort()
dp = {}
def helper(i,j):
if i==n or j==m:
return 0
if (i,j) in dp:
return dp[(i,j)]
if players[i]<=trainers[j]:
dp[(i,j)] = 1+helper(i+1,j+1)
else:
dp[(i,j)] = helper(i,j+1)
return dp[(i,j)]
return helper(0,0) | https://leetcode.com/problems/maximum-matching-of-players-with-trainers/discuss/2588450/Python-code-using-recursion | 2 | You are given a 0-indexed integer array players, where players[i] represents the ability of the ith player. You are also given a 0-indexed integer array trainers, where trainers[j] represents the training capacity of the jth trainer.
The ith player can match with the jth trainer if the player's ability is less than or equal to the trainer's training capacity. Additionally, the ith player can be matched with at most one trainer, and the jth trainer can be matched with at most one player.
Return the maximum number of matchings between players and trainers that satisfy these conditions.
Example 1:
Input: players = [4,7,9], trainers = [8,2,5,8]
Output: 2
Explanation:
One of the ways we can form two matchings is as follows:
- players[0] can be matched with trainers[0] since 4 <= 8.
- players[1] can be matched with trainers[3] since 7 <= 8.
It can be proven that 2 is the maximum number of matchings that can be formed.
Example 2:
Input: players = [1,1,1], trainers = [10]
Output: 1
Explanation:
The trainer can be matched with any of the 3 players.
Each player can only be matched with one trainer, so the maximum answer is 1.
Constraints:
1 <= players.length, trainers.length <= 105
1 <= players[i], trainers[j] <= 109 | Python code using recursion | 53 | maximum-matching-of-players-with-trainers | 0.598 | kamal0308 | Medium | 32,904 | 2,410 |
smallest subarrays with maximum bitwise or | class Solution:
def smallestSubarrays(self, nums: List[int]) -> List[int]:
def create(m):
t = 0
for n in m:
if m[n] > 0:
t = t | (1 << n)
return t
def add(a,m):
ans = bin( a )
s = str(ans)[2:]
for i, b in enumerate( s[::-1]):
if b == '1':
m[i] += 1
def remove(a,m):
ans = bin( a )
s = str(ans)[2:]
for i, b in enumerate( s[::-1]):
if b == '1':
m[i] -= 1
res = []
n = defaultdict(int)
for i in nums:
add(i,n)
m = defaultdict(int)
r = 0
c = 0
for i,v in enumerate(nums):
# The last check is for if nums[i] == 0, in that case we still want to add to the map
while r < len(nums) and (create(m) != create(n) or (c==0 and nums[i] ==0)):
add(nums[r],m)
r+=1
c+=1
res.append(c)
remove(nums[i],m)
remove(nums[i],n)
c-=1
return res | https://leetcode.com/problems/smallest-subarrays-with-maximum-bitwise-or/discuss/2588110/Secret-Python-Answer-Sliding-Window-with-Double-Dictionary-of-Binary-Count | 1 | You are given a 0-indexed array nums of length n, consisting of non-negative integers. For each index i from 0 to n - 1, you must determine the size of the minimum sized non-empty subarray of nums starting at i (inclusive) that has the maximum possible bitwise OR.
In other words, let Bij be the bitwise OR of the subarray nums[i...j]. You need to find the smallest subarray starting at i, such that bitwise OR of this subarray is equal to max(Bik) where i <= k <= n - 1.
The bitwise OR of an array is the bitwise OR of all the numbers in it.
Return an integer array answer of size n where answer[i] is the length of the minimum sized subarray starting at i with maximum bitwise OR.
A subarray is a contiguous non-empty sequence of elements within an array.
Example 1:
Input: nums = [1,0,2,1,3]
Output: [3,3,2,2,1]
Explanation:
The maximum possible bitwise OR starting at any index is 3.
- Starting at index 0, the shortest subarray that yields it is [1,0,2].
- Starting at index 1, the shortest subarray that yields the maximum bitwise OR is [0,2,1].
- Starting at index 2, the shortest subarray that yields the maximum bitwise OR is [2,1].
- Starting at index 3, the shortest subarray that yields the maximum bitwise OR is [1,3].
- Starting at index 4, the shortest subarray that yields the maximum bitwise OR is [3].
Therefore, we return [3,3,2,2,1].
Example 2:
Input: nums = [1,2]
Output: [2,1]
Explanation:
Starting at index 0, the shortest subarray that yields the maximum bitwise OR is of length 2.
Starting at index 1, the shortest subarray that yields the maximum bitwise OR is of length 1.
Therefore, we return [2,1].
Constraints:
n == nums.length
1 <= n <= 105
0 <= nums[i] <= 109 | [Secret Python Answer🤫🐍👌😍] Sliding Window with Double Dictionary of Binary Count | 113 | smallest-subarrays-with-maximum-bitwise-or | 0.403 | xmky | Medium | 32,915 | 2,411 |
minimum money required before transactions | class Solution:
def minimumMoney(self, transactions: List[List[int]]) -> int:
ans = val = 0
for cost, cashback in transactions:
ans += max(0, cost - cashback)
val = max(val, min(cost, cashback))
return ans + val | https://leetcode.com/problems/minimum-money-required-before-transactions/discuss/2588620/Python3-Greedy | 0 | You are given a 0-indexed 2D integer array transactions, where transactions[i] = [costi, cashbacki].
The array describes transactions, where each transaction must be completed exactly once in some order. At any given moment, you have a certain amount of money. In order to complete transaction i, money >= costi must hold true. After performing a transaction, money becomes money - costi + cashbacki.
Return the minimum amount of money required before any transaction so that all of the transactions can be completed regardless of the order of the transactions.
Example 1:
Input: transactions = [[2,1],[5,0],[4,2]]
Output: 10
Explanation:
Starting with money = 10, the transactions can be performed in any order.
It can be shown that starting with money < 10 will fail to complete all transactions in some order.
Example 2:
Input: transactions = [[3,0],[0,3]]
Output: 3
Explanation:
- If transactions are in the order [[3,0],[0,3]], the minimum money required to complete the transactions is 3.
- If transactions are in the order [[0,3],[3,0]], the minimum money required to complete the transactions is 0.
Thus, starting with money = 3, the transactions can be performed in any order.
Constraints:
1 <= transactions.length <= 105
transactions[i].length == 2
0 <= costi, cashbacki <= 109 | [Python3] Greedy | 19 | minimum-money-required-before-transactions | 0.391 | ye15 | Hard | 32,925 | 2,412 |
smallest even multiple | class Solution:
def smallestEvenMultiple(self, n: int) -> int:
# it's just asking for LCM of 2 and n
return lcm(2, n) | https://leetcode.com/problems/smallest-even-multiple/discuss/2601867/LeetCode-The-Hard-Way-Explained-Line-By-Line | 5 | 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: 6
Explanation: The smallest multiple of both 6 and 2 is 6. Note that a number is a multiple of itself.
Constraints:
1 <= n <= 150 | 🔥 [LeetCode The Hard Way] 🔥 Explained Line By Line | 258 | smallest-even-multiple | 0.879 | wingkwong | Easy | 32,926 | 2,413 |
length of the longest alphabetical continuous substring | class Solution:
def longestContinuousSubstring(self, s: str) -> int:
arr = ''.join(['1' if ord(s[i])-ord(s[i-1]) == 1
else ' ' for i in range(1,len(s))]).split()
return max((len(ones)+1 for ones in arr), default = 1) | https://leetcode.com/problems/length-of-the-longest-alphabetical-continuous-substring/discuss/2594370/Python3-oror-Str-join-and-split-2-lines-oror-TM-375ms15.7-MB | 3 | An alphabetical continuous string is a string consisting of consecutive letters in the alphabet. In other words, it is any substring of the string "abcdefghijklmnopqrstuvwxyz".
For example, "abc" is an alphabetical continuous string, while "acb" and "za" are not.
Given a string s consisting of lowercase letters only, return the length of the longest alphabetical continuous substring.
Example 1:
Input: s = "abacaba"
Output: 2
Explanation: There are 4 distinct continuous substrings: "a", "b", "c" and "ab".
"ab" is the longest continuous substring.
Example 2:
Input: s = "abcde"
Output: 5
Explanation: "abcde" is the longest continuous substring.
Constraints:
1 <= s.length <= 105
s consists of only English lowercase letters. | Python3 || Str join & split, 2 lines || T/M 375ms/15.7 MB | 38 | length-of-the-longest-alphabetical-continuous-substring | 0.558 | warrenruud | Medium | 32,963 | 2,414 |
reverse odd levels of binary tree | class Solution:
def reverseOddLevels(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
def dfs(n1, n2, level):
if not n1:
return
if level % 2:
n1.val, n2.val = n2.val, n1.val
dfs(n1.left, n2.right, level + 1)
dfs(n1.right, n2.left, level + 1)
dfs(root.left, root.right, 1)
return root | https://leetcode.com/problems/reverse-odd-levels-of-binary-tree/discuss/2825833/Python-DFS | 0 | Given the root of a perfect binary tree, reverse the node values at each odd level of the tree.
For example, suppose the node values at level 3 are [2,1,3,4,7,11,29,18], then it should become [18,29,11,7,4,3,1,2].
Return the root of the reversed tree.
A binary tree is perfect if all parent nodes have two children and all leaves are on the same level.
The level of a node is the number of edges along the path between it and the root node.
Example 1:
Input: root = [2,3,5,8,13,21,34]
Output: [2,5,3,8,13,21,34]
Explanation:
The tree has only one odd level.
The nodes at level 1 are 3, 5 respectively, which are reversed and become 5, 3.
Example 2:
Input: root = [7,13,11]
Output: [7,11,13]
Explanation:
The nodes at level 1 are 13, 11, which are reversed and become 11, 13.
Example 3:
Input: root = [0,1,2,0,0,0,0,1,1,1,1,2,2,2,2]
Output: [0,2,1,0,0,0,0,2,2,2,2,1,1,1,1]
Explanation:
The odd levels have non-zero values.
The nodes at level 1 were 1, 2, and are 2, 1 after the reversal.
The nodes at level 3 were 1, 1, 1, 1, 2, 2, 2, 2, and are 2, 2, 2, 2, 1, 1, 1, 1 after the reversal.
Constraints:
The number of nodes in the tree is in the range [1, 214].
0 <= Node.val <= 105
root is a perfect binary tree. | Python, DFS | 4 | reverse-odd-levels-of-binary-tree | 0.757 | blue_sky5 | Medium | 32,985 | 2,415 |
sum of prefix scores of strings | class Solution:
def sumPrefixScores(self, words: List[str]) -> List[int]:
d = defaultdict(int)
for word in words:
for index in range(1, len(word) + 1):
d[word[:index]] += 1
result = []
for word in words:
current_sum = 0
for index in range(1, len(word) + 1):
current_sum = current_sum + d[word[:index]]
result.append(current_sum)
return result | https://leetcode.com/problems/sum-of-prefix-scores-of-strings/discuss/2590687/Python-Simple-Python-Solution-Using-Dictionary | 1 | You are given an array words of size n consisting of non-empty strings.
We define the score of a string word as the number of strings words[i] such that word is a prefix of words[i].
For example, if words = ["a", "ab", "abc", "cab"], then the score of "ab" is 2, since "ab" is a prefix of both "ab" and "abc".
Return an array answer of size n where answer[i] is the sum of scores of every non-empty prefix of words[i].
Note that a string is considered as a prefix of itself.
Example 1:
Input: words = ["abc","ab","bc","b"]
Output: [5,4,3,2]
Explanation: The answer for each string is the following:
- "abc" has 3 prefixes: "a", "ab", and "abc".
- There are 2 strings with the prefix "a", 2 strings with the prefix "ab", and 1 string with the prefix "abc".
The total is answer[0] = 2 + 2 + 1 = 5.
- "ab" has 2 prefixes: "a" and "ab".
- There are 2 strings with the prefix "a", and 2 strings with the prefix "ab".
The total is answer[1] = 2 + 2 = 4.
- "bc" has 2 prefixes: "b" and "bc".
- There are 2 strings with the prefix "b", and 1 string with the prefix "bc".
The total is answer[2] = 2 + 1 = 3.
- "b" has 1 prefix: "b".
- There are 2 strings with the prefix "b".
The total is answer[3] = 2.
Example 2:
Input: words = ["abcd"]
Output: [4]
Explanation:
"abcd" has 4 prefixes: "a", "ab", "abc", and "abcd".
Each prefix has a score of one, so the total is answer[0] = 1 + 1 + 1 + 1 = 4.
Constraints:
1 <= words.length <= 1000
1 <= words[i].length <= 1000
words[i] consists of lowercase English letters. | [ Python ] ✅✅ Simple Python Solution Using Dictionary 🥳✌👍 | 70 | sum-of-prefix-scores-of-strings | 0.426 | ASHOK_KUMAR_MEGHVANSHI | Hard | 33,003 | 2,416 |
sort the people | class Solution: # Ex: names = ["Larry","Curly","Moe"] heights = [130,125,155]
def sortPeople(self, names: List[str], heights: List[int]) -> List[str]:
_,names = zip(*sorted(zip(heights,names), reverse = True))
# zipped --> [(130,"Larry"), (125,"Curly"), (155,"Moe") ]
# sorted --> [(155,"Moe" ), (130,"Larry"), (125,"Curly")]
# unzipped --> _ = (155,130,125) , names = ("Moe","Larry","Curly")
return list(names) # list(names) = ["Moe","Larry","Curly"] | https://leetcode.com/problems/sort-the-people/discuss/2627285/python3-oror-2-lines-with-example-oror-TM-42ms14.3MB | 7 | You are given an array of strings names, and an array heights that consists of distinct positive integers. Both arrays are of length n.
For each index i, names[i] and heights[i] denote the name and height of the ith person.
Return names sorted in descending order by the people's heights.
Example 1:
Input: names = ["Mary","John","Emma"], heights = [180,165,170]
Output: ["Mary","Emma","John"]
Explanation: Mary is the tallest, followed by Emma and John.
Example 2:
Input: names = ["Alice","Bob","Bob"], heights = [155,185,150]
Output: ["Bob","Alice","Bob"]
Explanation: The first Bob is the tallest, followed by Alice and the second Bob.
Constraints:
n == names.length == heights.length
1 <= n <= 103
1 <= names[i].length <= 20
1 <= heights[i] <= 105
names[i] consists of lower and upper case English letters.
All the values of heights are distinct. | python3 || 2 lines with example || T/M = 42ms/14.3MB | 575 | sort-the-people | 0.82 | warrenruud | Easy | 33,015 | 2,418 |
longest subarray with maximum bitwise and | class Solution:
def longestSubarray(self, nums: List[int]) -> int:
max_n = max(nums)
return max(len(list(it)) for n, it in groupby(nums) if n == max_n) | https://leetcode.com/problems/longest-subarray-with-maximum-bitwise-and/discuss/2648255/Group-By-and-One-Pass | 7 | You are given an integer array nums of size n.
Consider a non-empty subarray from nums that has the maximum possible bitwise AND.
In other words, let k be the maximum value of the bitwise AND of any subarray of nums. Then, only subarrays with a bitwise AND equal to k should be considered.
Return the length of the longest such subarray.
The bitwise AND of an array is the bitwise AND of all the numbers in it.
A subarray is a contiguous sequence of elements within an array.
Example 1:
Input: nums = [1,2,3,3,2,2]
Output: 2
Explanation:
The maximum possible bitwise AND of a subarray is 3.
The longest subarray with that value is [3,3], so we return 2.
Example 2:
Input: nums = [1,2,3,4]
Output: 1
Explanation:
The maximum possible bitwise AND of a subarray is 4.
The longest subarray with that value is [4], so we return 1.
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 106 | Group By and One-Pass | 63 | longest-subarray-with-maximum-bitwise-and | 0.477 | votrubac | Medium | 33,067 | 2,419 |
find all good indices | class Solution:
def goodIndices(self, nums: List[int], k: int) -> List[int]:
### forward pass.
forward = [False]*len(nums) ### For the forward pass, store if index i is good or not.
stack = []
for i in range(len(nums)):
### if the leangth of stack is greater or equal to k, it means this index is good.
if len(stack)>=k:
forward[i] = True
### if the stack is empty, just add the current number to it.
if not stack:
stack.append(nums[i])
### check to see if the current number is smaller or equal to the last number in stack, if it is not, put this number into the stack.
else:
if nums[i]<=stack[-1]:
stack.append(nums[i])
else:
stack = [nums[i]]
### backward pass
res = []
stack = []
for i in reversed(range(len(nums))):
### Check to see if the length of stack is greater or equal to k and also check if the forward pass at this index is Ture.
if len(stack)>=k and forward[i]:
res.append(i)
if not stack:
stack.append(nums[i])
else:
if nums[i]<=stack[-1]:
stack.append(nums[i])
else:
stack = [nums[i]]
return res[::-1] | https://leetcode.com/problems/find-all-good-indices/discuss/2620637/Python3-Two-passes-O(n)-with-line-by-line-comments. | 34 | You are given a 0-indexed integer array nums of size n and a positive integer k.
We call an index i in the range k <= i < n - k good if the following conditions are satisfied:
The k elements that are just before the index i are in non-increasing order.
The k elements that are just after the index i are in non-decreasing order.
Return an array of all good indices sorted in increasing order.
Example 1:
Input: nums = [2,1,1,1,3,4,1], k = 2
Output: [2,3]
Explanation: There are two good indices in the array:
- Index 2. The subarray [2,1] is in non-increasing order, and the subarray [1,3] is in non-decreasing order.
- Index 3. The subarray [1,1] is in non-increasing order, and the subarray [3,4] is in non-decreasing order.
Note that the index 4 is not good because [4,1] is not non-decreasing.
Example 2:
Input: nums = [2,1,1,2], k = 2
Output: []
Explanation: There are no good indices in this array.
Constraints:
n == nums.length
3 <= n <= 105
1 <= nums[i] <= 106
1 <= k <= n / 2 | [Python3] Two passes O(n) with line by line comments. | 1,400 | find-all-good-indices | 0.372 | md2030 | Medium | 33,076 | 2,420 |
number of good paths | class Solution:
def numberOfGoodPaths(self, vals: List[int], edges: List[List[int]]) -> int:
n = len(vals)
g = defaultdict(list)
# start from node with minimum val
for a, b in edges:
heappush(g[a], (vals[b], b))
heappush(g[b], (vals[a], a))
loc = list(range(n))
def find(x):
if loc[x] != x:
loc[x] = find(loc[x])
return loc[x]
def union(x, y):
a, b = find(x), find(y)
if a != b:
loc[b] = a
# node by val
v = defaultdict(list)
for i, val in enumerate(vals):
v[val].append(i)
ans = n
for k in sorted(v):
for node in v[k]:
# build graph if neighboring node <= current node val
while g[node] and g[node][0][0] <= k:
nei_v, nei = heappop(g[node])
union(node, nei)
# Count unioned groups
grp = Counter([find(x) for x in v[k]])
# for each unioned group, select two nodes (order doesn't matter)
ans += sum(math.comb(x, 2) for x in grp.values())
return ans | https://leetcode.com/problems/number-of-good-paths/discuss/2623051/Python-3Hint-solution-Heap-%2B-Union-find | 0 | There is a tree (i.e. a connected, undirected graph with no cycles) consisting of n nodes numbered from 0 to n - 1 and exactly n - 1 edges.
You are given a 0-indexed integer array vals of length n where vals[i] denotes the value of the ith node. You are also given a 2D integer array edges where edges[i] = [ai, bi] denotes that there exists an undirected edge connecting nodes ai and bi.
A good path is a simple path that satisfies the following conditions:
The starting node and the ending node have the same value.
All nodes between the starting node and the ending node have values less than or equal to the starting node (i.e. the starting node's value should be the maximum value along the path).
Return the number of distinct good paths.
Note that a path and its reverse are counted as the same path. For example, 0 -> 1 is considered to be the same as 1 -> 0. A single node is also considered as a valid path.
Example 1:
Input: vals = [1,3,2,1,3], edges = [[0,1],[0,2],[2,3],[2,4]]
Output: 6
Explanation: There are 5 good paths consisting of a single node.
There is 1 additional good path: 1 -> 0 -> 2 -> 4.
(The reverse path 4 -> 2 -> 0 -> 1 is treated as the same as 1 -> 0 -> 2 -> 4.)
Note that 0 -> 2 -> 3 is not a good path because vals[2] > vals[0].
Example 2:
Input: vals = [1,1,2,2,3], edges = [[0,1],[1,2],[2,3],[2,4]]
Output: 7
Explanation: There are 5 good paths consisting of a single node.
There are 2 additional good paths: 0 -> 1 and 2 -> 3.
Example 3:
Input: vals = [1], edges = []
Output: 1
Explanation: The tree consists of only one node, so there is one good path.
Constraints:
n == vals.length
1 <= n <= 3 * 104
0 <= vals[i] <= 105
edges.length == n - 1
edges[i].length == 2
0 <= ai, bi < n
ai != bi
edges represents a valid tree. | [Python 3]Hint solution Heap + Union find | 57 | number-of-good-paths | 0.398 | chestnut890123 | Hard | 33,085 | 2,421 |
remove letter to equalize frequency | class Solution:
def equalFrequency(self, word: str) -> bool:
cnt = Counter(Counter(word).values())
if (len(cnt) == 1):
return list(cnt.keys())[0] == 1 or list(cnt.values())[0] == 1
if (len(cnt) == 2):
f1, f2 = min(cnt.keys()), max(cnt.keys())
return (f1 + 1 == f2 and cnt[f2] == 1) or (f1 == 1 and cnt[f1] == 1)
return False | https://leetcode.com/problems/remove-letter-to-equalize-frequency/discuss/2660629/Counter-of-Counter | 9 | 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 all letters in word are equal, and false otherwise.
Note:
The frequency of a letter x is the number of times it occurs in the string.
You must remove exactly one letter and cannot choose to do nothing.
Example 1:
Input: word = "abcc"
Output: true
Explanation: Select index 3 and delete it: word becomes "abc" and each character has a frequency of 1.
Example 2:
Input: word = "aazz"
Output: false
Explanation: We must delete a character, so either the frequency of "a" is 1 and the frequency of "z" is 2, or vice versa. It is impossible to make all present letters have equal frequency.
Constraints:
2 <= word.length <= 100
word consists of lowercase English letters only. | Counter of Counter | 336 | remove-letter-to-equalize-frequency | 0.193 | votrubac | Easy | 33,088 | 2,423 |
bitwise xor of all pairings | class Solution:
def xorAllNums(self, nums1: List[int], nums2: List[int]) -> int:
m, n = map(len, (nums1, nums2))
return (m % 2 * reduce(xor, nums2)) ^ (n % 2 * reduce(xor, nums1)) | https://leetcode.com/problems/bitwise-xor-of-all-pairings/discuss/2646655/JavaPython-3-Bit-manipulations-analysis. | 10 | You are given two 0-indexed arrays, nums1 and nums2, consisting of non-negative integers. There exists another array, nums3, which contains the bitwise XOR of all pairings of integers between nums1 and nums2 (every integer in nums1 is paired with every integer in nums2 exactly once).
Return the bitwise XOR of all integers in nums3.
Example 1:
Input: nums1 = [2,1,3], nums2 = [10,2,5,0]
Output: 13
Explanation:
A possible nums3 array is [8,0,7,2,11,3,4,1,9,1,6,3].
The bitwise XOR of all these numbers is 13, so we return 13.
Example 2:
Input: nums1 = [1,2], nums2 = [3,4]
Output: 0
Explanation:
All possible pairs of bitwise XORs are nums1[0] ^ nums2[0], nums1[0] ^ nums2[1], nums1[1] ^ nums2[0],
and nums1[1] ^ nums2[1].
Thus, one possible nums3 array is [2,5,1,6].
2 ^ 5 ^ 1 ^ 6 = 0, so we return 0.
Constraints:
1 <= nums1.length, nums2.length <= 105
0 <= nums1[i], nums2[j] <= 109 | [Java/Python 3] Bit manipulations analysis. | 221 | bitwise-xor-of-all-pairings | 0.586 | rock | Medium | 33,118 | 2,425 |
number of pairs satisfying inequality | class Solution:
def numberOfPairs(self, nums1: List[int], nums2: List[int], diff: int) -> int:
n=len(nums1)
for i in range(n):
nums1[i]=nums1[i]-nums2[i]
ans=0
arr=[]
for i in range(n):
x=bisect_right(arr,nums1[i]+diff)
ans+=x
insort(arr,nums1[i])
return ans | https://leetcode.com/problems/number-of-pairs-satisfying-inequality/discuss/2647569/Python-Binary-Search-oror-Time%3A-2698-ms-(50)-Space%3A-32.5-MB-(100) | 0 | You are given two 0-indexed integer arrays nums1 and nums2, each of size n, and an integer diff. Find the number of pairs (i, j) such that:
0 <= i < j <= n - 1 and
nums1[i] - nums1[j] <= nums2[i] - nums2[j] + diff.
Return the number of pairs that satisfy the conditions.
Example 1:
Input: nums1 = [3,2,5], nums2 = [2,2,1], diff = 1
Output: 3
Explanation:
There are 3 pairs that satisfy the conditions:
1. i = 0, j = 1: 3 - 2 <= 2 - 2 + 1. Since i < j and 1 <= 1, this pair satisfies the conditions.
2. i = 0, j = 2: 3 - 5 <= 2 - 1 + 1. Since i < j and -2 <= 2, this pair satisfies the conditions.
3. i = 1, j = 2: 2 - 5 <= 2 - 1 + 1. Since i < j and -3 <= 2, this pair satisfies the conditions.
Therefore, we return 3.
Example 2:
Input: nums1 = [3,-1], nums2 = [-2,2], diff = -1
Output: 0
Explanation:
Since there does not exist any pair that satisfies the conditions, we return 0.
Constraints:
n == nums1.length == nums2.length
2 <= n <= 105
-104 <= nums1[i], nums2[i] <= 104
-104 <= diff <= 104 | Python Binary Search || Time: 2698 ms (50%), Space: 32.5 MB (100%) | 15 | number-of-pairs-satisfying-inequality | 0.422 | koder_786 | Hard | 33,137 | 2,426 |
number of common factors | class Solution:
def commonFactors(self, a: int, b: int) -> int:
c=0
mi=min(a,b)
for i in range(1,mi+1):
if a%i==0 and b%i==0:
c+=1
return c | https://leetcode.com/problems/number-of-common-factors/discuss/2817862/Easy-Python-Solution | 3 | Given two positive integers a and b, return the number of common factors of a and b.
An integer x is a common factor of a and b if x divides both a and b.
Example 1:
Input: a = 12, b = 6
Output: 4
Explanation: The common factors of 12 and 6 are 1, 2, 3, 6.
Example 2:
Input: a = 25, b = 30
Output: 2
Explanation: The common factors of 25 and 30 are 1, 5.
Constraints:
1 <= a, b <= 1000 | Easy Python Solution | 62 | number-of-common-factors | 0.801 | Vistrit | Easy | 33,141 | 2,427 |
maximum sum of an hourglass | class Solution:
def maxSum(self, grid: List[List[int]]) -> int:
res=0
cur=0
for i in range(len(grid)-2):
for j in range(1,len(grid[0])-1):
cur=sum(grid[i][j-1:j+2]) +grid[i+1][j] + sum(grid[i+2][j-1:j+2])
res = max(res,cur)
return res | https://leetcode.com/problems/maximum-sum-of-an-hourglass/discuss/2677741/Simple-Python-Solution-oror-O(MxN)-beats-83.88 | 1 | You are given an m x n integer matrix grid.
We define an hourglass as a part of the matrix with the following form:
Return the maximum sum of the elements of an hourglass.
Note that an hourglass cannot be rotated and must be entirely contained within the matrix.
Example 1:
Input: grid = [[6,2,1,3],[4,2,1,5],[9,2,8,7],[4,1,2,9]]
Output: 30
Explanation: The cells shown above represent the hourglass with the maximum sum: 6 + 2 + 1 + 2 + 9 + 2 + 8 = 30.
Example 2:
Input: grid = [[1,2,3],[4,5,6],[7,8,9]]
Output: 35
Explanation: There is only one hourglass in the matrix, with the sum: 1 + 2 + 3 + 5 + 7 + 8 + 9 = 35.
Constraints:
m == grid.length
n == grid[i].length
3 <= m, n <= 150
0 <= grid[i][j] <= 106 | Simple Python Solution || O(MxN) beats 83.88% | 42 | maximum-sum-of-an-hourglass | 0.739 | Graviel77 | Medium | 33,178 | 2,428 |
minimize xor | class Solution:
def minimizeXor(self, num1: int, num2: int) -> int:
nbit1 = 0
while num2>0:
nbit1 = nbit1 + (num2&1)
num2 = num2 >> 1
# print(nbit1)
chk = []
ans = 0
# print(bin(num1), bin(ans))
for i in range(31, -1, -1):
biti = (num1>>i)&1
if biti==1 and nbit1>0:
num1 = num1 & ~(1<<i)
ans = ans | (1<<i)
chk.append(i)
nbit1 -= 1
# print(bin(num1), bin(ans))
if nbit1>0:
for i in range(0, 32, 1):
biti = (num1>>i)&1
if i not in chk and nbit1>0:
num1 = num1 | (1<<i)
ans = ans | (1<<i)
nbit1 -= 1
# print(bin(num1), bin(ans))
# print("=" * 20)
return ans | https://leetcode.com/problems/minimize-xor/discuss/2649210/O(log(n))-using-set-and-clear-bit-(examples) | 1 | Given two positive integers num1 and num2, find the positive integer x such that:
x has the same number of set bits as num2, and
The value x XOR num1 is minimal.
Note that XOR is the bitwise XOR operation.
Return the integer x. The test cases are generated such that x is uniquely determined.
The number of set bits of an integer is the number of 1's in its binary representation.
Example 1:
Input: num1 = 3, num2 = 5
Output: 3
Explanation:
The binary representations of num1 and num2 are 0011 and 0101, respectively.
The integer 3 has the same number of set bits as num2, and the value 3 XOR 3 = 0 is minimal.
Example 2:
Input: num1 = 1, num2 = 12
Output: 3
Explanation:
The binary representations of num1 and num2 are 0001 and 1100, respectively.
The integer 3 has the same number of set bits as num2, and the value 3 XOR 1 = 2 is minimal.
Constraints:
1 <= num1, num2 <= 109 | O(log(n)) using set and clear bit (examples) | 39 | minimize-xor | 0.418 | dntai | Medium | 33,205 | 2,429 |
maximum deletions on a string | class Solution:
def deleteString(self, s: str) -> int:
n = len(s)
if len(set(s)) == 1:
return n
dp = [1] * n
for i in range(n - 2, -1, -1):
for l in range(1, (n - i) // 2 + 1):
if s[i : i + l] == s[i + l : i + 2 * l]:
dp[i] = max(dp[i], 1 + dp[i + l])
return dp[0] | https://leetcode.com/problems/maximum-deletions-on-a-string/discuss/2648661/Python3-Dynamic-Programming-Clean-and-Concise | 10 | You are given a string s consisting of only lowercase English letters. In one operation, you can:
Delete the entire string s, or
Delete the first i letters of s if the first i letters of s are equal to the following i letters in s, for any i in the range 1 <= i <= s.length / 2.
For example, if s = "ababc", then in one operation, you could delete the first two letters of s to get "abc", since the first two letters of s and the following two letters of s are both equal to "ab".
Return the maximum number of operations needed to delete all of s.
Example 1:
Input: s = "abcabcdabc"
Output: 2
Explanation:
- Delete the first 3 letters ("abc") since the next 3 letters are equal. Now, s = "abcdabc".
- Delete all the letters.
We used 2 operations so return 2. It can be proven that 2 is the maximum number of operations needed.
Note that in the second operation we cannot delete "abc" again because the next occurrence of "abc" does not happen in the next 3 letters.
Example 2:
Input: s = "aaabaab"
Output: 4
Explanation:
- Delete the first letter ("a") since the next letter is equal. Now, s = "aabaab".
- Delete the first 3 letters ("aab") since the next 3 letters are equal. Now, s = "aab".
- Delete the first letter ("a") since the next letter is equal. Now, s = "ab".
- Delete all the letters.
We used 4 operations so return 4. It can be proven that 4 is the maximum number of operations needed.
Example 3:
Input: s = "aaaaa"
Output: 5
Explanation: In each operation, we can delete the first letter of s.
Constraints:
1 <= s.length <= 4000
s consists only of lowercase English letters. | [Python3] Dynamic Programming, Clean & Concise | 1,000 | maximum-deletions-on-a-string | 0.322 | xil899 | Hard | 33,229 | 2,430 |
the employee that worked on the longest task | class Solution:
"""
Time: O(n)
Memory: O(1)
"""
def hardestWorker(self, n: int, logs: List[List[int]]) -> int:
best_id = best_time = start = 0
for emp_id, end in logs:
time = end - start
if time > best_time or (time == best_time and best_id > emp_id):
best_id = emp_id
best_time = time
start = end
return best_id | https://leetcode.com/problems/the-employee-that-worked-on-the-longest-task/discuss/2693491/Python-Elegant-and-Short-or-No-indexes-or-99.32-faster | 4 | There are n employees, each with a unique id from 0 to n - 1.
You are given a 2D integer array logs where logs[i] = [idi, leaveTimei] where:
idi is the id of the employee that worked on the ith task, and
leaveTimei is the time at which the employee finished the ith task. All the values leaveTimei are unique.
Note that the ith task starts the moment right after the (i - 1)th task ends, and the 0th task starts at time 0.
Return the id of the employee that worked the task with the longest time. If there is a tie between two or more employees, return the smallest id among them.
Example 1:
Input: n = 10, logs = [[0,3],[2,5],[0,9],[1,15]]
Output: 1
Explanation:
Task 0 started at 0 and ended at 3 with 3 units of times.
Task 1 started at 3 and ended at 5 with 2 units of times.
Task 2 started at 5 and ended at 9 with 4 units of times.
Task 3 started at 9 and ended at 15 with 6 units of times.
The task with the longest time is task 3 and the employee with id 1 is the one that worked on it, so we return 1.
Example 2:
Input: n = 26, logs = [[1,1],[3,7],[2,12],[7,17]]
Output: 3
Explanation:
Task 0 started at 0 and ended at 1 with 1 unit of times.
Task 1 started at 1 and ended at 7 with 6 units of times.
Task 2 started at 7 and ended at 12 with 5 units of times.
Task 3 started at 12 and ended at 17 with 5 units of times.
The tasks with the longest time is task 1. The employee that worked on it is 3, so we return 3.
Example 3:
Input: n = 2, logs = [[0,10],[1,20]]
Output: 0
Explanation:
Task 0 started at 0 and ended at 10 with 10 units of times.
Task 1 started at 10 and ended at 20 with 10 units of times.
The tasks with the longest time are tasks 0 and 1. The employees that worked on them are 0 and 1, so we return the smallest id 0.
Constraints:
2 <= n <= 500
1 <= logs.length <= 500
logs[i].length == 2
0 <= idi <= n - 1
1 <= leaveTimei <= 500
idi != idi+1
leaveTimei are sorted in a strictly increasing order. | Python Elegant & Short | No indexes | 99.32% faster | 47 | the-employee-that-worked-on-the-longest-task | 0.489 | Kyrylo-Ktl | Easy | 33,243 | 2,432 |
find the original array of prefix xor | class Solution:
def findArray(self, pref: List[int]) -> List[int]:
ans = [0 for i in range(len(pref))]
ans[0] = pref[0]
for i in range(1, len(pref)):
ans[i] = pref[i-1]^pref[i]
return ans | https://leetcode.com/problems/find-the-original-array-of-prefix-xor/discuss/2684467/Python-3-Easy-O(N)-Time-Greedy-Solution-Explained | 1 | 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 the answer is unique.
Example 1:
Input: pref = [5,2,0,3,1]
Output: [5,7,2,3,2]
Explanation: From the array [5,7,2,3,2] we have the following:
- pref[0] = 5.
- pref[1] = 5 ^ 7 = 2.
- pref[2] = 5 ^ 7 ^ 2 = 0.
- pref[3] = 5 ^ 7 ^ 2 ^ 3 = 3.
- pref[4] = 5 ^ 7 ^ 2 ^ 3 ^ 2 = 1.
Example 2:
Input: pref = [13]
Output: [13]
Explanation: We have pref[0] = arr[0] = 13.
Constraints:
1 <= pref.length <= 105
0 <= pref[i] <= 106 | [Python 3] Easy O(N) Time Greedy Solution Explained | 29 | find-the-original-array-of-prefix-xor | 0.857 | user2667O | Medium | 33,265 | 2,433 |
using a robot to print the lexicographically smallest string | class Solution:
def robotWithString(self, s: str) -> str:
cnt, lo, p, t = Counter(s), 'a', [], []
for ch in s:
t += ch
cnt[ch] -= 1
while lo < 'z' and cnt[lo] == 0:
lo = chr(ord(lo) + 1)
while t and t[-1] <= lo:
p += t.pop()
return "".join(p) | https://leetcode.com/problems/using-a-robot-to-print-the-lexicographically-smallest-string/discuss/2678810/Counter | 78 | You are given a string s and a robot that currently holds an empty string t. Apply one of the following operations until s and t are both empty:
Remove the first character of a string s and give it to the robot. The robot will append this character to the string t.
Remove the last character of a string t and give it to the robot. The robot will write this character on paper.
Return the lexicographically smallest string that can be written on the paper.
Example 1:
Input: s = "zza"
Output: "azz"
Explanation: Let p denote the written string.
Initially p="", s="zza", t="".
Perform first operation three times p="", s="", t="zza".
Perform second operation three times p="azz", s="", t="".
Example 2:
Input: s = "bac"
Output: "abc"
Explanation: Let p denote the written string.
Perform first operation twice p="", s="c", t="ba".
Perform second operation twice p="ab", s="c", t="".
Perform first operation p="ab", s="", t="c".
Perform second operation p="abc", s="", t="".
Example 3:
Input: s = "bdda"
Output: "addb"
Explanation: Let p denote the written string.
Initially p="", s="bdda", t="".
Perform first operation four times p="", s="", t="bdda".
Perform second operation four times p="addb", s="", t="".
Constraints:
1 <= s.length <= 105
s consists of only English lowercase letters. | Counter | 3,600 | using-a-robot-to-print-the-lexicographically-smallest-string | 0.381 | votrubac | Medium | 33,297 | 2,434 |
paths in matrix whose sum is divisible by k | class Solution:
def numberOfPaths(self, grid: List[List[int]], k: int) -> int:
dp = [[[0 for i in range(k)] for _ in range(len(grid[0]))] for _ in range(len(grid))]
rem = grid[0][0] % k
dp[0][0][rem] = 1
for i in range(1, len(grid[0])):
dp[0][i][(rem + grid[0][i]) % k] = 1
rem = (rem + grid[0][i]) % k
rem = grid[0][0] % k
for j in range(1, len(grid)):
dp[j][0][(rem + grid[j][0]) % k] = 1
rem = (rem + grid[j][0]) % k
for i in range(1, len(grid)):
for j in range(1, len(grid[0])):
for rem in range(k):
dp[i][j][(rem + grid[i][j]) % k] = dp[i - 1][j][rem] + dp[i][j - 1][rem]
return dp[-1][-1][0] % (10**9 + 7) | https://leetcode.com/problems/paths-in-matrix-whose-sum-is-divisible-by-k/discuss/2702890/Python-or-3d-dynamic-programming-approach-or-O(m*n*k) | 1 | You are given a 0-indexed m x n integer matrix grid and an integer k. You are currently at position (0, 0) and you want to reach position (m - 1, n - 1) moving only down or right.
Return the number of paths where the sum of the elements on the path is divisible by k. Since the answer may be very large, return it modulo 109 + 7.
Example 1:
Input: grid = [[5,2,4],[3,0,5],[0,7,2]], k = 3
Output: 2
Explanation: There are two paths where the sum of the elements on the path is divisible by k.
The first path highlighted in red has a sum of 5 + 2 + 4 + 5 + 2 = 18 which is divisible by 3.
The second path highlighted in blue has a sum of 5 + 3 + 0 + 5 + 2 = 15 which is divisible by 3.
Example 2:
Input: grid = [[0,0]], k = 5
Output: 1
Explanation: The path highlighted in red has a sum of 0 + 0 = 0 which is divisible by 5.
Example 3:
Input: grid = [[7,3,4,9],[2,3,6,2],[2,3,7,0]], k = 1
Output: 10
Explanation: Every integer is divisible by 1 so the sum of the elements on every possible path is divisible by k.
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 5 * 104
1 <= m * n <= 5 * 104
0 <= grid[i][j] <= 100
1 <= k <= 50 | Python | 3d dynamic programming approach | O(m*n*k) | 16 | paths-in-matrix-whose-sum-is-divisible-by-k | 0.41 | LordVader1 | Hard | 33,315 | 2,435 |
number of valid clock times | class Solution:
def countTime(self, t: str) -> int:
mm = (6 if t[3] == '?' else 1) * (10 if t[4] == '?' else 1)
match [t[0], t[1]]:
case ('?', '?'):
return mm * 24
case ('?', ('0' | '1' | '2' | '3')):
return mm * 3
case ('?', _):
return mm * 2
case (('0' | '1'), '?'):
return mm * 10
case (_, '?'):
return mm * 4
return mm | https://leetcode.com/problems/number-of-valid-clock-times/discuss/2706741/Structural-pattern-matching | 24 | You are given a string of length 5 called time, representing the current time on a digital clock in the format "hh:mm". The earliest possible time is "00:00" and the latest possible time is "23:59".
In the string time, the digits represented by the ? symbol are unknown, and must be replaced with a digit from 0 to 9.
Return an integer answer, the number of valid clock times that can be created by replacing every ? with a digit from 0 to 9.
Example 1:
Input: time = "?5:00"
Output: 2
Explanation: We can replace the ? with either a 0 or 1, producing "05:00" or "15:00". Note that we cannot replace it with a 2, since the time "25:00" is invalid. In total, we have two choices.
Example 2:
Input: time = "0?:0?"
Output: 100
Explanation: Each ? can be replaced by any digit from 0 to 9, so we have 100 total choices.
Example 3:
Input: time = "??:??"
Output: 1440
Explanation: There are 24 possible choices for the hours, and 60 possible choices for the minutes. In total, we have 24 * 60 = 1440 choices.
Constraints:
time is a valid string of length 5 in the format "hh:mm".
"00" <= hh <= "23"
"00" <= mm <= "59"
Some of the digits might be replaced with '?' and need to be replaced with digits from 0 to 9. | Structural pattern matching | 806 | number-of-valid-clock-times | 0.42 | votrubac | Easy | 33,331 | 2,437 |
range product queries of powers | class Solution:
def productQueries(self, n: int, queries: List[List[int]]) -> List[int]:
MOD = (10**9)+7
binary = bin(n)[2:]
powers = []
result = []
for index, val in enumerate(binary[::-1]):
if val == "1":
powers.append(2**index)
for index in range(1, len(powers)):
powers[index] = powers[index] * powers[index - 1]
for l,r in queries:
if l == 0:
result.append(powers[r]%MOD)
else:
result.append((powers[r]//powers[l-1])%MOD)
return result | https://leetcode.com/problems/range-product-queries-of-powers/discuss/2706690/Python-or-Prefix-Product | 8 | Given a positive integer n, there exists a 0-indexed array called powers, composed of the minimum number of powers of 2 that sum to n. The array is sorted in non-decreasing order, and there is only one way to form the array.
You are also given a 0-indexed 2D integer array queries, where queries[i] = [lefti, righti]. Each queries[i] represents a query where you have to find the product of all powers[j] with lefti <= j <= righti.
Return an array answers, equal in length to queries, where answers[i] is the answer to the ith query. Since the answer to the ith query may be too large, each answers[i] should be returned modulo 109 + 7.
Example 1:
Input: n = 15, queries = [[0,1],[2,2],[0,3]]
Output: [2,4,64]
Explanation:
For n = 15, powers = [1,2,4,8]. It can be shown that powers cannot be a smaller size.
Answer to 1st query: powers[0] * powers[1] = 1 * 2 = 2.
Answer to 2nd query: powers[2] = 4.
Answer to 3rd query: powers[0] * powers[1] * powers[2] * powers[3] = 1 * 2 * 4 * 8 = 64.
Each answer modulo 109 + 7 yields the same answer, so [2,4,64] is returned.
Example 2:
Input: n = 2, queries = [[0,0]]
Output: [2]
Explanation:
For n = 2, powers = [2].
The answer to the only query is powers[0] = 2. The answer modulo 109 + 7 is the same, so [2] is returned.
Constraints:
1 <= n <= 109
1 <= queries.length <= 105
0 <= starti <= endi < powers.length | Python | Prefix Product | 320 | range-product-queries-of-powers | 0.384 | Dhanush_krish | Medium | 33,359 | 2,438 |
minimize maximum of array | class Solution:
def minimizeArrayValue(self, nums: List[int]) -> int:
return max(ceil(n / (i + 1)) for i, n in enumerate(accumulate(nums))) | https://leetcode.com/problems/minimize-maximum-of-array/discuss/2706472/Average | 45 | You are given a 0-indexed array nums comprising of n non-negative integers.
In one operation, you must:
Choose an integer i such that 1 <= i < n and nums[i] > 0.
Decrease nums[i] by 1.
Increase nums[i - 1] by 1.
Return the minimum possible value of the maximum integer of nums after performing any number of operations.
Example 1:
Input: nums = [3,7,1,6]
Output: 5
Explanation:
One set of optimal operations is as follows:
1. Choose i = 1, and nums becomes [4,6,1,6].
2. Choose i = 3, and nums becomes [4,6,2,5].
3. Choose i = 1, and nums becomes [5,5,2,5].
The maximum integer of nums is 5. It can be shown that the maximum number cannot be less than 5.
Therefore, we return 5.
Example 2:
Input: nums = [10,1]
Output: 10
Explanation:
It is optimal to leave nums as is, and since 10 is the maximum value, we return 10.
Constraints:
n == nums.length
2 <= n <= 105
0 <= nums[i] <= 109 | Average | 2,800 | minimize-maximum-of-array | 0.331 | votrubac | Medium | 33,375 | 2,439 |
create components with same value | class Solution:
def componentValue(self, nums: List[int], edges: List[List[int]]) -> int:
tree = [[] for _ in nums]
for u, v in edges:
tree[u].append(v)
tree[v].append(u)
def fn(u, p):
"""Post-order dfs."""
ans = nums[u]
for v in tree[u]:
if v != p: ans += fn(v, u)
return 0 if ans == cand else ans
total = sum(nums)
for cand in range(1, total//2+1):
if total % cand == 0 and fn(0, -1) == 0: return total//cand-1
return 0 | https://leetcode.com/problems/create-components-with-same-value/discuss/2707304/Python3-post-order-dfs | 11 | There is an undirected tree with n nodes labeled from 0 to n - 1.
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] indicates that there is an edge between nodes ai and bi in the tree.
You are allowed to delete some edges, splitting the tree into multiple connected components. Let the value of a component be the sum of all nums[i] for which node i is in the component.
Return the maximum number of edges you can delete, such that every connected component in the tree has the same value.
Example 1:
Input: nums = [6,2,2,2,6], edges = [[0,1],[1,2],[1,3],[3,4]]
Output: 2
Explanation: The above figure shows how we can delete the edges [0,1] and [3,4]. The created components are nodes [0], [1,2,3] and [4]. The sum of the values in each component equals 6. It can be proven that no better deletion exists, so the answer is 2.
Example 2:
Input: nums = [2], edges = []
Output: 0
Explanation: There are no edges to be deleted.
Constraints:
1 <= n <= 2 * 104
nums.length == n
1 <= nums[i] <= 50
edges.length == n - 1
edges[i].length == 2
0 <= edges[i][0], edges[i][1] <= n - 1
edges represents a valid tree. | [Python3] post-order dfs | 264 | create-components-with-same-value | 0.543 | ye15 | Hard | 33,393 | 2,440 |
largest positive integer that exists with its negative | class Solution:
def findMaxK(self, nums: List[int]) -> int:
nums.sort()
for i in nums[::-1]:
if -i in nums:
return i
return -1 | https://leetcode.com/problems/largest-positive-integer-that-exists-with-its-negative/discuss/2774238/Easy-Python-Solution | 3 | Given an integer array nums that does not contain any zeros, find the largest positive integer k such that -k also exists in the array.
Return the positive integer k. If there is no such integer, return -1.
Example 1:
Input: nums = [-1,2,-3,3]
Output: 3
Explanation: 3 is the only valid k we can find in the array.
Example 2:
Input: nums = [-1,10,6,7,-7,1]
Output: 7
Explanation: Both 1 and 7 have their corresponding negative values in the array. 7 has a larger value.
Example 3:
Input: nums = [-10,8,6,7,-2,-3]
Output: -1
Explanation: There is no a single valid k, we return -1.
Constraints:
1 <= nums.length <= 1000
-1000 <= nums[i] <= 1000
nums[i] != 0 | Easy Python Solution | 64 | largest-positive-integer-that-exists-with-its-negative | 0.678 | Vistrit | Easy | 33,395 | 2,441 |
count number of distinct integers after reverse operations | class Solution:
def countDistinctIntegers(self, nums: List[int]) -> int:
return len(set([int(str(i)[::-1]) for i in nums] + nums)) | https://leetcode.com/problems/count-number-of-distinct-integers-after-reverse-operations/discuss/2708055/One-Liner-or-Explained | 5 | You are given an array nums consisting of positive integers.
You have to take each integer in the array, reverse its digits, and add it to the end of the array. You should apply this operation to the original integers in nums.
Return the number of distinct integers in the final array.
Example 1:
Input: nums = [1,13,10,12,31]
Output: 6
Explanation: After including the reverse of each number, the resulting array is [1,13,10,12,31,1,31,1,21,13].
The reversed integers that were added to the end of the array are underlined. Note that for the integer 10, after reversing it, it becomes 01 which is just 1.
The number of distinct integers in this array is 6 (The numbers 1, 10, 12, 13, 21, and 31).
Example 2:
Input: nums = [2,2,2]
Output: 1
Explanation: After including the reverse of each number, the resulting array is [2,2,2,2,2,2].
The number of distinct integers in this array is 1 (The number 2).
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 106 | One Liner | Explained | 427 | count-number-of-distinct-integers-after-reverse-operations | 0.788 | lukewu28 | Medium | 33,429 | 2,442 |
sum of number and its reverse | class Solution:
def sumOfNumberAndReverse(self, num: int) -> bool:
digits = []
while num > 0:
digits.append(num % 10)
num = num // 10
digits.reverse()
hi, lo = 0, len(digits) - 1
while hi <= lo:
if hi == lo:
if digits[hi] % 2 == 0:
break
else:
return False
if digits[hi] == digits[lo]:
hi += 1
lo -= 1
elif digits[hi] == 1 and digits[hi] != digits[lo]:
digits[hi] -= 1
digits[hi+1] += 10
hi += 1
if lo != hi:
digits[lo] += 10
digits[lo-1] -= 1
cur = lo - 1
while digits[cur] < 0:
digits[cur] = 0
digits[cur-1] -= 1
cur -= 1
elif digits[hi]-1 == digits[lo] and hi + 1 < lo:
digits[hi]-= 1
digits[hi+1] += 10
hi += 1
lo -= 1
# else:
# return False
elif digits[hi] - 1 == digits[lo] + 10 and hi + 1 < lo:
digits[hi] -= 1
digits[hi+1] += 10
digits[lo-1] -= 1
cur = lo - 1
while digits[cur] < 0:
digits[cur] = 0
digits[cur-1] -= 1
cur -= 1
digits[lo] += 10
elif hi-1>=0 and lo+1<=len(digits)-1 and digits[hi-1] == 1 and digits[lo+1] == 1:
digits[hi-1] -= 1
digits[hi] += 10
digits[lo+1] += 10
digits[lo] -= 1
cur = lo
while digits[cur] < 0:
digits[cur] = 0
digits[cur-1] -= 1
cur -= 1
lo += 1
else:
return False
return True | https://leetcode.com/problems/sum-of-number-and-its-reverse/discuss/2708439/Python3-O(-digits)-solution-beats-100-47ms | 2 | Given a non-negative integer num, return true if num can be expressed as the sum of any non-negative integer and its reverse, or false otherwise.
Example 1:
Input: num = 443
Output: true
Explanation: 172 + 271 = 443 so we return true.
Example 2:
Input: num = 63
Output: false
Explanation: 63 cannot be expressed as the sum of a non-negative integer and its reverse so we return false.
Example 3:
Input: num = 181
Output: true
Explanation: 140 + 041 = 181 so we return true. Note that when a number is reversed, there may be leading zeros.
Constraints:
0 <= num <= 105 | [Python3] O(# digits) solution beats 100% 47ms | 326 | sum-of-number-and-its-reverse | 0.453 | jfang2021 | Medium | 33,466 | 2,443 |
count subarrays with fixed bounds | class Solution:
def countSubarrays(self, nums: List[int], minK: int, maxK: int) -> int:
if minK > maxK: return 0
def count(l, r):
if l + 1 == r: return 0
dic = Counter([nums[l]])
ans, j = 0, l + 1
for i in range(l + 1, r):
dic[nums[i - 1]] -= 1
while not dic[minK] * dic[maxK] and j < r:
dic[nums[j]] += 1
j += 1
if dic[minK] * dic[maxK]: ans += r - j + 1
else: break
return ans
arr = [-1] + [i for i, num in enumerate(nums) if num < minK or num > maxK] + [len(nums)]
return sum(count(arr[i - 1], arr[i]) for i in range(1, len(arr))) | https://leetcode.com/problems/count-subarrays-with-fixed-bounds/discuss/2708034/Python3-Sliding-Window-O(N)-with-Explanations | 1 | You are given an integer array nums and two integers minK and maxK.
A fixed-bound subarray of nums is a subarray that satisfies the following conditions:
The minimum value in the subarray is equal to minK.
The maximum value in the subarray is equal to maxK.
Return the number of fixed-bound subarrays.
A subarray is a contiguous part of an array.
Example 1:
Input: nums = [1,3,5,2,7,5], minK = 1, maxK = 5
Output: 2
Explanation: The fixed-bound subarrays are [1,3,5] and [1,3,5,2].
Example 2:
Input: nums = [1,1,1,1], minK = 1, maxK = 1
Output: 10
Explanation: Every subarray of nums is a fixed-bound subarray. There are 10 possible subarrays.
Constraints:
2 <= nums.length <= 105
1 <= nums[i], minK, maxK <= 106 | [Python3] Sliding Window O(N) with Explanations | 97 | count-subarrays-with-fixed-bounds | 0.432 | xil899 | Hard | 33,498 | 2,444 |
determine if two events have conflict | class Solution:
"""
Time: O(1)
Memory: O(1)
"""
def haveConflict(self, a: List[str], b: List[str]) -> bool:
a_start, a_end = a
b_start, b_end = b
return b_start <= a_start <= b_end or \
b_start <= a_end <= b_end or \
a_start <= b_start <= a_end or \
a_start <= b_end <= a_end | https://leetcode.com/problems/determine-if-two-events-have-conflict/discuss/2744018/Python-Elegant-and-Short | 3 | You are given two arrays of strings that represent two inclusive events that happened on the same day, event1 and event2, where:
event1 = [startTime1, endTime1] and
event2 = [startTime2, endTime2].
Event times are valid 24 hours format in the form of HH:MM.
A conflict happens when two events have some non-empty intersection (i.e., some moment is common to both events).
Return true if there is a conflict between two events. Otherwise, return false.
Example 1:
Input: event1 = ["01:15","02:00"], event2 = ["02:00","03:00"]
Output: true
Explanation: The two events intersect at time 2:00.
Example 2:
Input: event1 = ["01:00","02:00"], event2 = ["01:20","03:00"]
Output: true
Explanation: The two events intersect starting from 01:20 to 02:00.
Example 3:
Input: event1 = ["10:00","11:00"], event2 = ["14:00","15:00"]
Output: false
Explanation: The two events do not intersect.
Constraints:
event1.length == event2.length == 2
event1[i].length == event2[i].length == 5
startTime1 <= endTime1
startTime2 <= endTime2
All the event times follow the HH:MM format. | Python Elegant & Short | 79 | determine-if-two-events-have-conflict | 0.494 | Kyrylo-Ktl | Easy | 33,507 | 2,446 |
number of subarrays with gcd equal to k | class Solution:
def subarrayGCD(self, nums: List[int], k: int) -> int:
n = len(nums)
ans = 0
for i in range(n):
temp = nums[i]
for j in range(i, n):
temp = math.gcd(temp, nums[j])
if temp == k:
ans += 1
elif temp < k:
break
return ans | https://leetcode.com/problems/number-of-subarrays-with-gcd-equal-to-k/discuss/2734224/Python3-Brute-Force-%2B-Early-Stopping-Clean-and-Concise | 4 | Given an integer array nums and an integer k, return the number of subarrays of nums where the greatest common divisor of the subarray's elements is k.
A subarray is a contiguous non-empty sequence of elements within an array.
The greatest common divisor of an array is the largest integer that evenly divides all the array elements.
Example 1:
Input: nums = [9,3,1,2,6,3], k = 3
Output: 4
Explanation: The subarrays of nums where 3 is the greatest common divisor of all the subarray's elements are:
- [9,3,1,2,6,3]
- [9,3,1,2,6,3]
- [9,3,1,2,6,3]
- [9,3,1,2,6,3]
Example 2:
Input: nums = [4], k = 7
Output: 0
Explanation: There are no subarrays of nums where 7 is the greatest common divisor of all the subarray's elements.
Constraints:
1 <= nums.length <= 1000
1 <= nums[i], k <= 109 | [Python3] Brute Force + Early Stopping, Clean & Concise | 423 | number-of-subarrays-with-gcd-equal-to-k | 0.482 | xil899 | Medium | 33,524 | 2,447 |
minimum cost to make array equal | class Solution:
def minCost(self, nums: List[int], cost: List[int]) -> int:
arr = sorted(zip(nums, cost))
total, cnt = sum(cost), 0
for num, c in arr:
cnt += c
if cnt > total // 2:
target = num
break
return sum(c * abs(num - target) for num, c in arr) | https://leetcode.com/problems/minimum-cost-to-make-array-equal/discuss/2734183/Python3-Weighted-Median-O(NlogN)-with-Explanations | 109 | You are given two 0-indexed arrays nums and cost consisting each of n positive integers.
You can do the following operation any number of times:
Increase or decrease any element of the array nums by 1.
The cost of doing one operation on the ith element is cost[i].
Return the minimum total cost such that all the elements of the array nums become equal.
Example 1:
Input: nums = [1,3,5,2], cost = [2,3,1,14]
Output: 8
Explanation: We can make all the elements equal to 2 in the following way:
- Increase the 0th element one time. The cost is 2.
- Decrease the 1st element one time. The cost is 3.
- Decrease the 2nd element three times. The cost is 1 + 1 + 1 = 3.
The total cost is 2 + 3 + 3 = 8.
It can be shown that we cannot make the array equal with a smaller cost.
Example 2:
Input: nums = [2,2,2,2,2], cost = [4,2,8,1,3]
Output: 0
Explanation: All the elements are already equal, so no operations are needed.
Constraints:
n == nums.length == cost.length
1 <= n <= 105
1 <= nums[i], cost[i] <= 106
Test cases are generated in a way that the output doesn't exceed 253-1 | [Python3] Weighted Median O(NlogN) with Explanations | 2,300 | minimum-cost-to-make-array-equal | 0.346 | xil899 | Hard | 33,535 | 2,448 |