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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
minimum absolute difference queries | class Solution:
def minDifference(self, nums: List[int], queries: List[List[int]]) -> List[int]:
loc = {}
for i, x in enumerate(nums): loc.setdefault(x, []).append(i)
keys = sorted(loc)
ans = []
for l, r in queries:
prev, val = 0, inf
for x in keys:
i = bisect_left(loc[x], l)
if i < len(loc[x]) and loc[x][i] <= r:
if prev: val = min(val, x - prev)
prev = x
ans.append(val if val < inf else -1)
return ans | https://leetcode.com/problems/minimum-absolute-difference-queries/discuss/1284341/Python3-binary-search | 8 | The minimum absolute difference of an array a is defined as the minimum value of |a[i] - a[j]|, where 0 <= i < j < a.length and a[i] != a[j]. If all elements of a are the same, the minimum absolute difference is -1.
For example, the minimum absolute difference of the array [5,2,3,7,2] is |2 - 3| = 1. Note that it is not 0 because a[i] and a[j] must be different.
You are given an integer array nums and the array queries where queries[i] = [li, ri]. For each query i, compute the minimum absolute difference of the subarray nums[li...ri] containing the elements of nums between the 0-based indices li and ri (inclusive).
Return an array ans where ans[i] is the answer to the ith query.
A subarray is a contiguous sequence of elements in an array.
The value of |x| is defined as:
x if x >= 0.
-x if x < 0.
Example 1:
Input: nums = [1,3,4,8], queries = [[0,1],[1,2],[2,3],[0,3]]
Output: [2,1,4,1]
Explanation: The queries are processed as follows:
- queries[0] = [0,1]: The subarray is [1,3] and the minimum absolute difference is |1-3| = 2.
- queries[1] = [1,2]: The subarray is [3,4] and the minimum absolute difference is |3-4| = 1.
- queries[2] = [2,3]: The subarray is [4,8] and the minimum absolute difference is |4-8| = 4.
- queries[3] = [0,3]: The subarray is [1,3,4,8] and the minimum absolute difference is |3-4| = 1.
Example 2:
Input: nums = [4,5,2,2,7,10], queries = [[2,3],[0,2],[0,5],[3,5]]
Output: [-1,1,1,3]
Explanation: The queries are processed as follows:
- queries[0] = [2,3]: The subarray is [2,2] and the minimum absolute difference is -1 because all the
elements are the same.
- queries[1] = [0,2]: The subarray is [4,5,2] and the minimum absolute difference is |4-5| = 1.
- queries[2] = [0,5]: The subarray is [4,5,2,2,7,10] and the minimum absolute difference is |4-5| = 1.
- queries[3] = [3,5]: The subarray is [2,7,10] and the minimum absolute difference is |7-10| = 3.
Constraints:
2 <= nums.length <= 105
1 <= nums[i] <= 100
1 <= queries.length <= 2 * 104
0 <= li < ri < nums.length | [Python3] binary search | 681 | minimum-absolute-difference-queries | 0.439 | ye15 | Medium | 26,966 | 1,906 |
remove one element to make the array strictly increasing | class Solution:
def canBeIncreasing(self, nums: List[int]) -> bool:
stack = []
for i in range(1, len(nums)):
if nums[i-1] >= nums[i]: stack.append(i)
if not stack: return True
if len(stack) > 1: return False
i = stack[0]
return (i == 1 or nums[i-2] < nums[i]) or (i+1 == len(nums) or nums[i-1] < nums[i+1]) | https://leetcode.com/problems/remove-one-element-to-make-the-array-strictly-increasing/discuss/1298457/Python3-collect-non-conforming-indices | 15 | Given a 0-indexed integer array nums, return true if it can be made strictly increasing after removing exactly one element, or false otherwise. If the array is already strictly increasing, return true.
The array nums is strictly increasing if nums[i - 1] < nums[i] for each index (1 <= i < nums.length).
Example 1:
Input: nums = [1,2,10,5,7]
Output: true
Explanation: By removing 10 at index 2 from nums, it becomes [1,2,5,7].
[1,2,5,7] is strictly increasing, so return true.
Example 2:
Input: nums = [2,3,1,2]
Output: false
Explanation:
[3,1,2] is the result of removing the element at index 0.
[2,1,2] is the result of removing the element at index 1.
[2,3,2] is the result of removing the element at index 2.
[2,3,1] is the result of removing the element at index 3.
No resulting array is strictly increasing, so return false.
Example 3:
Input: nums = [1,1,1]
Output: false
Explanation: The result of removing any element is [1,1].
[1,1] is not strictly increasing, so return false.
Constraints:
2 <= nums.length <= 1000
1 <= nums[i] <= 1000 | [Python3] collect non-conforming indices | 1,200 | remove-one-element-to-make-the-array-strictly-increasing | 0.26 | ye15 | Easy | 26,967 | 1,909 |
remove all occurrences of a substring | class Solution:
def removeOccurrences(self, s: str, part: str) -> str:
lps = [0]
k = 0
for i in range(1, len(part)):
while k and part[k] != part[i]: k = lps[k-1]
if part[k] == part[i]: k += 1
lps.append(k)
stack = [("", 0)]
for ch in s:
k = stack[-1][1]
while k and part[k] != ch: k = lps[k-1]
if part[k] == ch: k += 1
stack.append((ch, k))
if k == len(part):
for _ in range(len(part)): stack.pop()
return "".join(x for x, _ in stack) | https://leetcode.com/problems/remove-all-occurrences-of-a-substring/discuss/1298899/Python3-kmp | 9 | Given two strings s and part, perform the following operation on s until all occurrences of the substring part are removed:
Find the leftmost occurrence of the substring part and remove it from s.
Return s after removing all occurrences of part.
A substring is a contiguous sequence of characters in a string.
Example 1:
Input: s = "daabcbaabcbc", part = "abc"
Output: "dab"
Explanation: The following operations are done:
- s = "daabcbaabcbc", remove "abc" starting at index 2, so s = "dabaabcbc".
- s = "dabaabcbc", remove "abc" starting at index 4, so s = "dababc".
- s = "dababc", remove "abc" starting at index 3, so s = "dab".
Now s has no occurrences of "abc".
Example 2:
Input: s = "axxxxyyyyb", part = "xy"
Output: "ab"
Explanation: The following operations are done:
- s = "axxxxyyyyb", remove "xy" starting at index 4 so s = "axxxyyyb".
- s = "axxxyyyb", remove "xy" starting at index 3 so s = "axxyyb".
- s = "axxyyb", remove "xy" starting at index 2 so s = "axyb".
- s = "axyb", remove "xy" starting at index 1 so s = "ab".
Now s has no occurrences of "xy".
Constraints:
1 <= s.length <= 1000
1 <= part.length <= 1000
s and part consists of lowercase English letters. | [Python3] kmp | 955 | remove-all-occurrences-of-a-substring | 0.742 | ye15 | Medium | 26,988 | 1,910 |
maximum alternating subsequence sum | class Solution:
def maxAlternatingSum(self, nums: List[int]) -> int:
ma=0
mi=0
for num in nums:
ma=max(ma,num-mi)
mi=min(mi,num-ma)
return ma | https://leetcode.com/problems/maximum-alternating-subsequence-sum/discuss/1298531/4-lines-oror-96-faster-oror-Easy-approach | 7 | The alternating sum of a 0-indexed array is defined as the sum of the elements at even indices minus the sum of the elements at odd indices.
For example, the alternating sum of [4,2,5,3] is (4 + 5) - (2 + 3) = 4.
Given an array nums, return the maximum alternating sum of any subsequence of nums (after reindexing the elements of the subsequence).
A subsequence of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order. For example, [2,7,4] is a subsequence of [4,2,3,7,2,1,4] (the underlined elements), while [2,4,2] is not.
Example 1:
Input: nums = [4,2,5,3]
Output: 7
Explanation: It is optimal to choose the subsequence [4,2,5] with alternating sum (4 + 5) - 2 = 7.
Example 2:
Input: nums = [5,6,7,8]
Output: 8
Explanation: It is optimal to choose the subsequence [8] with alternating sum 8.
Example 3:
Input: nums = [6,2,1,2,4,5]
Output: 10
Explanation: It is optimal to choose the subsequence [6,1,5] with alternating sum (6 + 5) - 1 = 10.
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 105 | π 4 lines || 96% faster || Easy-approach π | 358 | maximum-alternating-subsequence-sum | 0.593 | abhi9Rai | Medium | 27,014 | 1,911 |
maximum product difference between two pairs | class Solution:
def maxProductDifference(self, nums: List[int]) -> int:
nums.sort()
return (nums[-1]*nums[-2])-(nums[0]*nums[1]) | https://leetcode.com/problems/maximum-product-difference-between-two-pairs/discuss/2822079/Python-oror-96.20-Faster-oror-2-Lines-oror-Sorting | 1 | The product difference between two pairs (a, b) and (c, d) is defined as (a * b) - (c * d).
For example, the product difference between (5, 6) and (2, 7) is (5 * 6) - (2 * 7) = 16.
Given an integer array nums, choose four distinct indices w, x, y, and z such that the product difference between pairs (nums[w], nums[x]) and (nums[y], nums[z]) is maximized.
Return the maximum such product difference.
Example 1:
Input: nums = [5,6,2,7,4]
Output: 34
Explanation: We can choose indices 1 and 3 for the first pair (6, 7) and indices 2 and 4 for the second pair (2, 4).
The product difference is (6 * 7) - (2 * 4) = 34.
Example 2:
Input: nums = [4,2,5,9,7,4,8]
Output: 64
Explanation: We can choose indices 3 and 6 for the first pair (9, 8) and indices 1 and 5 for the second pair (2, 4).
The product difference is (9 * 8) - (2 * 4) = 64.
Constraints:
4 <= nums.length <= 104
1 <= nums[i] <= 104 | Python || 96.20% Faster || 2 Lines || Sorting | 44 | maximum-product-difference-between-two-pairs | 0.814 | DareDevil_007 | Easy | 27,027 | 1,913 |
cyclically rotating a grid | class Solution:
def rotateGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
m, n = len(grid), len(grid[0]) # dimensions
for r in range(min(m, n)//2):
i = j = r
vals = []
for jj in range(j, n-j-1): vals.append(grid[i][jj])
for ii in range(i, m-i-1): vals.append(grid[ii][n-j-1])
for jj in range(n-j-1, j, -1): vals.append(grid[m-i-1][jj])
for ii in range(m-i-1, i, -1): vals.append(grid[ii][j])
kk = k % len(vals)
vals = vals[kk:] + vals[:kk]
x = 0
for jj in range(j, n-j-1): grid[i][jj] = vals[x]; x += 1
for ii in range(i, m-i-1): grid[ii][n-j-1] = vals[x]; x += 1
for jj in range(n-j-1, j, -1): grid[m-i-1][jj] = vals[x]; x += 1
for ii in range(m-i-1, i, -1): grid[ii][j] = vals[x]; x += 1
return grid | https://leetcode.com/problems/cyclically-rotating-a-grid/discuss/1299526/Python3-brute-force | 24 | You are given an m x n integer matrix grid, where m and n are both even integers, and an integer k.
The matrix is composed of several layers, which is shown in the below image, where each color is its own layer:
A cyclic rotation of the matrix is done by cyclically rotating each layer in the matrix. To cyclically rotate a layer once, each element in the layer will take the place of the adjacent element in the counter-clockwise direction. An example rotation is shown below:
Return the matrix after applying k cyclic rotations to it.
Example 1:
Input: grid = [[40,10],[30,20]], k = 1
Output: [[10,20],[40,30]]
Explanation: The figures above represent the grid at every state.
Example 2:
Input: grid = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]], k = 2
Output: [[3,4,8,12],[2,11,10,16],[1,7,6,15],[5,9,13,14]]
Explanation: The figures above represent the grid at every state.
Constraints:
m == grid.length
n == grid[i].length
2 <= m, n <= 50
Both m and n are even integers.
1 <= grid[i][j] <= 5000
1 <= k <= 109 | [Python3] brute-force | 988 | cyclically-rotating-a-grid | 0.481 | ye15 | Medium | 27,068 | 1,914 |
number of wonderful substrings | class Solution:
def wonderfulSubstrings(self, word: str) -> int:
ans = mask = 0
freq = defaultdict(int, {0: 1})
for ch in word:
mask ^= 1 << ord(ch)-97
ans += freq[mask]
for i in range(10): ans += freq[mask ^ 1 << i]
freq[mask] += 1
return ans | https://leetcode.com/problems/number-of-wonderful-substrings/discuss/1299537/Python3-freq-table-w.-mask | 11 | A wonderful string is a string where at most one letter appears an odd number of times.
For example, "ccjjc" and "abab" are wonderful, but "ab" is not.
Given a string word that consists of the first ten lowercase English letters ('a' through 'j'), return the number of wonderful non-empty substrings in word. If the same substring appears multiple times in word, then count each occurrence separately.
A substring is a contiguous sequence of characters in a string.
Example 1:
Input: word = "aba"
Output: 4
Explanation: The four wonderful substrings are underlined below:
- "aba" -> "a"
- "aba" -> "b"
- "aba" -> "a"
- "aba" -> "aba"
Example 2:
Input: word = "aabb"
Output: 9
Explanation: The nine wonderful substrings are underlined below:
- "aabb" -> "a"
- "aabb" -> "aa"
- "aabb" -> "aab"
- "aabb" -> "aabb"
- "aabb" -> "a"
- "aabb" -> "abb"
- "aabb" -> "b"
- "aabb" -> "bb"
- "aabb" -> "b"
Example 3:
Input: word = "he"
Output: 2
Explanation: The two wonderful substrings are underlined below:
- "he" -> "h"
- "he" -> "e"
Constraints:
1 <= word.length <= 105
word consists of lowercase English letters from 'a' to 'j'. | [Python3] freq table w. mask | 678 | number-of-wonderful-substrings | 0.45 | ye15 | Medium | 27,076 | 1,915 |
count ways to build rooms in an ant colony | class Solution:
def waysToBuildRooms(self, prevRoom: List[int]) -> int:
tree = defaultdict(list)
for i, x in enumerate(prevRoom): tree[x].append(i)
def fn(n):
"""Return number of nodes and ways to build sub-tree."""
if not tree[n]: return 1, 1 # leaf
c, m = 0, 1
for nn in tree[n]:
cc, mm = fn(nn)
c += cc
m = (m * comb(c, cc) * mm) % 1_000_000_007
return c+1, m
return fn(0)[1] | https://leetcode.com/problems/count-ways-to-build-rooms-in-an-ant-colony/discuss/1299545/Python3-post-order-dfs | 8 | You are an ant tasked with adding n new rooms numbered 0 to n-1 to your colony. You are given the expansion plan as a 0-indexed integer array of length n, prevRoom, where prevRoom[i] indicates that you must build room prevRoom[i] before building room i, and these two rooms must be connected directly. Room 0 is already built, so prevRoom[0] = -1. The expansion plan is given such that once all the rooms are built, every room will be reachable from room 0.
You can only build one room at a time, and you can travel freely between rooms you have already built only if they are connected. You can choose to build any room as long as its previous room is already built.
Return the number of different orders you can build all the rooms in. Since the answer may be large, return it modulo 109 + 7.
Example 1:
Input: prevRoom = [-1,0,1]
Output: 1
Explanation: There is only one way to build the additional rooms: 0 β 1 β 2
Example 2:
Input: prevRoom = [-1,0,0,1,2]
Output: 6
Explanation:
The 6 ways are:
0 β 1 β 3 β 2 β 4
0 β 2 β 4 β 1 β 3
0 β 1 β 2 β 3 β 4
0 β 1 β 2 β 4 β 3
0 β 2 β 1 β 3 β 4
0 β 2 β 1 β 4 β 3
Constraints:
n == prevRoom.length
2 <= n <= 105
prevRoom[0] == -1
0 <= prevRoom[i] < n for all 1 <= i < n
Every room is reachable from room 0 once all the rooms are built. | [Python3] post-order dfs | 762 | count-ways-to-build-rooms-in-an-ant-colony | 0.493 | ye15 | Hard | 27,079 | 1,916 |
build array from permutation | class Solution:
def buildArray(self, nums: List[int]) -> List[int]:
return [nums[nums[i]] for i in range(len(nums))] | https://leetcode.com/problems/build-array-from-permutation/discuss/1314345/Python3-1-line | 11 | Given a zero-based permutation nums (0-indexed), build an array ans of the same length where ans[i] = nums[nums[i]] for each 0 <= i < nums.length and return it.
A zero-based permutation nums is an array of distinct integers from 0 to nums.length - 1 (inclusive).
Example 1:
Input: nums = [0,2,1,5,3,4]
Output: [0,1,2,4,5,3]
Explanation: The array ans is built as follows:
ans = [nums[nums[0]], nums[nums[1]], nums[nums[2]], nums[nums[3]], nums[nums[4]], nums[nums[5]]]
= [nums[0], nums[2], nums[1], nums[5], nums[3], nums[4]]
= [0,1,2,4,5,3]
Example 2:
Input: nums = [5,0,1,2,3,4]
Output: [4,5,0,1,2,3]
Explanation: The array ans is built as follows:
ans = [nums[nums[0]], nums[nums[1]], nums[nums[2]], nums[nums[3]], nums[nums[4]], nums[nums[5]]]
= [nums[5], nums[0], nums[1], nums[2], nums[3], nums[4]]
= [4,5,0,1,2,3]
Constraints:
1 <= nums.length <= 1000
0 <= nums[i] < nums.length
The elements in nums are distinct.
Follow-up: Can you solve it without using an extra space (i.e., O(1) memory)? | [Python3] 1-line | 1,800 | build-array-from-permutation | 0.912 | ye15 | Easy | 27,080 | 1,920 |
eliminate maximum number of monsters | class Solution:
def eliminateMaximum(self, dist: List[int], speed: List[int]) -> int:
for i, t in enumerate(sorted((d+s-1)//s for d, s in zip(dist, speed))):
if i == t: return i
return len(dist) | https://leetcode.com/problems/eliminate-maximum-number-of-monsters/discuss/1314370/Python3-3-line | 4 | You are playing a video game where you are defending your city from a group of n monsters. You are given a 0-indexed integer array dist of size n, where dist[i] is the initial distance in kilometers of the ith monster from the city.
The monsters walk toward the city at a constant speed. The speed of each monster is given to you in an integer array speed of size n, where speed[i] is the speed of the ith monster in kilometers per minute.
You have a weapon that, once fully charged, can eliminate a single monster. However, the weapon takes one minute to charge. The weapon is fully charged at the very start.
You lose when any monster reaches your city. If a monster reaches the city at the exact moment the weapon is fully charged, it counts as a loss, and the game ends before you can use your weapon.
Return the maximum number of monsters that you can eliminate before you lose, or n if you can eliminate all the monsters before they reach the city.
Example 1:
Input: dist = [1,3,4], speed = [1,1,1]
Output: 3
Explanation:
In the beginning, the distances of the monsters are [1,3,4]. You eliminate the first monster.
After a minute, the distances of the monsters are [X,2,3]. You eliminate the second monster.
After a minute, the distances of the monsters are [X,X,2]. You eliminate the third monster.
All 3 monsters can be eliminated.
Example 2:
Input: dist = [1,1,2,3], speed = [1,1,1,1]
Output: 1
Explanation:
In the beginning, the distances of the monsters are [1,1,2,3]. You eliminate the first monster.
After a minute, the distances of the monsters are [X,0,1,2], so you lose.
You can only eliminate 1 monster.
Example 3:
Input: dist = [3,2,4], speed = [5,3,2]
Output: 1
Explanation:
In the beginning, the distances of the monsters are [3,2,4]. You eliminate the first monster.
After a minute, the distances of the monsters are [X,0,2], so you lose.
You can only eliminate 1 monster.
Constraints:
n == dist.length == speed.length
1 <= n <= 105
1 <= dist[i], speed[i] <= 105 | [Python3] 3-line | 312 | eliminate-maximum-number-of-monsters | 0.379 | ye15 | Medium | 27,128 | 1,921 |
count good numbers | class Solution:
def countGoodNumbers(self, n: int) -> int:
'''
ans=1
MOD=int(10**9+7)
for i in range(n):
if i%2==0:
ans*=5
else:
ans*=4
ans%=MOD
return ans
'''
MOD=int(10**9+7)
fives,fours=n//2+n%2,n//2
# 5^fives*4^fours % MOD
# = 5^fives % MOD * 4^fours % MOD
return (pow(5,fives,MOD) * pow(4,fours,MOD)) % MOD | https://leetcode.com/problems/count-good-numbers/discuss/1314484/Python3-Powermod-hack-3-lines | 5 | A digit string is good if the digits (0-indexed) at even indices are even and the digits at odd indices are prime (2, 3, 5, or 7).
For example, "2582" is good because the digits (2 and 8) at even positions are even and the digits (5 and 2) at odd positions are prime. However, "3245" is not good because 3 is at an even index but is not even.
Given an integer n, return the total number of good digit strings of length n. Since the answer may be large, return it modulo 109 + 7.
A digit string is a string consisting of digits 0 through 9 that may contain leading zeros.
Example 1:
Input: n = 1
Output: 5
Explanation: The good numbers of length 1 are "0", "2", "4", "6", "8".
Example 2:
Input: n = 4
Output: 400
Example 3:
Input: n = 50
Output: 564908303
Constraints:
1 <= n <= 1015 | [Python3] Powermod hack, 3 lines | 396 | count-good-numbers | 0.384 | mikeyliu | Medium | 27,137 | 1,922 |
count square sum triples | ```class Solution:
def countTriples(self, n: int) -> int:
count = 0
sqrt = 0
for i in range(1,n-1):
for j in range(i+1, n):
sqrt = ((i*i) + (j*j)) ** 0.5
if sqrt % 1 == 0 and sqrt <= n:
count += 2
return (count)
*Please Upvote if you like* | https://leetcode.com/problems/count-square-sum-triples/discuss/2318104/Easy-Solution-oror-PYTHON | 2 | A square triple (a,b,c) is a triple where a, b, and c are integers and a2 + b2 = c2.
Given an integer n, return the number of square triples such that 1 <= a, b, c <= n.
Example 1:
Input: n = 5
Output: 2
Explanation: The square triples are (3,4,5) and (4,3,5).
Example 2:
Input: n = 10
Output: 4
Explanation: The square triples are (3,4,5), (4,3,5), (6,8,10), and (8,6,10).
Constraints:
1 <= n <= 250 | Easy Solution || PYTHON | 134 | count-square-sum-triples | 0.68 | Jonny69 | Easy | 27,145 | 1,925 |
nearest exit from entrance in maze | class Solution:
def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int:
q = collections.deque([(*entrance, 0)])
m, n = len(maze), len(maze[0])
maze[entrance[0]][entrance[1]] == '+'
while q:
x, y, c = q.popleft()
if (x == 0 or x == m-1 or y == 0 or y == n-1) and [x, y] != entrance:
return c
for i, j in [(x+_x, y+_y) for _x, _y in [(-1, 0), (1, 0), (0, -1), (0, 1)]]:
if 0 <= i < m and 0 <= j < n and maze[i][j] == '.':
maze[i][j] = '+'
q.append((i, j, c + 1))
return -1 | https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/discuss/1329534/Python-3-or-BFS-Deque-In-place-or-Explanation | 5 | You are given an m x n matrix maze (0-indexed) with empty cells (represented as '.') and walls (represented as '+'). You are also given the entrance of the maze, where entrance = [entrancerow, entrancecol] denotes the row and column of the cell you are initially standing at.
In one step, you can move one cell up, down, left, or right. You cannot step into a cell with a wall, and you cannot step outside the maze. Your goal is to find the nearest exit from the entrance. An exit is defined as an empty cell that is at the border of the maze. The entrance does not count as an exit.
Return the number of steps in the shortest path from the entrance to the nearest exit, or -1 if no such path exists.
Example 1:
Input: maze = [["+","+",".","+"],[".",".",".","+"],["+","+","+","."]], entrance = [1,2]
Output: 1
Explanation: There are 3 exits in this maze at [1,0], [0,2], and [2,3].
Initially, you are at the entrance cell [1,2].
- You can reach [1,0] by moving 2 steps left.
- You can reach [0,2] by moving 1 step up.
It is impossible to reach [2,3] from the entrance.
Thus, the nearest exit is [0,2], which is 1 step away.
Example 2:
Input: maze = [["+","+","+"],[".",".","."],["+","+","+"]], entrance = [1,0]
Output: 2
Explanation: There is 1 exit in this maze at [1,2].
[1,0] does not count as an exit since it is the entrance cell.
Initially, you are at the entrance cell [1,0].
- You can reach [1,2] by moving 2 steps right.
Thus, the nearest exit is [1,2], which is 2 steps away.
Example 3:
Input: maze = [[".","+"]], entrance = [0,0]
Output: -1
Explanation: There are no exits in this maze.
Constraints:
maze.length == m
maze[i].length == n
1 <= m, n <= 100
maze[i][j] is either '.' or '+'.
entrance.length == 2
0 <= entrancerow < m
0 <= entrancecol < n
entrance will always be an empty cell. | Python 3 | BFS, Deque, In-place | Explanation | 197 | nearest-exit-from-entrance-in-maze | 0.49 | idontknoooo | Medium | 27,157 | 1,926 |
sum game | class Solution:
def sumGame(self, num: str) -> bool:
n = len(num)
q_cnt_1 = s1 = 0
for i in range(n//2): # get digit sum and question mark count for the first half of `num`
if num[i] == '?':
q_cnt_1 += 1
else:
s1 += int(num[i])
q_cnt_2 = s2 = 0
for i in range(n//2, n): # get digit sum and question mark count for the second half of `num`
if num[i] == '?':
q_cnt_2 += 1
else:
s2 += int(num[i])
s_diff = s1 - s2 # calculate sum difference and question mark difference
q_diff = q_cnt_2 - q_cnt_1
return not (q_diff % 2 == 0 and q_diff // 2 * 9 == s_diff) # When Bob can't win, Alice wins | https://leetcode.com/problems/sum-game/discuss/1330360/Python-3-or-Simple-Math-or-Explanation | 16 | Alice and Bob take turns playing a game, with Alice starting first.
You are given a string num of even length consisting of digits and '?' characters. On each turn, a player will do the following if there is still at least one '?' in num:
Choose an index i where num[i] == '?'.
Replace num[i] with any digit between '0' and '9'.
The game ends when there are no more '?' characters in num.
For Bob to win, the sum of the digits in the first half of num must be equal to the sum of the digits in the second half. For Alice to win, the sums must not be equal.
For example, if the game ended with num = "243801", then Bob wins because 2+4+3 = 8+0+1. If the game ended with num = "243803", then Alice wins because 2+4+3 != 8+0+3.
Assuming Alice and Bob play optimally, return true if Alice will win and false if Bob will win.
Example 1:
Input: num = "5023"
Output: false
Explanation: There are no moves to be made.
The sum of the first half is equal to the sum of the second half: 5 + 0 = 2 + 3.
Example 2:
Input: num = "25??"
Output: true
Explanation: Alice can replace one of the '?'s with '9' and it will be impossible for Bob to make the sums equal.
Example 3:
Input: num = "?3295???"
Output: false
Explanation: It can be proven that Bob will always win. One possible outcome is:
- Alice replaces the first '?' with '9'. num = "93295???".
- Bob replaces one of the '?' in the right half with '9'. num = "932959??".
- Alice replaces one of the '?' in the right half with '2'. num = "9329592?".
- Bob replaces the last '?' in the right half with '7'. num = "93295927".
Bob wins because 9 + 3 + 2 + 9 = 5 + 9 + 2 + 7.
Constraints:
2 <= num.length <= 105
num.length is even.
num consists of only digits and '?'. | Python 3 | Simple Math | Explanation | 396 | sum-game | 0.469 | idontknoooo | Medium | 27,202 | 1,927 |
minimum cost to reach destination in time | class Solution:
def minCost(self, maxTime: int, edges: List[List[int]], passingFees: List[int]) -> int:
n = len(passingFees)
mat = {}
for x, y, time in edges:
if x not in mat: mat[x] = set()
if y not in mat: mat[y] = set()
mat[x].add((y, time))
mat[y].add((x, time))
h = [(passingFees[0], 0, 0)]
visited = set()
while h:
fees, time_so_far, city = heappop(h)
if time_so_far > maxTime: continue
if city == n - 1: return fees
if (city, time_so_far) in visited: continue
visited.add((city, time_so_far))
for nxt, time_to_travel in mat[city]:
# Check if we are retracing a visited path
if (nxt, time_so_far - time_to_travel) in visited: continue
heappush(h, (fees + passingFees[nxt], time_so_far + time_to_travel, nxt))
return -1 | https://leetcode.com/problems/minimum-cost-to-reach-destination-in-time/discuss/2841255/Python-Dijkstra's-Algorithm%3A-36-time-8-space | 0 | There is a country of n cities numbered from 0 to n - 1 where all the cities are connected by bi-directional roads. The roads are represented as a 2D integer array edges where edges[i] = [xi, yi, timei] denotes a road between cities xi and yi that takes timei minutes to travel. There may be multiple roads of differing travel times connecting the same two cities, but no road connects a city to itself.
Each time you pass through a city, you must pay a passing fee. This is represented as a 0-indexed integer array passingFees of length n where passingFees[j] is the amount of dollars you must pay when you pass through city j.
In the beginning, you are at city 0 and want to reach city n - 1 in maxTime minutes or less. The cost of your journey is the summation of passing fees for each city that you passed through at some moment of your journey (including the source and destination cities).
Given maxTime, edges, and passingFees, return the minimum cost to complete your journey, or -1 if you cannot complete it within maxTime minutes.
Example 1:
Input: maxTime = 30, edges = [[0,1,10],[1,2,10],[2,5,10],[0,3,1],[3,4,10],[4,5,15]], passingFees = [5,1,2,20,20,3]
Output: 11
Explanation: The path to take is 0 -> 1 -> 2 -> 5, which takes 30 minutes and has $11 worth of passing fees.
Example 2:
Input: maxTime = 29, edges = [[0,1,10],[1,2,10],[2,5,10],[0,3,1],[3,4,10],[4,5,15]], passingFees = [5,1,2,20,20,3]
Output: 48
Explanation: The path to take is 0 -> 3 -> 4 -> 5, which takes 26 minutes and has $48 worth of passing fees.
You cannot take path 0 -> 1 -> 2 -> 5 since it would take too long.
Example 3:
Input: maxTime = 25, edges = [[0,1,10],[1,2,10],[2,5,10],[0,3,1],[3,4,10],[4,5,15]], passingFees = [5,1,2,20,20,3]
Output: -1
Explanation: There is no way to reach city 5 from city 0 within 25 minutes.
Constraints:
1 <= maxTime <= 1000
n == passingFees.length
2 <= n <= 1000
n - 1 <= edges.length <= 1000
0 <= xi, yi <= n - 1
1 <= timei <= 1000
1 <= passingFees[j] <= 1000
The graph may contain multiple edges between two nodes.
The graph does not contain self loops. | Python Dijkstra's Algorithm: 36% time, 8% space | 2 | minimum-cost-to-reach-destination-in-time | 0.374 | hqz3 | Hard | 27,204 | 1,928 |
concatenation of array | class Solution:
def getConcatenation(self, nums: List[int]) -> List[int]:
nums.extend(nums)
return nums | https://leetcode.com/problems/concatenation-of-array/discuss/2044719/Easy-Python-two-liner-code | 10 | Given an integer array nums of length n, you want to create an array ans of length 2n where ans[i] == nums[i] and ans[i + n] == nums[i] for 0 <= i < n (0-indexed).
Specifically, ans is the concatenation of two nums arrays.
Return the array ans.
Example 1:
Input: nums = [1,2,1]
Output: [1,2,1,1,2,1]
Explanation: The array ans is formed as follows:
- ans = [nums[0],nums[1],nums[2],nums[0],nums[1],nums[2]]
- ans = [1,2,1,1,2,1]
Example 2:
Input: nums = [1,3,2,1]
Output: [1,3,2,1,1,3,2,1]
Explanation: The array ans is formed as follows:
- ans = [nums[0],nums[1],nums[2],nums[3],nums[0],nums[1],nums[2],nums[3]]
- ans = [1,3,2,1,1,3,2,1]
Constraints:
n == nums.length
1 <= n <= 1000
1 <= nums[i] <= 1000 | Easy Python two liner code | 743 | concatenation-of-array | 0.912 | Shivam_Raj_Sharma | Easy | 27,207 | 1,929 |
unique length 3 palindromic subsequences | class Solution(object):
def countPalindromicSubsequence(self, s):
d=defaultdict(list)
for i,c in enumerate(s):
d[c].append(i)
ans=0
for el in d:
if len(d[el])<2:
continue
a=d[el][0]
b=d[el][-1]
ans+=len(set(s[a+1:b]))
return(ans) | https://leetcode.com/problems/unique-length-3-palindromic-subsequences/discuss/1330186/easy-python-solution | 32 | Given a string s, return the number of unique palindromes of length three that are a subsequence of s.
Note that even if there are multiple ways to obtain the same subsequence, it is still only counted once.
A palindrome is a string that reads the same forwards and backwards.
A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.
For example, "ace" is a subsequence of "abcde".
Example 1:
Input: s = "aabca"
Output: 3
Explanation: The 3 palindromic subsequences of length 3 are:
- "aba" (subsequence of "aabca")
- "aaa" (subsequence of "aabca")
- "aca" (subsequence of "aabca")
Example 2:
Input: s = "adc"
Output: 0
Explanation: There are no palindromic subsequences of length 3 in "adc".
Example 3:
Input: s = "bbcbaba"
Output: 4
Explanation: The 4 palindromic subsequences of length 3 are:
- "bbb" (subsequence of "bbcbaba")
- "bcb" (subsequence of "bbcbaba")
- "bab" (subsequence of "bbcbaba")
- "aba" (subsequence of "bbcbaba")
Constraints:
3 <= s.length <= 105
s consists of only lowercase English letters. | easy python solution | 1,100 | unique-length-3-palindromic-subsequences | 0.515 | aayush_chhabra | Medium | 27,274 | 1,930 |
painting a grid with three different colors | class Solution:
def colorTheGrid(self, m: int, n: int) -> int:
@cache
def fn(i, j, mask):
"""Return number of ways to color grid."""
if j == n: return 1
if i == m: return fn(0, j+1, mask)
ans = 0
for x in 1<<2*i, 1<<2*i+1, 0b11<<2*i:
mask0 = mask ^ x
if mask0 & 0b11<<2*i and (i == 0 or (mask0 >> 2*i) & 0b11 != (mask0 >> 2*i-2) & 0b11):
ans += fn(i+1, j, mask0)
return ans % 1_000_000_007
return fn(0, 0, 0) | https://leetcode.com/problems/painting-a-grid-with-three-different-colors/discuss/1338695/Python3-top-down-dp | 1 | You are given two integers m and n. Consider an m x n grid where each cell is initially white. You can paint each cell red, green, or blue. All cells must be painted.
Return the number of ways to color the grid with no two adjacent cells having the same color. Since the answer can be very large, return it modulo 109 + 7.
Example 1:
Input: m = 1, n = 1
Output: 3
Explanation: The three possible colorings are shown in the image above.
Example 2:
Input: m = 1, n = 2
Output: 6
Explanation: The six possible colorings are shown in the image above.
Example 3:
Input: m = 5, n = 5
Output: 580986
Constraints:
1 <= m <= 5
1 <= n <= 1000 | [Python3] top-down dp | 263 | painting-a-grid-with-three-different-colors | 0.57 | ye15 | Hard | 27,285 | 1,931 |
merge bsts to create single bst | class Solution:
def canMerge(self, trees: List[TreeNode]) -> TreeNode:
roots, leaves, loners, n = {}, {}, set(), len(trees)
if n == 1:
return trees[0]
for tree in trees:
if not tree.left and not tree.right:
loners.add(tree.val)
continue
roots[tree.val] = tree
for node in [tree.left, tree.right]:
if node:
if node.val in leaves:
return None
leaves[node.val] = node
for loner in loners:
if loner not in leaves and loner not in roots:
return None
orphan = None
for val, tree in roots.items():
if val not in leaves:
if orphan:
return None
orphan = tree
if not orphan:
return None
def build(node, small, big):
nonlocal roots
if not node:
return True
if small >= node.val or node.val >= big:
return False
if node.val in roots:
node.left, node.right = roots[node.val].left, roots[node.val].right
del roots[node.val]
return build(node.left, small, node.val) and build(node.right, node.val, big)
del roots[orphan.val]
result = build(orphan.left, -inf, orphan.val) and build(orphan.right, orphan.val, inf)
return orphan if result and not roots.keys() else None | https://leetcode.com/problems/merge-bsts-to-create-single-bst/discuss/1410066/Python3-Recursive-tree-building-solution | 0 | You are given n BST (binary search tree) root nodes for n separate BSTs stored in an array trees (0-indexed). Each BST in trees has at most 3 nodes, and no two roots have the same value. In one operation, you can:
Select two distinct indices i and j such that the value stored at one of the leaves of trees[i] is equal to the root value of trees[j].
Replace the leaf node in trees[i] with trees[j].
Remove trees[j] from trees.
Return the root of the resulting BST if it is possible to form a valid BST after performing n - 1 operations, or null if it is impossible to create a valid BST.
A BST (binary search tree) is a binary tree where each node satisfies the following property:
Every node in the node's left subtree has a value strictly less than the node's value.
Every node in the node's right subtree has a value strictly greater than the node's value.
A leaf is a node that has no children.
Example 1:
Input: trees = [[2,1],[3,2,5],[5,4]]
Output: [3,2,5,1,null,4]
Explanation:
In the first operation, pick i=1 and j=0, and merge trees[0] into trees[1].
Delete trees[0], so trees = [[3,2,5,1],[5,4]].
In the second operation, pick i=0 and j=1, and merge trees[1] into trees[0].
Delete trees[1], so trees = [[3,2,5,1,null,4]].
The resulting tree, shown above, is a valid BST, so return its root.
Example 2:
Input: trees = [[5,3,8],[3,2,6]]
Output: []
Explanation:
Pick i=0 and j=1 and merge trees[1] into trees[0].
Delete trees[1], so trees = [[5,3,8,2,6]].
The resulting tree is shown above. This is the only valid operation that can be performed, but the resulting tree is not a valid BST, so return null.
Example 3:
Input: trees = [[5,4],[3]]
Output: []
Explanation: It is impossible to perform any operations.
Constraints:
n == trees.length
1 <= n <= 5 * 104
The number of nodes in each tree is in the range [1, 3].
Each node in the input may have children but no grandchildren.
No two roots of trees have the same value.
All the trees in the input are valid BSTs.
1 <= TreeNode.val <= 5 * 104. | Python3 Recursive tree building solution | 134 | merge-bsts-to-create-single-bst | 0.353 | yiseboge | Hard | 27,287 | 1,932 |
maximum number of words you can type | class Solution:
def canBeTypedWords(self, text: str, brokenLetters: str) -> int:
text = text.split()
length = len(text)
brokenLetters = set(brokenLetters)
for word in text:
for char in word:
if char in brokenLetters:
length -= 1
break
return length | https://leetcode.com/problems/maximum-number-of-words-you-can-type/discuss/1355349/Easy-Fast-Python-Solutions-(2-Approaches-28ms-32ms-Faster-than-93) | 10 | There is a malfunctioning keyboard where some letter keys do not work. All other keys on the keyboard work properly.
Given a string text of words separated by a single space (no leading or trailing spaces) and a string brokenLetters of all distinct letter keys that are broken, return the number of words in text you can fully type using this keyboard.
Example 1:
Input: text = "hello world", brokenLetters = "ad"
Output: 1
Explanation: We cannot type "world" because the 'd' key is broken.
Example 2:
Input: text = "leet code", brokenLetters = "lt"
Output: 1
Explanation: We cannot type "leet" because the 'l' and 't' keys are broken.
Example 3:
Input: text = "leet code", brokenLetters = "e"
Output: 0
Explanation: We cannot type either word because the 'e' key is broken.
Constraints:
1 <= text.length <= 104
0 <= brokenLetters.length <= 26
text consists of words separated by a single space without any leading or trailing spaces.
Each word only consists of lowercase English letters.
brokenLetters consists of distinct lowercase English letters. | Easy, Fast Python Solutions (2 Approaches - 28ms, 32ms; Faster than 93%) | 624 | maximum-number-of-words-you-can-type | 0.71 | the_sky_high | Easy | 27,288 | 1,935 |
add minimum number of rungs | class Solution:
def addRungs(self, rungs: List[int], dist: int) -> int:
return sum((a - b - 1) // dist for a, b in zip(rungs, [0] + rungs)) | https://leetcode.com/problems/add-minimum-number-of-rungs/discuss/1344878/Divide-gaps-by-dist | 37 | You are given a strictly increasing integer array rungs that represents the height of rungs on a ladder. You are currently on the floor at height 0, and you want to reach the last rung.
You are also given an integer dist. You can only climb to the next highest rung if the distance between where you are currently at (the floor or on a rung) and the next rung is at most dist. You are able to insert rungs at any positive integer height if a rung is not already there.
Return the minimum number of rungs that must be added to the ladder in order for you to climb to the last rung.
Example 1:
Input: rungs = [1,3,5,10], dist = 2
Output: 2
Explanation:
You currently cannot reach the last rung.
Add rungs at heights 7 and 8 to climb this ladder.
The ladder will now have rungs at [1,3,5,7,8,10].
Example 2:
Input: rungs = [3,6,8,10], dist = 3
Output: 0
Explanation:
This ladder can be climbed without adding additional rungs.
Example 3:
Input: rungs = [3,4,6,7], dist = 2
Output: 1
Explanation:
You currently cannot reach the first rung from the ground.
Add a rung at height 1 to climb this ladder.
The ladder will now have rungs at [1,3,4,6,7].
Constraints:
1 <= rungs.length <= 105
1 <= rungs[i] <= 109
1 <= dist <= 109
rungs is strictly increasing. | Divide gaps by dist | 1,800 | add-minimum-number-of-rungs | 0.429 | votrubac | Medium | 27,323 | 1,936 |
maximum number of points with cost | class Solution:
def maxPoints(self, points: List[List[int]]) -> int:
m, n = len(points), len(points[0])
dp = points[0]
left = [0] * n ## left side contribution
right = [0] * n ## right side contribution
for r in range(1, m):
for c in range(n):
if c == 0:
left[c] = dp[c]
else:
left[c] = max(left[c - 1] - 1, dp[c])
for c in range(n - 1, -1, -1):
if c == n-1:
right[c] = dp[c]
else:
right[c] = max(right[c + 1] - 1, dp[c])
for c in range(n):
dp[c] = points[r][c] + max(left[c], right[c])
return max(dp) | https://leetcode.com/problems/maximum-number-of-points-with-cost/discuss/2119013/Python%3A-Dynamic-Programming-O(mn)-Solution | 14 | You are given an m x n integer matrix points (0-indexed). Starting with 0 points, you want to maximize the number of points you can get from the matrix.
To gain points, you must pick one cell in each row. Picking the cell at coordinates (r, c) will add points[r][c] to your score.
However, you will lose points if you pick a cell too far from the cell that you picked in the previous row. For every two adjacent rows r and r + 1 (where 0 <= r < m - 1), picking cells at coordinates (r, c1) and (r + 1, c2) will subtract abs(c1 - c2) from your score.
Return the maximum number of points you can achieve.
abs(x) is defined as:
x for x >= 0.
-x for x < 0.
Example 1:
Input: points = [[1,2,3],[1,5,1],[3,1,1]]
Output: 9
Explanation:
The blue cells denote the optimal cells to pick, which have coordinates (0, 2), (1, 1), and (2, 0).
You add 3 + 5 + 3 = 11 to your score.
However, you must subtract abs(2 - 1) + abs(1 - 0) = 2 from your score.
Your final score is 11 - 2 = 9.
Example 2:
Input: points = [[1,5],[2,3],[4,2]]
Output: 11
Explanation:
The blue cells denote the optimal cells to pick, which have coordinates (0, 1), (1, 1), and (2, 0).
You add 5 + 3 + 4 = 12 to your score.
However, you must subtract abs(1 - 1) + abs(1 - 0) = 1 from your score.
Your final score is 12 - 1 = 11.
Constraints:
m == points.length
n == points[r].length
1 <= m, n <= 105
1 <= m * n <= 105
0 <= points[r][c] <= 105 | Python: Dynamic Programming O(mn) Solution | 784 | maximum-number-of-points-with-cost | 0.362 | dadhania | Medium | 27,340 | 1,937 |
check if all characters have equal number of occurrences | class Solution:
def areOccurrencesEqual(self, s: str) -> bool:
return len(set(Counter(s).values())) == 1 | https://leetcode.com/problems/check-if-all-characters-have-equal-number-of-occurrences/discuss/1359715/Python3-1-line | 35 | Given a string s, return true if s is a good string, or false otherwise.
A string s is good if all the characters that appear in s have the same number of occurrences (i.e., the same frequency).
Example 1:
Input: s = "abacbc"
Output: true
Explanation: The characters that appear in s are 'a', 'b', and 'c'. All characters occur 2 times in s.
Example 2:
Input: s = "aaabb"
Output: false
Explanation: The characters that appear in s are 'a' and 'b'.
'a' occurs 3 times while 'b' occurs 2 times, which is not the same number of times.
Constraints:
1 <= s.length <= 1000
s consists of lowercase English letters. | [Python3] 1-line | 2,100 | check-if-all-characters-have-equal-number-of-occurrences | 0.768 | ye15 | Easy | 27,350 | 1,941 |
the number of the smallest unoccupied chair | class Solution:
def smallestChair(self, times: List[List[int]], targetFriend: int) -> int:
arrivals = []
departures = []
for ind, (x, y) in enumerate(times):
heappush(arrivals, (x, ind))
heappush(departures, (y, ind))
d = {}
occupied = [0] * len(times)
while True:
if arrivals and departures and arrivals[0][0] < departures[0][0]:
_, ind = heappop(arrivals)
d[ind] = occupied.index(0)
occupied[d[ind]] = 1
if ind == targetFriend:
return d[ind]
elif arrivals and departures and arrivals[0][0] >= departures[0][0]:
_, ind = heappop(departures)
occupied[d[ind]] = 0 | https://leetcode.com/problems/the-number-of-the-smallest-unoccupied-chair/discuss/1359713/Python-Simple-Heap-Solution-with-Explanation | 20 | There is a party where n friends numbered from 0 to n - 1 are attending. There is an infinite number of chairs in this party that are numbered from 0 to infinity. When a friend arrives at the party, they sit on the unoccupied chair with the smallest number.
For example, if chairs 0, 1, and 5 are occupied when a friend comes, they will sit on chair number 2.
When a friend leaves the party, their chair becomes unoccupied at the moment they leave. If another friend arrives at that same moment, they can sit in that chair.
You are given a 0-indexed 2D integer array times where times[i] = [arrivali, leavingi], indicating the arrival and leaving times of the ith friend respectively, and an integer targetFriend. All arrival times are distinct.
Return the chair number that the friend numbered targetFriend will sit on.
Example 1:
Input: times = [[1,4],[2,3],[4,6]], targetFriend = 1
Output: 1
Explanation:
- Friend 0 arrives at time 1 and sits on chair 0.
- Friend 1 arrives at time 2 and sits on chair 1.
- Friend 1 leaves at time 3 and chair 1 becomes empty.
- Friend 0 leaves at time 4 and chair 0 becomes empty.
- Friend 2 arrives at time 4 and sits on chair 0.
Since friend 1 sat on chair 1, we return 1.
Example 2:
Input: times = [[3,10],[1,5],[2,6]], targetFriend = 0
Output: 2
Explanation:
- Friend 1 arrives at time 1 and sits on chair 0.
- Friend 2 arrives at time 2 and sits on chair 1.
- Friend 0 arrives at time 3 and sits on chair 2.
- Friend 1 leaves at time 5 and chair 0 becomes empty.
- Friend 2 leaves at time 6 and chair 1 becomes empty.
- Friend 0 leaves at time 10 and chair 2 becomes empty.
Since friend 0 sat on chair 2, we return 2.
Constraints:
n == times.length
2 <= n <= 104
times[i].length == 2
1 <= arrivali < leavingi <= 105
0 <= targetFriend <= n - 1
Each arrivali time is distinct. | Python - Simple Heap Solution with Explanation | 1,100 | the-number-of-the-smallest-unoccupied-chair | 0.406 | ajith6198 | Medium | 27,391 | 1,942 |
describe the painting | class Solution:
def splitPainting(self, segments: List[List[int]]) -> List[List[int]]:
# via this mapping, we can easily know which coordinates should be took into consideration.
mapping = defaultdict(int)
for s, e, c in segments:
mapping[s] += c
mapping[e] -= c
res = []
prev, color = None, 0
for now in sorted(mapping):
if color: # if color == 0, it means this part isn't painted.
res.append((prev, now, color))
color += mapping[now]
prev = now
return res | https://leetcode.com/problems/describe-the-painting/discuss/1359717/Python-Easy-solution-in-O(n*logn)-with-detailed-explanation | 129 | There is a long and thin painting that can be represented by a number line. The painting was painted with multiple overlapping segments where each segment was painted with a unique color. You are given a 2D integer array segments, where segments[i] = [starti, endi, colori] represents the half-closed segment [starti, endi) with colori as the color.
The colors in the overlapping segments of the painting were mixed when it was painted. When two or more colors mix, they form a new color that can be represented as a set of mixed colors.
For example, if colors 2, 4, and 6 are mixed, then the resulting mixed color is {2,4,6}.
For the sake of simplicity, you should only output the sum of the elements in the set rather than the full set.
You want to describe the painting with the minimum number of non-overlapping half-closed segments of these mixed colors. These segments can be represented by the 2D array painting where painting[j] = [leftj, rightj, mixj] describes a half-closed segment [leftj, rightj) with the mixed color sum of mixj.
For example, the painting created with segments = [[1,4,5],[1,7,7]] can be described by painting = [[1,4,12],[4,7,7]] because:
[1,4) is colored {5,7} (with a sum of 12) from both the first and second segments.
[4,7) is colored {7} from only the second segment.
Return the 2D array painting describing the finished painting (excluding any parts that are not painted). You may return the segments in any order.
A half-closed segment [a, b) is the section of the number line between points a and b including point a and not including point b.
Example 1:
Input: segments = [[1,4,5],[4,7,7],[1,7,9]]
Output: [[1,4,14],[4,7,16]]
Explanation: The painting can be described as follows:
- [1,4) is colored {5,9} (with a sum of 14) from the first and third segments.
- [4,7) is colored {7,9} (with a sum of 16) from the second and third segments.
Example 2:
Input: segments = [[1,7,9],[6,8,15],[8,10,7]]
Output: [[1,6,9],[6,7,24],[7,8,15],[8,10,7]]
Explanation: The painting can be described as follows:
- [1,6) is colored 9 from the first segment.
- [6,7) is colored {9,15} (with a sum of 24) from the first and second segments.
- [7,8) is colored 15 from the second segment.
- [8,10) is colored 7 from the third segment.
Example 3:
Input: segments = [[1,4,5],[1,4,7],[4,7,1],[4,7,11]]
Output: [[1,4,12],[4,7,12]]
Explanation: The painting can be described as follows:
- [1,4) is colored {5,7} (with a sum of 12) from the first and second segments.
- [4,7) is colored {1,11} (with a sum of 12) from the third and fourth segments.
Note that returning a single segment [1,7) is incorrect because the mixed color sets are different.
Constraints:
1 <= segments.length <= 2 * 104
segments[i].length == 3
1 <= starti < endi <= 105
1 <= colori <= 109
Each colori is distinct. | [Python] Easy solution in O(n*logn) with detailed explanation | 2,000 | describe-the-painting | 0.48 | fishballLin | Medium | 27,398 | 1,943 |
number of visible people in a queue | class Solution:
def canSeePersonsCount(self, heights: List[int]) -> List[int]:
ans = [0]*len(heights)
stack = [] # mono-stack
for i in reversed(range(len(heights))):
while stack and stack[-1] <= heights[i]:
ans[i] += 1
stack.pop()
if stack: ans[i] += 1
stack.append(heights[i])
return ans | https://leetcode.com/problems/number-of-visible-people-in-a-queue/discuss/1359735/Python3-mono-stack | 10 | There are n people standing in a queue, and they numbered from 0 to n - 1 in left to right order. You are given an array heights of distinct integers where heights[i] represents the height of the ith person.
A person can see another person to their right in the queue if everybody in between is shorter than both of them. More formally, the ith person can see the jth person if i < j and min(heights[i], heights[j]) > max(heights[i+1], heights[i+2], ..., heights[j-1]).
Return an array answer of length n where answer[i] is the number of people the ith person can see to their right in the queue.
Example 1:
Input: heights = [10,6,8,5,11,9]
Output: [3,1,2,1,1,0]
Explanation:
Person 0 can see person 1, 2, and 4.
Person 1 can see person 2.
Person 2 can see person 3 and 4.
Person 3 can see person 4.
Person 4 can see person 5.
Person 5 can see no one since nobody is to the right of them.
Example 2:
Input: heights = [5,1,2,3,10]
Output: [4,1,1,1,0]
Constraints:
n == heights.length
1 <= n <= 105
1 <= heights[i] <= 105
All the values of heights are unique. | [Python3] mono-stack | 667 | number-of-visible-people-in-a-queue | 0.697 | ye15 | Hard | 27,403 | 1,944 |
sum of digits of string after convert | class Solution:
def getLucky(self, s: str, k: int) -> int:
s = "".join(str(ord(ch) - 96) for ch in s)
for _ in range(k):
x = sum(int(ch) for ch in s)
s = str(x)
return x | https://leetcode.com/problems/sum-of-digits-of-string-after-convert/discuss/1360730/Python3-simulation | 5 | You are given a string s consisting of lowercase English letters, and an integer k.
First, convert s into an integer by replacing each letter with its position in the alphabet (i.e., replace 'a' with 1, 'b' with 2, ..., 'z' with 26). Then, transform the integer by replacing it with the sum of its digits. Repeat the transform operation k times in total.
For example, if s = "zbax" and k = 2, then the resulting integer would be 8 by the following operations:
Convert: "zbax" β "(26)(2)(1)(24)" β "262124" β 262124
Transform #1: 262124 β 2 + 6 + 2 + 1 + 2 + 4 β 17
Transform #2: 17 β 1 + 7 β 8
Return the resulting integer after performing the operations described above.
Example 1:
Input: s = "iiii", k = 1
Output: 36
Explanation: The operations are as follows:
- Convert: "iiii" β "(9)(9)(9)(9)" β "9999" β 9999
- Transform #1: 9999 β 9 + 9 + 9 + 9 β 36
Thus the resulting integer is 36.
Example 2:
Input: s = "leetcode", k = 2
Output: 6
Explanation: The operations are as follows:
- Convert: "leetcode" β "(12)(5)(5)(20)(3)(15)(4)(5)" β "12552031545" β 12552031545
- Transform #1: 12552031545 β 1 + 2 + 5 + 5 + 2 + 0 + 3 + 1 + 5 + 4 + 5 β 33
- Transform #2: 33 β 3 + 3 β 6
Thus the resulting integer is 6.
Example 3:
Input: s = "zbax", k = 2
Output: 8
Constraints:
1 <= s.length <= 100
1 <= k <= 10
s consists of lowercase English letters. | [Python3] simulation | 487 | sum-of-digits-of-string-after-convert | 0.612 | ye15 | Easy | 27,409 | 1,945 |
largest number after mutating substring | class Solution:
def maximumNumber(self, num: str, change: List[int]) -> str:
num = list(num)
on = False
for i, ch in enumerate(num):
x = int(ch)
if x < change[x]:
on = True
num[i] = str(change[x])
elif x > change[x] and on: break
return "".join(num) | https://leetcode.com/problems/largest-number-after-mutating-substring/discuss/1360736/Python3-greedy | 7 | You are given a string num, which represents a large integer. You are also given a 0-indexed integer array change of length 10 that maps each digit 0-9 to another digit. More formally, digit d maps to digit change[d].
You may choose to mutate a single substring of num. To mutate a substring, replace each digit num[i] with the digit it maps to in change (i.e. replace num[i] with change[num[i]]).
Return a string representing the largest possible integer after mutating (or choosing not to) a single substring of num.
A substring is a contiguous sequence of characters within the string.
Example 1:
Input: num = "132", change = [9,8,5,0,3,6,4,2,6,8]
Output: "832"
Explanation: Replace the substring "1":
- 1 maps to change[1] = 8.
Thus, "132" becomes "832".
"832" is the largest number that can be created, so return it.
Example 2:
Input: num = "021", change = [9,4,3,5,7,2,1,9,0,6]
Output: "934"
Explanation: Replace the substring "021":
- 0 maps to change[0] = 9.
- 2 maps to change[2] = 3.
- 1 maps to change[1] = 4.
Thus, "021" becomes "934".
"934" is the largest number that can be created, so return it.
Example 3:
Input: num = "5", change = [1,4,7,5,3,2,5,6,9,4]
Output: "5"
Explanation: "5" is already the largest number that can be created, so return it.
Constraints:
1 <= num.length <= 105
num consists of only digits 0-9.
change.length == 10
0 <= change[d] <= 9 | [Python3] greedy | 572 | largest-number-after-mutating-substring | 0.346 | ye15 | Medium | 27,437 | 1,946 |
maximum compatibility score sum | class Solution:
def maxCompatibilitySum(self, students: List[List[int]], mentors: List[List[int]]) -> int:
m = len(students)
score = [[0]*m for _ in range(m)]
for i in range(m):
for j in range(m):
score[i][j] = sum(x == y for x, y in zip(students[i], mentors[j]))
ans = 0
for perm in permutations(range(m)):
ans = max(ans, sum(score[i][j] for i, j in zip(perm, range(m))))
return ans | https://leetcode.com/problems/maximum-compatibility-score-sum/discuss/1360746/Python3-permutations | 16 | There is a survey that consists of n questions where each question's answer is either 0 (no) or 1 (yes).
The survey was given to m students numbered from 0 to m - 1 and m mentors numbered from 0 to m - 1. The answers of the students are represented by a 2D integer array students where students[i] is an integer array that contains the answers of the ith student (0-indexed). The answers of the mentors are represented by a 2D integer array mentors where mentors[j] is an integer array that contains the answers of the jth mentor (0-indexed).
Each student will be assigned to one mentor, and each mentor will have one student assigned to them. The compatibility score of a student-mentor pair is the number of answers that are the same for both the student and the mentor.
For example, if the student's answers were [1, 0, 1] and the mentor's answers were [0, 0, 1], then their compatibility score is 2 because only the second and the third answers are the same.
You are tasked with finding the optimal student-mentor pairings to maximize the sum of the compatibility scores.
Given students and mentors, return the maximum compatibility score sum that can be achieved.
Example 1:
Input: students = [[1,1,0],[1,0,1],[0,0,1]], mentors = [[1,0,0],[0,0,1],[1,1,0]]
Output: 8
Explanation: We assign students to mentors in the following way:
- student 0 to mentor 2 with a compatibility score of 3.
- student 1 to mentor 0 with a compatibility score of 2.
- student 2 to mentor 1 with a compatibility score of 3.
The compatibility score sum is 3 + 2 + 3 = 8.
Example 2:
Input: students = [[0,0],[0,0],[0,0]], mentors = [[1,1],[1,1],[1,1]]
Output: 0
Explanation: The compatibility score of any student-mentor pair is 0.
Constraints:
m == students.length == mentors.length
n == students[i].length == mentors[j].length
1 <= m, n <= 8
students[i][k] is either 0 or 1.
mentors[j][k] is either 0 or 1. | [Python3] permutations | 1,100 | maximum-compatibility-score-sum | 0.609 | ye15 | Medium | 27,443 | 1,947 |
delete duplicate folders in system | class Solution:
def deleteDuplicateFolder(self, paths: List[List[str]]) -> List[List[str]]:
paths.sort()
tree = {"#": -1}
for i, path in enumerate(paths):
node = tree
for x in path: node = node.setdefault(x, {})
node["#"] = i
seen = {}
mark = set()
def fn(n):
"""Return serialized value of sub-tree rooted at n."""
if len(n) == 1: return "$" # leaf node
vals = []
for k in n:
if k != "#": vals.append(f"${k}${fn(n[k])}")
hs = "".join(vals)
if hs in seen:
mark.add(n["#"])
mark.add(seen[hs])
if hs != "$": seen[hs] = n["#"]
return hs
fn(tree)
ans = []
stack = [tree]
while stack:
n = stack.pop()
if n["#"] >= 0: ans.append(paths[n["#"]])
for k in n:
if k != "#" and n[k]["#"] not in mark: stack.append(n[k])
return ans | https://leetcode.com/problems/delete-duplicate-folders-in-system/discuss/1360749/Python3-serialize-sub-trees | 4 | Due to a bug, there are many duplicate folders in a file system. You are given a 2D array paths, where paths[i] is an array representing an absolute path to the ith folder in the file system.
For example, ["one", "two", "three"] represents the path "/one/two/three".
Two folders (not necessarily on the same level) are identical if they contain the same non-empty set of identical subfolders and underlying subfolder structure. The folders do not need to be at the root level to be identical. If two or more folders are identical, then mark the folders as well as all their subfolders.
For example, folders "/a" and "/b" in the file structure below are identical. They (as well as their subfolders) should all be marked:
/a
/a/x
/a/x/y
/a/z
/b
/b/x
/b/x/y
/b/z
However, if the file structure also included the path "/b/w", then the folders "/a" and "/b" would not be identical. Note that "/a/x" and "/b/x" would still be considered identical even with the added folder.
Once all the identical folders and their subfolders have been marked, the file system will delete all of them. The file system only runs the deletion once, so any folders that become identical after the initial deletion are not deleted.
Return the 2D array ans containing the paths of the remaining folders after deleting all the marked folders. The paths may be returned in any order.
Example 1:
Input: paths = [["a"],["c"],["d"],["a","b"],["c","b"],["d","a"]]
Output: [["d"],["d","a"]]
Explanation: The file structure is as shown.
Folders "/a" and "/c" (and their subfolders) are marked for deletion because they both contain an empty
folder named "b".
Example 2:
Input: paths = [["a"],["c"],["a","b"],["c","b"],["a","b","x"],["a","b","x","y"],["w"],["w","y"]]
Output: [["c"],["c","b"],["a"],["a","b"]]
Explanation: The file structure is as shown.
Folders "/a/b/x" and "/w" (and their subfolders) are marked for deletion because they both contain an empty folder named "y".
Note that folders "/a" and "/c" are identical after the deletion, but they are not deleted because they were not marked beforehand.
Example 3:
Input: paths = [["a","b"],["c","d"],["c"],["a"]]
Output: [["c"],["c","d"],["a"],["a","b"]]
Explanation: All folders are unique in the file system.
Note that the returned array can be in a different order as the order does not matter.
Constraints:
1 <= paths.length <= 2 * 104
1 <= paths[i].length <= 500
1 <= paths[i][j].length <= 10
1 <= sum(paths[i][j].length) <= 2 * 105
path[i][j] consists of lowercase English letters.
No two paths lead to the same folder.
For any folder not at the root level, its parent folder will also be in the input. | [Python3] serialize sub-trees | 469 | delete-duplicate-folders-in-system | 0.579 | ye15 | Hard | 27,452 | 1,948 |
three divisors | class Solution:
def isThree(self, n: int) -> bool:
return sum(n%i == 0 for i in range(1, n+1)) == 3 | https://leetcode.com/problems/three-divisors/discuss/1375468/Python3-1-line | 14 | Given an integer n, return true if n has exactly three positive divisors. Otherwise, return false.
An integer m is a divisor of n if there exists an integer k such that n = k * m.
Example 1:
Input: n = 2
Output: false
Explantion: 2 has only two divisors: 1 and 2.
Example 2:
Input: n = 4
Output: true
Explantion: 4 has three divisors: 1, 2, and 4.
Constraints:
1 <= n <= 104 | [Python3] 1-line | 866 | three-divisors | 0.572 | ye15 | Easy | 27,454 | 1,952 |
maximum number of weeks for which you can work | class Solution:
def numberOfWeeks(self, milestones: List[int]) -> int:
_sum, _max = sum(milestones), max(milestones)
# (_sum - _max) is the sum of milestones from (2) the rest of projects, if True, we can form another project with the same amount of milestones as (1)
# can refer to the section `Why the greedy strategy works?` for the proof
if _sum - _max >= _max:
return _sum
return 2 * (_sum - _max) + 1 # start from the project with most milestones (_sum - _max + 1) and work on the the rest of milestones (_sum - _max) | https://leetcode.com/problems/maximum-number-of-weeks-for-which-you-can-work/discuss/1375390/Python-Solution-with-detailed-explanation-and-proof-and-common-failure-analysis | 232 | There are n projects numbered from 0 to n - 1. You are given an integer array milestones where each milestones[i] denotes the number of milestones the ith project has.
You can work on the projects following these two rules:
Every week, you will finish exactly one milestone of one project. You must work every week.
You cannot work on two milestones from the same project for two consecutive weeks.
Once all the milestones of all the projects are finished, or if the only milestones that you can work on will cause you to violate the above rules, you will stop working. Note that you may not be able to finish every project's milestones due to these constraints.
Return the maximum number of weeks you would be able to work on the projects without violating the rules mentioned above.
Example 1:
Input: milestones = [1,2,3]
Output: 6
Explanation: One possible scenario is:
- During the 1st week, you will work on a milestone of project 0.
- During the 2nd week, you will work on a milestone of project 2.
- During the 3rd week, you will work on a milestone of project 1.
- During the 4th week, you will work on a milestone of project 2.
- During the 5th week, you will work on a milestone of project 1.
- During the 6th week, you will work on a milestone of project 2.
The total number of weeks is 6.
Example 2:
Input: milestones = [5,2,1]
Output: 7
Explanation: One possible scenario is:
- During the 1st week, you will work on a milestone of project 0.
- During the 2nd week, you will work on a milestone of project 1.
- During the 3rd week, you will work on a milestone of project 0.
- During the 4th week, you will work on a milestone of project 1.
- During the 5th week, you will work on a milestone of project 0.
- During the 6th week, you will work on a milestone of project 2.
- During the 7th week, you will work on a milestone of project 0.
The total number of weeks is 7.
Note that you cannot work on the last milestone of project 0 on 8th week because it would violate the rules.
Thus, one milestone in project 0 will remain unfinished.
Constraints:
n == milestones.length
1 <= n <= 105
1 <= milestones[i] <= 109 | [Python] Solution with detailed explanation & proof & common failure analysis | 7,200 | maximum-number-of-weeks-for-which-you-can-work | 0.391 | fishballLin | Medium | 27,482 | 1,953 |
minimum garden perimeter to collect enough apples | class Solution:
def minimumPerimeter(self, nap: int) -> int:
# here for n = 2 , there are two series :
# (1) Diagnal points for n=3 , diagnal apples = 2*n = 6
# (2) there is series = 2,3,3 = 2+ (sigma(3)-sigma(2))*2
# how to solve:
# here 3 = sigma(n+(n-1))-sigma(n) = sigma(2*n-1)-sigma(n) = 0.5*2n*(2n-1)-0.5*n*n-1
# (3) so our final 2,3,3 = 3*2+2 = (0.5*2n*(2n-1)-0.5*n*n-1)*2+n
# (4) so final 2,3,3 = 3*n*n - 2*n
# (5) we have 4 times repitation of (2,3,3) = 4*(2,3,3) = 4*(3*n*n - 2*n) = 12*n*n - 8*n
# (6) we have 4 diagnal points so their sum(4 diagnal) = 4*(2*n)
# (7) so final sum(total) = 4 diagnal sum + 4(2,3,3) = 4(2*n) + 12*n*n - 8*n = 12*n*n
# so at nth distance we have total 12*n*n apples at the circumfrance
# so net sum = sigma(12*n*n) = 2*n*(n+1)*(2*n+1)
n=1
val=2*n*(n+1)*(2*n+1)
while(val<nap):
n+=1
val=val=2*n*(n+1)*(2*n+1)
return n*8 | https://leetcode.com/problems/minimum-garden-perimeter-to-collect-enough-apples/discuss/1589250/Explanation-for-Intuition-behind-the-math-formula-derivation | 2 | In a garden represented as an infinite 2D grid, there is an apple tree planted at every integer coordinate. The apple tree planted at an integer coordinate (i, j) has |i| + |j| apples growing on it.
You will buy an axis-aligned square plot of land that is centered at (0, 0).
Given an integer neededApples, return the minimum perimeter of a plot such that at least neededApples apples are inside or on the perimeter of that plot.
The value of |x| is defined as:
x if x >= 0
-x if x < 0
Example 1:
Input: neededApples = 1
Output: 8
Explanation: A square plot of side length 1 does not contain any apples.
However, a square plot of side length 2 has 12 apples inside (as depicted in the image above).
The perimeter is 2 * 4 = 8.
Example 2:
Input: neededApples = 13
Output: 16
Example 3:
Input: neededApples = 1000000000
Output: 5040
Constraints:
1 <= neededApples <= 1015 | Explanation for Intuition behind the math formula derivation | 123 | minimum-garden-perimeter-to-collect-enough-apples | 0.53 | martian_rock | Medium | 27,487 | 1,954 |
count number of special subsequences | class Solution:
def countSpecialSubsequences(self, nums: List[int]) -> int:
total_zeros = 0 # number of subsequences of 0s so far
total_ones = 0 # the number of subsequences of 0s followed by 1s so far
total_twos = 0 # the number of special subsequences so far
M = 1000000007
for n in nums:
if n == 0:
# if we have found new 0 we can add it to any existing subsequence of 0s
# or use only this 0
total_zeros += (total_zeros + 1) % M
elif n == 1:
# if we have found new 1 we can add it to any existing subsequence of 0s or 0s and 1s
# to get a valid subsequence of 0s and 1s
total_ones += (total_zeros + total_ones) % M
else:
# if we have found new 2 we can add it to any existing subsequence of 0s and 1s 0r 0s,1s and 2s
# to get a valid subsequence of 0s,1s and 2s
total_twos += (total_ones + total_twos) % M
return total_twos % M | https://leetcode.com/problems/count-number-of-special-subsequences/discuss/1387357/Simple-Python-with-comments.-One-pass-O(n)-with-O(1)-space | 4 | A sequence is special if it consists of a positive number of 0s, followed by a positive number of 1s, then a positive number of 2s.
For example, [0,1,2] and [0,0,1,1,1,2] are special.
In contrast, [2,1,0], [1], and [0,1,2,0] are not special.
Given an array nums (consisting of only integers 0, 1, and 2), return the number of different subsequences that are special. Since the answer may be very large, return it modulo 109 + 7.
A subsequence of an array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements. Two subsequences are different if the set of indices chosen are different.
Example 1:
Input: nums = [0,1,2,2]
Output: 3
Explanation: The special subsequences are bolded [0,1,2,2], [0,1,2,2], and [0,1,2,2].
Example 2:
Input: nums = [2,2,0,0]
Output: 0
Explanation: There are no special subsequences in [2,2,0,0].
Example 3:
Input: nums = [0,1,2,0,1,2]
Output: 7
Explanation: The special subsequences are bolded:
- [0,1,2,0,1,2]
- [0,1,2,0,1,2]
- [0,1,2,0,1,2]
- [0,1,2,0,1,2]
- [0,1,2,0,1,2]
- [0,1,2,0,1,2]
- [0,1,2,0,1,2]
Constraints:
1 <= nums.length <= 105
0 <= nums[i] <= 2 | Simple Python with comments. One pass O(n) with O(1) space | 151 | count-number-of-special-subsequences | 0.513 | IlyaL | Hard | 27,499 | 1,955 |
delete characters to make fancy string | class Solution:
def makeFancyString(self, s: str) -> str:
stack = []
for letter in s:
if len(stack) > 1 and letter == stack[-1] == stack[-2]:
stack.pop()
stack.append(letter)
return ''.join(stack) | https://leetcode.com/problems/delete-characters-to-make-fancy-string/discuss/2714159/Python-or-Easy-Solution | 6 | A fancy string is a string where no three consecutive characters are equal.
Given a string s, delete the minimum possible number of characters from s to make it fancy.
Return the final string after the deletion. It can be shown that the answer will always be unique.
Example 1:
Input: s = "leeetcode"
Output: "leetcode"
Explanation:
Remove an 'e' from the first group of 'e's to create "leetcode".
No three consecutive characters are equal, so return "leetcode".
Example 2:
Input: s = "aaabaaaa"
Output: "aabaa"
Explanation:
Remove an 'a' from the first group of 'a's to create "aabaaaa".
Remove two 'a's from the second group of 'a's to create "aabaa".
No three consecutive characters are equal, so return "aabaa".
Example 3:
Input: s = "aab"
Output: "aab"
Explanation: No three consecutive characters are equal, so return "aab".
Constraints:
1 <= s.length <= 105
s consists only of lowercase English letters. | Python | Easy Solutionβ | 113 | delete-characters-to-make-fancy-string | 0.567 | manayathgeorgejames | Easy | 27,503 | 1,957 |
check if move is legal | class Solution:
def checkMove(self, board: List[List[str]], rMove: int, cMove: int, color: str) -> bool:
for di, dj in (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1), (-1, 0), (-1, 1):
i, j = rMove+di, cMove+dj
step = 0
while 0 <= i < 8 and 0 <= j < 8:
if board[i][j] == color and step: return True
if board[i][j] == "." or board[i][j] == color and not step: break
i, j = i+di, j+dj
step += 1
return False | https://leetcode.com/problems/check-if-move-is-legal/discuss/1389250/Python3-check-8-directions | 5 | You are given a 0-indexed 8 x 8 grid board, where board[r][c] represents the cell (r, c) on a game board. On the board, free cells are represented by '.', white cells are represented by 'W', and black cells are represented by 'B'.
Each move in this game consists of choosing a free cell and changing it to the color you are playing as (either white or black). However, a move is only legal if, after changing it, the cell becomes the endpoint of a good line (horizontal, vertical, or diagonal).
A good line is a line of three or more cells (including the endpoints) where the endpoints of the line are one color, and the remaining cells in the middle are the opposite color (no cells in the line are free). You can find examples for good lines in the figure below:
Given two integers rMove and cMove and a character color representing the color you are playing as (white or black), return true if changing cell (rMove, cMove) to color color is a legal move, or false if it is not legal.
Example 1:
Input: board = [[".",".",".","B",".",".",".","."],[".",".",".","W",".",".",".","."],[".",".",".","W",".",".",".","."],[".",".",".","W",".",".",".","."],["W","B","B",".","W","W","W","B"],[".",".",".","B",".",".",".","."],[".",".",".","B",".",".",".","."],[".",".",".","W",".",".",".","."]], rMove = 4, cMove = 3, color = "B"
Output: true
Explanation: '.', 'W', and 'B' are represented by the colors blue, white, and black respectively, and cell (rMove, cMove) is marked with an 'X'.
The two good lines with the chosen cell as an endpoint are annotated above with the red rectangles.
Example 2:
Input: board = [[".",".",".",".",".",".",".","."],[".","B",".",".","W",".",".","."],[".",".","W",".",".",".",".","."],[".",".",".","W","B",".",".","."],[".",".",".",".",".",".",".","."],[".",".",".",".","B","W",".","."],[".",".",".",".",".",".","W","."],[".",".",".",".",".",".",".","B"]], rMove = 4, cMove = 4, color = "W"
Output: false
Explanation: While there are good lines with the chosen cell as a middle cell, there are no good lines with the chosen cell as an endpoint.
Constraints:
board.length == board[r].length == 8
0 <= rMove, cMove < 8
board[rMove][cMove] == '.'
color is either 'B' or 'W'. | [Python3] check 8 directions | 312 | check-if-move-is-legal | 0.445 | ye15 | Medium | 27,526 | 1,958 |
minimum total space wasted with k resizing operations | class Solution:
def minSpaceWastedKResizing(self, nums: List[int], k: int) -> int:
@cache
def fn(i, k):
"""Return min waste from i with k ops."""
if i == len(nums): return 0
if k < 0: return inf
ans = inf
rmx = rsm = 0
for j in range(i, len(nums)):
rmx = max(rmx, nums[j])
rsm += nums[j]
ans = min(ans, rmx*(j-i+1) - rsm + fn(j+1, k-1))
return ans
return fn(0, k) | https://leetcode.com/problems/minimum-total-space-wasted-with-k-resizing-operations/discuss/1389260/Python3-dp | 14 | You are currently designing a dynamic array. You are given a 0-indexed integer array nums, where nums[i] is the number of elements that will be in the array at time i. In addition, you are given an integer k, the maximum number of times you can resize the array (to any size).
The size of the array at time t, sizet, must be at least nums[t] because there needs to be enough space in the array to hold all the elements. The space wasted at time t is defined as sizet - nums[t], and the total space wasted is the sum of the space wasted across every time t where 0 <= t < nums.length.
Return the minimum total space wasted if you can resize the array at most k times.
Note: The array can have any size at the start and does not count towards the number of resizing operations.
Example 1:
Input: nums = [10,20], k = 0
Output: 10
Explanation: size = [20,20].
We can set the initial size to be 20.
The total wasted space is (20 - 10) + (20 - 20) = 10.
Example 2:
Input: nums = [10,20,30], k = 1
Output: 10
Explanation: size = [20,20,30].
We can set the initial size to be 20 and resize to 30 at time 2.
The total wasted space is (20 - 10) + (20 - 20) + (30 - 30) = 10.
Example 3:
Input: nums = [10,20,15,30,20], k = 2
Output: 15
Explanation: size = [10,20,20,30,30].
We can set the initial size to 10, resize to 20 at time 1, and resize to 30 at time 3.
The total wasted space is (10 - 10) + (20 - 20) + (20 - 15) + (30 - 30) + (30 - 20) = 15.
Constraints:
1 <= nums.length <= 200
1 <= nums[i] <= 106
0 <= k <= nums.length - 1 | [Python3] dp | 987 | minimum-total-space-wasted-with-k-resizing-operations | 0.42 | ye15 | Medium | 27,530 | 1,959 |
maximum product of the length of two palindromic substrings | class Solution:
def maxProduct(self, s: str) -> int:
n = len(s)
# Manacher's algo
hlen = [0]*n # half-length
center = right = 0
for i in range(n):
if i < right: hlen[i] = min(right - i, hlen[2*center - i])
while 0 <= i-1-hlen[i] and i+1+hlen[i] < len(s) and s[i-1-hlen[i]] == s[i+1+hlen[i]]:
hlen[i] += 1
if right < i+hlen[i]: center, right = i, i+hlen[i]
prefix = [0]*n
suffix = [0]*n
for i in range(n):
prefix[i+hlen[i]] = max(prefix[i+hlen[i]], 2*hlen[i]+1)
suffix[i-hlen[i]] = max(suffix[i-hlen[i]], 2*hlen[i]+1)
for i in range(1, n):
prefix[~i] = max(prefix[~i], prefix[~i+1]-2)
suffix[i] = max(suffix[i], suffix[i-1]-2)
for i in range(1, n):
prefix[i] = max(prefix[i-1], prefix[i])
suffix[~i] = max(suffix[~i], suffix[~i+1])
return max(prefix[i-1]*suffix[i] for i in range(1, n)) | https://leetcode.com/problems/maximum-product-of-the-length-of-two-palindromic-substrings/discuss/1393832/Python3-Manacher | 3 | You are given a 0-indexed string s and are tasked with finding two non-intersecting palindromic substrings of odd length such that the product of their lengths is maximized.
More formally, you want to choose four integers i, j, k, l such that 0 <= i <= j < k <= l < s.length and both the substrings s[i...j] and s[k...l] are palindromes and have odd lengths. s[i...j] denotes a substring from index i to index j inclusive.
Return the maximum possible product of the lengths of the two non-intersecting palindromic substrings.
A palindrome is a string that is the same forward and backward. A substring is a contiguous sequence of characters in a string.
Example 1:
Input: s = "ababbb"
Output: 9
Explanation: Substrings "aba" and "bbb" are palindromes with odd length. product = 3 * 3 = 9.
Example 2:
Input: s = "zaaaxbbby"
Output: 9
Explanation: Substrings "aaa" and "bbb" are palindromes with odd length. product = 3 * 3 = 9.
Constraints:
2 <= s.length <= 105
s consists of lowercase English letters. | [Python3] Manacher | 200 | maximum-product-of-the-length-of-two-palindromic-substrings | 0.293 | ye15 | Hard | 27,534 | 1,960 |
check if string is a prefix of array | class Solution:
def isPrefixString(self, s: str, words: List[str]) -> bool:
i = 0
for word in words:
if s[i:i+len(word)] != word: return False
i += len(word)
if i == len(s): return True
return False | https://leetcode.com/problems/check-if-string-is-a-prefix-of-array/discuss/1390199/Python3-move-along-s | 22 | Given a string s and an array of strings words, determine whether s is a prefix string of words.
A string s is a prefix string of words if s can be made by concatenating the first k strings in words for some positive k no larger than words.length.
Return true if s is a prefix string of words, or false otherwise.
Example 1:
Input: s = "iloveleetcode", words = ["i","love","leetcode","apples"]
Output: true
Explanation:
s can be made by concatenating "i", "love", and "leetcode" together.
Example 2:
Input: s = "iloveleetcode", words = ["apples","i","love","leetcode"]
Output: false
Explanation:
It is impossible to make s using a prefix of arr.
Constraints:
1 <= words.length <= 100
1 <= words[i].length <= 20
1 <= s.length <= 1000
words[i] and s consist of only lowercase English letters. | [Python3] move along s | 1,200 | check-if-string-is-a-prefix-of-array | 0.541 | ye15 | Easy | 27,535 | 1,961 |
remove stones to minimize the total | class Solution:
def minStoneSum(self, piles: List[int], k: int) -> int:
pq = [-x for x in piles]
heapify(pq)
for _ in range(k): heapreplace(pq, pq[0]//2)
return -sum(pq) | https://leetcode.com/problems/remove-stones-to-minimize-the-total/discuss/1390207/Python3-priority-queue | 7 | You are given a 0-indexed integer array piles, where piles[i] represents the number of stones in the ith pile, and an integer k. You should apply the following operation exactly k times:
Choose any piles[i] and remove floor(piles[i] / 2) stones from it.
Notice that you can apply the operation on the same pile more than once.
Return the minimum possible total number of stones remaining after applying the k operations.
floor(x) is the greatest integer that is smaller than or equal to x (i.e., rounds x down).
Example 1:
Input: piles = [5,4,9], k = 2
Output: 12
Explanation: Steps of a possible scenario are:
- Apply the operation on pile 2. The resulting piles are [5,4,5].
- Apply the operation on pile 0. The resulting piles are [3,4,5].
The total number of stones in [3,4,5] is 12.
Example 2:
Input: piles = [4,3,6,7], k = 3
Output: 12
Explanation: Steps of a possible scenario are:
- Apply the operation on pile 2. The resulting piles are [4,3,3,7].
- Apply the operation on pile 3. The resulting piles are [4,3,3,4].
- Apply the operation on pile 0. The resulting piles are [2,3,3,4].
The total number of stones in [2,3,3,4] is 12.
Constraints:
1 <= piles.length <= 105
1 <= piles[i] <= 104
1 <= k <= 105 | [Python3] priority queue | 413 | remove-stones-to-minimize-the-total | 0.593 | ye15 | Medium | 27,556 | 1,962 |
minimum number of swaps to make the string balanced | class Solution:
def minSwaps(self, s: str) -> int:
res, bal = 0, 0
for ch in s:
bal += 1 if ch == '[' else -1
if bal == -1:
res += 1
bal = 1
return res | https://leetcode.com/problems/minimum-number-of-swaps-to-make-the-string-balanced/discuss/1390576/Two-Pointers | 19 | You are given a 0-indexed string s of even length n. The string consists of exactly n / 2 opening brackets '[' and n / 2 closing brackets ']'.
A string is called balanced if and only if:
It is the empty string, or
It can be written as AB, where both A and B are balanced strings, or
It can be written as [C], where C is a balanced string.
You may swap the brackets at any two indices any number of times.
Return the minimum number of swaps to make s balanced.
Example 1:
Input: s = "][]["
Output: 1
Explanation: You can make the string balanced by swapping index 0 with index 3.
The resulting string is "[[]]".
Example 2:
Input: s = "]]][[["
Output: 2
Explanation: You can do the following to make the string balanced:
- Swap index 0 with index 4. s = "[]][][".
- Swap index 1 with index 5. s = "[[][]]".
The resulting string is "[[][]]".
Example 3:
Input: s = "[]"
Output: 0
Explanation: The string is already balanced.
Constraints:
n == s.length
2 <= n <= 106
n is even.
s[i] is either '[' or ']'.
The number of opening brackets '[' equals n / 2, and the number of closing brackets ']' equals n / 2. | Two Pointers | 2,000 | minimum-number-of-swaps-to-make-the-string-balanced | 0.684 | votrubac | Medium | 27,563 | 1,963 |
find the longest valid obstacle course at each position | class Solution:
def longestObstacleCourseAtEachPosition(self, obs: List[int]) -> List[int]:
local = []
res=[0 for _ in range(len(obs))]
for i in range(len(obs)):
n=obs[i]
if len(local)==0 or local[-1]<=n:
local.append(n)
res[i]=len(local)
else:
ind = bisect.bisect_right(local,n)
local[ind]=n
res[i]=ind+1
return res | https://leetcode.com/problems/find-the-longest-valid-obstacle-course-at-each-position/discuss/1390573/Clean-and-Simple-oror-98-faster-oror-Easy-Code | 1 | You want to build some obstacle courses. You are given a 0-indexed integer array obstacles of length n, where obstacles[i] describes the height of the ith obstacle.
For every index i between 0 and n - 1 (inclusive), find the length of the longest obstacle course in obstacles such that:
You choose any number of obstacles between 0 and i inclusive.
You must include the ith obstacle in the course.
You must put the chosen obstacles in the same order as they appear in obstacles.
Every obstacle (except the first) is taller than or the same height as the obstacle immediately before it.
Return an array ans of length n, where ans[i] is the length of the longest obstacle course for index i as described above.
Example 1:
Input: obstacles = [1,2,3,2]
Output: [1,2,3,3]
Explanation: The longest valid obstacle course at each position is:
- i = 0: [1], [1] has length 1.
- i = 1: [1,2], [1,2] has length 2.
- i = 2: [1,2,3], [1,2,3] has length 3.
- i = 3: [1,2,3,2], [1,2,2] has length 3.
Example 2:
Input: obstacles = [2,2,1]
Output: [1,2,1]
Explanation: The longest valid obstacle course at each position is:
- i = 0: [2], [2] has length 1.
- i = 1: [2,2], [2,2] has length 2.
- i = 2: [2,2,1], [1] has length 1.
Example 3:
Input: obstacles = [3,1,5,6,4,2]
Output: [1,1,2,3,2,2]
Explanation: The longest valid obstacle course at each position is:
- i = 0: [3], [3] has length 1.
- i = 1: [3,1], [1] has length 1.
- i = 2: [3,1,5], [3,5] has length 2. [1,5] is also valid.
- i = 3: [3,1,5,6], [3,5,6] has length 3. [1,5,6] is also valid.
- i = 4: [3,1,5,6,4], [3,4] has length 2. [1,4] is also valid.
- i = 5: [3,1,5,6,4,2], [1,2] has length 2.
Constraints:
n == obstacles.length
1 <= n <= 105
1 <= obstacles[i] <= 107 | π Clean & Simple || 98% faster || Easy-Code π | 48 | find-the-longest-valid-obstacle-course-at-each-position | 0.469 | abhi9Rai | Hard | 27,574 | 1,964 |
number of strings that appear as substrings in word | class Solution:
def numOfStrings(self, patterns: List[str], word: str) -> int:
return sum(x in word for x in patterns) | https://leetcode.com/problems/number-of-strings-that-appear-as-substrings-in-word/discuss/1404073/Python3-1-line | 19 | Given an array of strings patterns and a string word, return the number of strings in patterns that exist as a substring in word.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: patterns = ["a","abc","bc","d"], word = "abc"
Output: 3
Explanation:
- "a" appears as a substring in "abc".
- "abc" appears as a substring in "abc".
- "bc" appears as a substring in "abc".
- "d" does not appear as a substring in "abc".
3 of the strings in patterns appear as a substring in word.
Example 2:
Input: patterns = ["a","b","c"], word = "aaaaabbbbb"
Output: 2
Explanation:
- "a" appears as a substring in "aaaaabbbbb".
- "b" appears as a substring in "aaaaabbbbb".
- "c" does not appear as a substring in "aaaaabbbbb".
2 of the strings in patterns appear as a substring in word.
Example 3:
Input: patterns = ["a","a","a"], word = "ab"
Output: 3
Explanation: Each of the patterns appears as a substring in word "ab".
Constraints:
1 <= patterns.length <= 100
1 <= patterns[i].length <= 100
1 <= word.length <= 100
patterns[i] and word consist of lowercase English letters. | [Python3] 1-line | 1,400 | number-of-strings-that-appear-as-substrings-in-word | 0.799 | ye15 | Easy | 27,576 | 1,967 |
array with elements not equal to average of neighbors | class Solution:
def rearrangeArray(self, nums: List[int]) -> List[int]:
nums.sort()
if len(nums)==3:
nums[1],nums[0] = nums[0],nums[1]
return nums
for i in range(1,len(nums)-1):
if nums[i]-nums[i-1] == nums[i+1]-nums[i]:
if i!=len(nums)-2:
nums[i+1],nums[i+2] = nums[i+2],nums[i+1]
if i==len(nums)-2:
nums[i+1],nums[0] = nums[0],nums[i+1]
return nums | https://leetcode.com/problems/array-with-elements-not-equal-to-average-of-neighbors/discuss/2280763/O(nlogn)-Solution-or-Python | 0 | You are given a 0-indexed array nums of distinct integers. You want to rearrange the elements in the array such that every element in the rearranged array is not equal to the average of its neighbors.
More formally, the rearranged array should have the property such that for every i in the range 1 <= i < nums.length - 1, (nums[i-1] + nums[i+1]) / 2 is not equal to nums[i].
Return any rearrangement of nums that meets the requirements.
Example 1:
Input: nums = [1,2,3,4,5]
Output: [1,2,4,5,3]
Explanation:
When i=1, nums[i] = 2, and the average of its neighbors is (1+4) / 2 = 2.5.
When i=2, nums[i] = 4, and the average of its neighbors is (2+5) / 2 = 3.5.
When i=3, nums[i] = 5, and the average of its neighbors is (4+3) / 2 = 3.5.
Example 2:
Input: nums = [6,2,0,9,7]
Output: [9,7,6,2,0]
Explanation:
When i=1, nums[i] = 7, and the average of its neighbors is (9+6) / 2 = 7.5.
When i=2, nums[i] = 6, and the average of its neighbors is (7+2) / 2 = 4.5.
When i=3, nums[i] = 2, and the average of its neighbors is (6+0) / 2 = 3.
Constraints:
3 <= nums.length <= 105
0 <= nums[i] <= 105 | O(nlogn) Solution | Python | 27 | array-with-elements-not-equal-to-average-of-neighbors | 0.496 | user7457RV | Medium | 27,600 | 1,968 |
minimum non zero product of the array elements | class Solution:
def minNonZeroProduct(self, p: int) -> int:
x = (1 << p) - 1
return pow(x-1, (x-1)//2, 1_000_000_007) * x % 1_000_000_007 | https://leetcode.com/problems/minimum-non-zero-product-of-the-array-elements/discuss/1403953/Python3-2-line | 6 | You are given a positive integer p. Consider an array nums (1-indexed) that consists of the integers in the inclusive range [1, 2p - 1] in their binary representations. You are allowed to do the following operation any number of times:
Choose two elements x and y from nums.
Choose a bit in x and swap it with its corresponding bit in y. Corresponding bit refers to the bit that is in the same position in the other integer.
For example, if x = 1101 and y = 0011, after swapping the 2nd bit from the right, we have x = 1111 and y = 0001.
Find the minimum non-zero product of nums after performing the above operation any number of times. Return this product modulo 109 + 7.
Note: The answer should be the minimum product before the modulo operation is done.
Example 1:
Input: p = 1
Output: 1
Explanation: nums = [1].
There is only one element, so the product equals that element.
Example 2:
Input: p = 2
Output: 6
Explanation: nums = [01, 10, 11].
Any swap would either make the product 0 or stay the same.
Thus, the array product of 1 * 2 * 3 = 6 is already minimized.
Example 3:
Input: p = 3
Output: 1512
Explanation: nums = [001, 010, 011, 100, 101, 110, 111]
- In the first operation we can swap the leftmost bit of the second and fifth elements.
- The resulting array is [001, 110, 011, 100, 001, 110, 111].
- In the second operation we can swap the middle bit of the third and fourth elements.
- The resulting array is [001, 110, 001, 110, 001, 110, 111].
The array product is 1 * 6 * 1 * 6 * 1 * 6 * 7 = 1512, which is the minimum possible product.
Constraints:
1 <= p <= 60 | [Python3] 2-line | 569 | minimum-non-zero-product-of-the-array-elements | 0.338 | ye15 | Medium | 27,603 | 1,969 |
last day where you can still cross | class Solution(object):
def latestDayToCross(self, row, col, cells):
l,h=0,len(cells)-1
ans=-1
while l<=h:
m=(l+h)>>1
if self.isPath(cells,m,row,col):
l=m+1
ans=m+1
else:
h=m-1
return ans
def isPath(self,cells,ind,row,col):
grid=[[0 for i in range(col)] for j in range(row)]
for i in range(ind+1):
x,y=cells[i]
grid[x-1][y-1]=1
vis=set()
for i in range(col):
if grid[0][i]!=1:
dq=deque()
dq.append((0,i))
dr=[(-1,0),(0,-1),(1,0),(0,1)]
while dq:
x,y=dq.popleft()
if x==row-1:
return True
for d in dr:
dx,dy=d
if 0<=x+dx<row and 0<=y+dy<col and grid[x+dx][y+dy]!=1 and (x+dx,y+dy) not in vis:
vis.add((x+dx,y+dy))
dq.append((x+dx,y+dy))
return False | https://leetcode.com/problems/last-day-where-you-can-still-cross/discuss/2489142/Python3-or-Binary-Search-%2B-BFS | 0 | There is a 1-based binary matrix where 0 represents land and 1 represents water. You are given integers row and col representing the number of rows and columns in the matrix, respectively.
Initially on day 0, the entire matrix is land. However, each day a new cell becomes flooded with water. You are given a 1-based 2D array cells, where cells[i] = [ri, ci] represents that on the ith day, the cell on the rith row and cith column (1-based coordinates) will be covered with water (i.e., changed to 1).
You want to find the last day that it is possible to walk from the top to the bottom by only walking on land cells. You can start from any cell in the top row and end at any cell in the bottom row. You can only travel in the four cardinal directions (left, right, up, and down).
Return the last day where it is possible to walk from the top to the bottom by only walking on land cells.
Example 1:
Input: row = 2, col = 2, cells = [[1,1],[2,1],[1,2],[2,2]]
Output: 2
Explanation: The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 2.
Example 2:
Input: row = 2, col = 2, cells = [[1,1],[1,2],[2,1],[2,2]]
Output: 1
Explanation: The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 1.
Example 3:
Input: row = 3, col = 3, cells = [[1,2],[2,1],[3,3],[2,2],[1,1],[1,3],[2,3],[3,2],[3,1]]
Output: 3
Explanation: The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 3.
Constraints:
2 <= row, col <= 2 * 104
4 <= row * col <= 2 * 104
cells.length == row * col
1 <= ri <= row
1 <= ci <= col
All the values of cells are unique. | [Python3] | Binary Search + BFS | 36 | last-day-where-you-can-still-cross | 0.495 | swapnilsingh421 | Hard | 27,606 | 1,970 |
find if path exists in graph | class Solution(object):
def validPath(self, n, edges, start, end):
"""
:type n: int
:type edges: List[List[int]]
:type start: int
:type end: int
:rtype: bool
"""
visited = [False]*n
d = {}
#store the undirected edges for both vertices
for i in edges:
if i[0] in d:
d[i[0]].append(i[1])
else:
d[i[0]] = [i[1]]
if i[1] in d:
d[i[1]].append(i[0])
else:
d[i[1]] = [i[0]]
#create a queue as we will apply BFS
q = [start]
while q:
curr = q.pop(0) #pop the first element as we do in queue
if curr == end: #if its the end then we can return True
return True
elif curr in d and not visited[curr]: #else if it is not the end then check whether its visited or not
q.extend(d[curr]) #add the adjacent vertices of the current node to the queue
visited[curr] = True #mark this curr vertex as visited = True, so that we dont visit this vertex again
return False #return False if the queue gets empty and we dont reach the end | https://leetcode.com/problems/find-if-path-exists-in-graph/discuss/1406782/Python-Easy-to-Understand-or-Beginners | 29 | There is a bi-directional graph with n vertices, where each vertex is labeled from 0 to n - 1 (inclusive). The edges in the graph are represented as a 2D integer array edges, where each edges[i] = [ui, vi] denotes a bi-directional edge between vertex ui and vertex vi. Every vertex pair is connected by at most one edge, and no vertex has an edge to itself.
You want to determine if there is a valid path that exists from vertex source to vertex destination.
Given edges and the integers n, source, and destination, return true if there is a valid path from source to destination, or false otherwise.
Example 1:
Input: n = 3, edges = [[0,1],[1,2],[2,0]], source = 0, destination = 2
Output: true
Explanation: There are two paths from vertex 0 to vertex 2:
- 0 β 1 β 2
- 0 β 2
Example 2:
Input: n = 6, edges = [[0,1],[0,2],[3,5],[5,4],[4,3]], source = 0, destination = 5
Output: false
Explanation: There is no path from vertex 0 to vertex 5.
Constraints:
1 <= n <= 2 * 105
0 <= edges.length <= 2 * 105
edges[i].length == 2
0 <= ui, vi <= n - 1
ui != vi
0 <= source, destination <= n - 1
There are no duplicate edges.
There are no self edges. | Python - Easy to Understand | Beginners | 6,800 | find-if-path-exists-in-graph | 0.504 | Sibu0811 | Easy | 27,608 | 1,971 |
minimum time to type word using special typewriter | class Solution:
def minTimeToType(self, word: str) -> int:
ans = len(word)
prev = "a"
for ch in word:
val = (ord(ch) - ord(prev)) % 26
ans += min(val, 26 - val)
prev = ch
return ans | https://leetcode.com/problems/minimum-time-to-type-word-using-special-typewriter/discuss/1417585/Python3-greedy | 48 | There is a special typewriter with lowercase English letters 'a' to 'z' arranged in a circle with a pointer. A character can only be typed if the pointer is pointing to that character. The pointer is initially pointing to the character 'a'.
Each second, you may perform one of the following operations:
Move the pointer one character counterclockwise or clockwise.
Type the character the pointer is currently on.
Given a string word, return the minimum number of seconds to type out the characters in word.
Example 1:
Input: word = "abc"
Output: 5
Explanation:
The characters are printed as follows:
- Type the character 'a' in 1 second since the pointer is initially on 'a'.
- Move the pointer clockwise to 'b' in 1 second.
- Type the character 'b' in 1 second.
- Move the pointer clockwise to 'c' in 1 second.
- Type the character 'c' in 1 second.
Example 2:
Input: word = "bza"
Output: 7
Explanation:
The characters are printed as follows:
- Move the pointer clockwise to 'b' in 1 second.
- Type the character 'b' in 1 second.
- Move the pointer counterclockwise to 'z' in 2 seconds.
- Type the character 'z' in 1 second.
- Move the pointer clockwise to 'a' in 1 second.
- Type the character 'a' in 1 second.
Example 3:
Input: word = "zjpc"
Output: 34
Explanation:
The characters are printed as follows:
- Move the pointer counterclockwise to 'z' in 1 second.
- Type the character 'z' in 1 second.
- Move the pointer clockwise to 'j' in 10 seconds.
- Type the character 'j' in 1 second.
- Move the pointer clockwise to 'p' in 6 seconds.
- Type the character 'p' in 1 second.
- Move the pointer counterclockwise to 'c' in 13 seconds.
- Type the character 'c' in 1 second.
Constraints:
1 <= word.length <= 100
word consists of lowercase English letters. | [Python3] greedy | 2,200 | minimum-time-to-type-word-using-special-typewriter | 0.714 | ye15 | Easy | 27,634 | 1,974 |
maximum matrix sum | class Solution:
def maxMatrixSum(self, matrix: List[List[int]]) -> int:
ans = mult = 0
val = inf
for i in range(len(matrix)):
for j in range(len(matrix)):
ans += abs(matrix[i][j])
val = min(val, abs(matrix[i][j]))
if matrix[i][j] < 0: mult ^= 1
return ans - 2*mult*val | https://leetcode.com/problems/maximum-matrix-sum/discuss/1417592/Python3-greedy | 12 | You are given an n x n integer matrix. You can do the following operation any number of times:
Choose any two adjacent elements of matrix and multiply each of them by -1.
Two elements are considered adjacent if and only if they share a border.
Your goal is to maximize the summation of the matrix's elements. Return the maximum sum of the matrix's elements using the operation mentioned above.
Example 1:
Input: matrix = [[1,-1],[-1,1]]
Output: 4
Explanation: We can follow the following steps to reach sum equals 4:
- Multiply the 2 elements in the first row by -1.
- Multiply the 2 elements in the first column by -1.
Example 2:
Input: matrix = [[1,2,3],[-1,-2,-3],[1,2,3]]
Output: 16
Explanation: We can follow the following step to reach sum equals 16:
- Multiply the 2 last elements in the second row by -1.
Constraints:
n == matrix.length == matrix[i].length
2 <= n <= 250
-105 <= matrix[i][j] <= 105 | [Python3] greedy | 581 | maximum-matrix-sum | 0.457 | ye15 | Medium | 27,647 | 1,975 |
number of ways to arrive at destination | class Solution:
def countPaths(self, n: int, roads: List[List[int]]) -> int:
graph = {}
for u, v, time in roads:
graph.setdefault(u, {})[v] = time
graph.setdefault(v, {})[u] = time
dist = [inf]*n
dist[-1] = 0
stack = [(n-1, 0)]
while stack:
x, t = stack.pop()
if t == dist[x]:
for xx in graph.get(x, {}):
if t + graph[x][xx] < dist[xx]:
dist[xx] = t + graph[x][xx]
stack.append((xx, t + graph[x][xx]))
@cache
def fn(x):
"""Return """
if x == n-1: return 1
if dist[x] == inf: return 0
ans = 0
for xx in graph.get(x, {}):
if graph[x][xx] + dist[xx] == dist[x]: ans += fn(xx)
return ans % 1_000_000_007
return fn(0) | https://leetcode.com/problems/number-of-ways-to-arrive-at-destination/discuss/1417598/Python3-dfs-%2B-dp | 5 | You are in a city that consists of n intersections numbered from 0 to n - 1 with bi-directional roads between some intersections. The inputs are generated such that you can reach any intersection from any other intersection and that there is at most one road between any two intersections.
You are given an integer n and a 2D integer array roads where roads[i] = [ui, vi, timei] means that there is a road between intersections ui and vi that takes timei minutes to travel. You want to know in how many ways you can travel from intersection 0 to intersection n - 1 in the shortest amount of time.
Return the number of ways you can arrive at your destination in the shortest amount of time. Since the answer may be large, return it modulo 109 + 7.
Example 1:
Input: n = 7, roads = [[0,6,7],[0,1,2],[1,2,3],[1,3,3],[6,3,3],[3,5,1],[6,5,1],[2,5,1],[0,4,5],[4,6,2]]
Output: 4
Explanation: The shortest amount of time it takes to go from intersection 0 to intersection 6 is 7 minutes.
The four ways to get there in 7 minutes are:
- 0 β 6
- 0 β 4 β 6
- 0 β 1 β 2 β 5 β 6
- 0 β 1 β 3 β 5 β 6
Example 2:
Input: n = 2, roads = [[1,0,10]]
Output: 1
Explanation: There is only one way to go from intersection 0 to intersection 1, and it takes 10 minutes.
Constraints:
1 <= n <= 200
n - 1 <= roads.length <= n * (n - 1) / 2
roads[i].length == 3
0 <= ui, vi <= n - 1
1 <= timei <= 109
ui != vi
There is at most one road connecting any two intersections.
You can reach any intersection from any other intersection. | [Python3] dfs + dp | 846 | number-of-ways-to-arrive-at-destination | 0.323 | ye15 | Medium | 27,653 | 1,976 |
number of ways to separate numbers | class Solution:
def numberOfCombinations(self, num: str) -> int:
n = len(num)
lcs = [[0]*(n+1) for _ in range(n)]
for i in reversed(range(n)):
for j in reversed(range(i+1, n)):
if num[i] == num[j]: lcs[i][j] = 1 + lcs[i+1][j+1]
def cmp(i, j, d):
"""Return True if """
m = lcs[i][j]
if m >= d: return True
return num[i+m] <= num[j+m]
dp = [[0]*(n+1) for _ in range(n)]
for i in range(n):
if num[i] != "0":
for j in range(i+1, n+1):
if i == 0: dp[i][j] = 1
else:
dp[i][j] = dp[i][j-1]
if 2*i-j >= 0 and cmp(2*i-j, i, j-i): dp[i][j] += dp[2*i-j][i]
if 2*i-j+1 >= 0 and not cmp(2*i-j+1, i, j-i-1): dp[i][j] += dp[2*i-j+1][i]
return sum(dp[i][n] for i in range(n)) % 1_000_000_007 | https://leetcode.com/problems/number-of-ways-to-separate-numbers/discuss/1424057/Python3-dp | 3 | You wrote down many positive integers in a string called num. However, you realized that you forgot to add commas to seperate the different numbers. You remember that the list of integers was non-decreasing and that no integer had leading zeros.
Return the number of possible lists of integers that you could have written down to get the string num. Since the answer may be large, return it modulo 109 + 7.
Example 1:
Input: num = "327"
Output: 2
Explanation: You could have written down the numbers:
3, 27
327
Example 2:
Input: num = "094"
Output: 0
Explanation: No numbers can have leading zeros and all numbers must be positive.
Example 3:
Input: num = "0"
Output: 0
Explanation: No numbers can have leading zeros and all numbers must be positive.
Constraints:
1 <= num.length <= 3500
num consists of digits '0' through '9'. | [Python3] dp | 367 | number-of-ways-to-separate-numbers | 0.209 | ye15 | Hard | 27,660 | 1,977 |
find greatest common divisor of array | class Solution:
def findGCD(self, nums: List[int]) -> int:
gcd = lambda a, b: a if b == 0 else gcd(b, a % b)
return gcd(max(nums), min(nums)) | https://leetcode.com/problems/find-greatest-common-divisor-of-array/discuss/2580234/2-lines-PythonJavascript-(no-built-in-gcd-function) | 1 | Given an integer array nums, return the greatest common divisor of the smallest number and largest number in nums.
The greatest common divisor of two numbers is the largest positive integer that evenly divides both numbers.
Example 1:
Input: nums = [2,5,6,9,10]
Output: 2
Explanation:
The smallest number in nums is 2.
The largest number in nums is 10.
The greatest common divisor of 2 and 10 is 2.
Example 2:
Input: nums = [7,5,6,8,3]
Output: 1
Explanation:
The smallest number in nums is 3.
The largest number in nums is 8.
The greatest common divisor of 3 and 8 is 1.
Example 3:
Input: nums = [3,3]
Output: 3
Explanation:
The smallest number in nums is 3.
The largest number in nums is 3.
The greatest common divisor of 3 and 3 is 3.
Constraints:
2 <= nums.length <= 1000
1 <= nums[i] <= 1000 | 2 lines Python/Javascript (no built in gcd function) | 125 | find-greatest-common-divisor-of-array | 0.767 | SmittyWerbenjagermanjensen | Easy | 27,661 | 1,979 |
find unique binary string | class Solution:
def findDifferentBinaryString(self, nums: List[str]) -> str:
return list(set(list((map(lambda x:"".join(list(map(str,x))),list(itertools.product([0,1],repeat=len(nums)))))))-set(nums))[0] | https://leetcode.com/problems/find-unique-binary-string/discuss/1657090/One-line-python-Solution | 2 | Given an array of strings nums containing n unique binary strings each of length n, return a binary string of length n that does not appear in nums. If there are multiple answers, you may return any of them.
Example 1:
Input: nums = ["01","10"]
Output: "11"
Explanation: "11" does not appear in nums. "00" would also be correct.
Example 2:
Input: nums = ["00","01"]
Output: "11"
Explanation: "11" does not appear in nums. "10" would also be correct.
Example 3:
Input: nums = ["111","011","001"]
Output: "101"
Explanation: "101" does not appear in nums. "000", "010", "100", and "110" would also be correct.
Constraints:
n == nums.length
1 <= n <= 16
nums[i].length == n
nums[i] is either '0' or '1'.
All the strings of nums are unique. | One line python Solution | 159 | find-unique-binary-string | 0.643 | amannarayansingh10 | Medium | 27,687 | 1,980 |
minimize the difference between target and chosen elements | class Solution:
def minimizeTheDifference(self, mat: List[List[int]], target: int) -> int:
# store the mxn size of the matrix
m = len(mat)
n = len(mat[0])
dp = defaultdict(defaultdict)
# Sorting each row of the array for more efficient pruning
# Note:this purely based on the observation on problem constraints (although interesting :))
for i in range(m):
mat[i] = sorted(mat[i])
# returns minimum absolute starting from from row i to n-1 for the target
globalMin = float("inf")
def findMinAbsDiff(i,prevSum):
nonlocal globalMin
if i == m:
globalMin = min(globalMin, abs(prevSum-target))
return abs(prevSum-target)
# pruning step 1
# because the array is increasing & prevSum & target will always be positive
if prevSum-target > globalMin:
return float("inf")
if (i in dp) and (prevSum in dp[i]):
return dp[i][prevSum]
minDiff = float("inf")
# for each candidate select that and backtrack
for j in range(n):
diff = findMinAbsDiff(i+1, prevSum+mat[i][j])
# pruning step 2 - break if we found minDiff 0 --> VERY CRTICIAL
if diff == 0:
minDiff = 0
break
minDiff = min(minDiff, diff)
dp[i][prevSum] = minDiff
return minDiff
return findMinAbsDiff(0, 0) | https://leetcode.com/problems/minimize-the-difference-between-target-and-chosen-elements/discuss/1418634/100-efficient-or-Pruning-%2B-Memoization-or-Dynamic-Programming-or-Explanation | 24 | You are given an m x n integer matrix mat and an integer target.
Choose one integer from each row in the matrix such that the absolute difference between target and the sum of the chosen elements is minimized.
Return the minimum absolute difference.
The absolute difference between two numbers a and b is the absolute value of a - b.
Example 1:
Input: mat = [[1,2,3],[4,5,6],[7,8,9]], target = 13
Output: 0
Explanation: One possible choice is to:
- Choose 1 from the first row.
- Choose 5 from the second row.
- Choose 7 from the third row.
The sum of the chosen elements is 13, which equals the target, so the absolute difference is 0.
Example 2:
Input: mat = [[1],[2],[3]], target = 100
Output: 94
Explanation: The best possible choice is to:
- Choose 1 from the first row.
- Choose 2 from the second row.
- Choose 3 from the third row.
The sum of the chosen elements is 6, and the absolute difference is 94.
Example 3:
Input: mat = [[1,2,9,8,7]], target = 6
Output: 1
Explanation: The best choice is to choose 7 from the first row.
The absolute difference is 1.
Constraints:
m == mat.length
n == mat[i].length
1 <= m, n <= 70
1 <= mat[i][j] <= 70
1 <= target <= 800 | β
100% efficient | Pruning + Memoization | Dynamic Programming | Explanation | 2,200 | minimize-the-difference-between-target-and-chosen-elements | 0.323 | CaptainX | Medium | 27,714 | 1,981 |
find array given subset sums | class Solution:
def recoverArray(self, n: int, sums: List[int]) -> List[int]:
res = [] # Result set
sums.sort()
while len(sums) > 1:
num = sums[-1] - sums[-2] # max - secondMax
countMap = Counter(sums) # Get count of each elements
excluding = [] # Subset sums that do NOT contain num
including = [] # Subset sums that contain num
for x in sums:
if countMap.get(x) > 0:
excluding.append(x)
including.append(x+num)
countMap[x] -= 1
countMap[x+num] -= 1
# Check validity of excluding set
if 0 in excluding:
sums = excluding
res.append(num)
else:
sums = including
res.append(-1*num)
return res | https://leetcode.com/problems/find-array-given-subset-sums/discuss/1431457/Easy-Explanation-for-Noobs-%2B-Python-code-with-comments | 57 | You are given an integer n representing the length of an unknown array that you are trying to recover. You are also given an array sums containing the values of all 2n subset sums of the unknown array (in no particular order).
Return the array ans of length n representing the unknown array. If multiple answers exist, return any of them.
An array sub is a subset of an array arr if sub can be obtained from arr by deleting some (possibly zero or all) elements of arr. The sum of the elements in sub is one possible subset sum of arr. The sum of an empty array is considered to be 0.
Note: Test cases are generated such that there will always be at least one correct answer.
Example 1:
Input: n = 3, sums = [-3,-2,-1,0,0,1,2,3]
Output: [1,2,-3]
Explanation: [1,2,-3] is able to achieve the given subset sums:
- []: sum is 0
- [1]: sum is 1
- [2]: sum is 2
- [1,2]: sum is 3
- [-3]: sum is -3
- [1,-3]: sum is -2
- [2,-3]: sum is -1
- [1,2,-3]: sum is 0
Note that any permutation of [1,2,-3] and also any permutation of [-1,-2,3] will also be accepted.
Example 2:
Input: n = 2, sums = [0,0,0,0]
Output: [0,0]
Explanation: The only correct answer is [0,0].
Example 3:
Input: n = 4, sums = [0,0,5,5,4,-1,4,9,9,-1,4,3,4,8,3,8]
Output: [0,-1,4,5]
Explanation: [0,-1,4,5] is able to achieve the given subset sums.
Constraints:
1 <= n <= 15
sums.length == 2n
-104 <= sums[i] <= 104 | Easy Explanation for Noobs + Python code with comments | 1,500 | find-array-given-subset-sums | 0.489 | sumit686215 | Hard | 27,718 | 1,982 |
minimum difference between highest and lowest of k scores | class Solution:
def minimumDifference(self, nums: List[int], k: int) -> int:
nums.sort()
return min(nums[i+k-1]-nums[i] for i in range(len(nums)-k+1)) | https://leetcode.com/problems/minimum-difference-between-highest-and-lowest-of-k-scores/discuss/1433298/Python3-greedy-2-line | 2 | You are given a 0-indexed integer array nums, where nums[i] represents the score of the ith student. You are also given an integer k.
Pick the scores of any k students from the array so that the difference between the highest and the lowest of the k scores is minimized.
Return the minimum possible difference.
Example 1:
Input: nums = [90], k = 1
Output: 0
Explanation: There is one way to pick score(s) of one student:
- [90]. The difference between the highest and lowest score is 90 - 90 = 0.
The minimum possible difference is 0.
Example 2:
Input: nums = [9,4,1,7], k = 2
Output: 2
Explanation: There are six ways to pick score(s) of two students:
- [9,4,1,7]. The difference between the highest and lowest score is 9 - 4 = 5.
- [9,4,1,7]. The difference between the highest and lowest score is 9 - 1 = 8.
- [9,4,1,7]. The difference between the highest and lowest score is 9 - 7 = 2.
- [9,4,1,7]. The difference between the highest and lowest score is 4 - 1 = 3.
- [9,4,1,7]. The difference between the highest and lowest score is 7 - 4 = 3.
- [9,4,1,7]. The difference between the highest and lowest score is 7 - 1 = 6.
The minimum possible difference is 2.
Constraints:
1 <= k <= nums.length <= 1000
0 <= nums[i] <= 105 | [Python3] greedy 2-line | 151 | minimum-difference-between-highest-and-lowest-of-k-scores | 0.536 | ye15 | Easy | 27,720 | 1,984 |
find the kth largest integer in the array | class Solution:
def kthLargestNumber(self, nums: List[str], k: int) -> str:
nums = sorted(map(int, nums), reverse=True)
return str(nums[k-1]) | https://leetcode.com/problems/find-the-kth-largest-integer-in-the-array/discuss/1432093/Python-or-The-Right-Way-during-Interview-or-Comparators | 28 | You are given an array of strings nums and an integer k. Each string in nums represents an integer without leading zeros.
Return the string that represents the kth largest integer in nums.
Note: Duplicate numbers should be counted distinctly. For example, if nums is ["1","2","2"], "2" is the first largest integer, "2" is the second-largest integer, and "1" is the third-largest integer.
Example 1:
Input: nums = ["3","6","7","10"], k = 4
Output: "3"
Explanation:
The numbers in nums sorted in non-decreasing order are ["3","6","7","10"].
The 4th largest integer in nums is "3".
Example 2:
Input: nums = ["2","21","12","1"], k = 3
Output: "2"
Explanation:
The numbers in nums sorted in non-decreasing order are ["1","2","12","21"].
The 3rd largest integer in nums is "2".
Example 3:
Input: nums = ["0","0"], k = 2
Output: "0"
Explanation:
The numbers in nums sorted in non-decreasing order are ["0","0"].
The 2nd largest integer in nums is "0".
Constraints:
1 <= k <= nums.length <= 104
1 <= nums[i].length <= 100
nums[i] consists of only digits.
nums[i] will not have any leading zeros. | Python | The Right Way during Interview | Comparators | 1,800 | find-the-kth-largest-integer-in-the-array | 0.447 | malraharsh | Medium | 27,738 | 1,985 |
minimum number of work sessions to finish the tasks | class Solution:
def minSessions(self, tasks: List[int], sessionTime: int) -> int:
subsets = []
self.ans = len(tasks)
def func(idx):
if len(subsets) >= self.ans:
return
if idx == len(tasks):
self.ans = min(self.ans, len(subsets))
return
for i in range(len(subsets)):
if subsets[i] + tasks[idx] <= sessionTime:
subsets[i] += tasks[idx]
func(idx + 1)
subsets[i] -= tasks[idx]
subsets.append(tasks[idx])
func(idx + 1)
subsets.pop()
func(0)
return self.ans | https://leetcode.com/problems/minimum-number-of-work-sessions-to-finish-the-tasks/discuss/1433054/Python-or-Backtracking-or-664ms-or-100-time-and-space-or-Explanation | 22 | There are n tasks assigned to you. The task times are represented as an integer array tasks of length n, where the ith task takes tasks[i] hours to finish. A work session is when you work for at most sessionTime consecutive hours and then take a break.
You should finish the given tasks in a way that satisfies the following conditions:
If you start a task in a work session, you must complete it in the same work session.
You can start a new task immediately after finishing the previous one.
You may complete the tasks in any order.
Given tasks and sessionTime, return the minimum number of work sessions needed to finish all the tasks following the conditions above.
The tests are generated such that sessionTime is greater than or equal to the maximum element in tasks[i].
Example 1:
Input: tasks = [1,2,3], sessionTime = 3
Output: 2
Explanation: You can finish the tasks in two work sessions.
- First work session: finish the first and the second tasks in 1 + 2 = 3 hours.
- Second work session: finish the third task in 3 hours.
Example 2:
Input: tasks = [3,1,3,1,1], sessionTime = 8
Output: 2
Explanation: You can finish the tasks in two work sessions.
- First work session: finish all the tasks except the last one in 3 + 1 + 3 + 1 = 8 hours.
- Second work session: finish the last task in 1 hour.
Example 3:
Input: tasks = [1,2,3,4,5], sessionTime = 15
Output: 1
Explanation: You can finish all the tasks in one work session.
Constraints:
n == tasks.length
1 <= n <= 14
1 <= tasks[i] <= 10
max(tasks[i]) <= sessionTime <= 15 | Python | Backtracking | 664ms | 100% time and space | Explanation | 1,000 | minimum-number-of-work-sessions-to-finish-the-tasks | 0.331 | detective_dp | Medium | 27,760 | 1,986 |
number of unique good subsequences | class Solution:
def numberOfUniqueGoodSubsequences(self, binary: str) -> int:
@cache
def fn(i, mask, v):
"""Return # unique good subsequences starting with 1."""
if i == len(binary) or not mask: return v
x = int(binary[i])
if not mask & (1<<x): return fn(i+1, mask, v)
return (fn(i+1, 3, 1) + fn(i+1, mask^(1<<x), v)) % 1_000_000_007
return fn(0, 2, 0) + int("0" in binary) | https://leetcode.com/problems/number-of-unique-good-subsequences/discuss/1433355/Python3-bit-mask-dp | 1 | You are given a binary string binary. A subsequence of binary is considered good if it is not empty and has no leading zeros (with the exception of "0").
Find the number of unique good subsequences of binary.
For example, if binary = "001", then all the good subsequences are ["0", "0", "1"], so the unique good subsequences are "0" and "1". Note that subsequences "00", "01", and "001" are not good because they have leading zeros.
Return the number of unique good subsequences of binary. Since the answer may be very large, return it modulo 109 + 7.
A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
Example 1:
Input: binary = "001"
Output: 2
Explanation: The good subsequences of binary are ["0", "0", "1"].
The unique good subsequences are "0" and "1".
Example 2:
Input: binary = "11"
Output: 2
Explanation: The good subsequences of binary are ["1", "1", "11"].
The unique good subsequences are "1" and "11".
Example 3:
Input: binary = "101"
Output: 5
Explanation: The good subsequences of binary are ["1", "0", "1", "10", "11", "101"].
The unique good subsequences are "0", "1", "10", "11", and "101".
Constraints:
1 <= binary.length <= 105
binary consists of only '0's and '1's. | [Python3] bit-mask dp | 139 | number-of-unique-good-subsequences | 0.524 | ye15 | Hard | 27,768 | 1,987 |
find the middle index in array | class Solution:
def findMiddleIndex(self, nums: List[int]) -> int:
left = 0 # nums[0] + nums[1] + ... + nums[middleIndex-1]
right = sum(nums) # nums[middleIndex+1] + nums[middleIndex+2] + ... + nums[nums.length-1]
for i, num in enumerate(nums): # we can use normal for loop as well.
right -= num # as we are trying to find out middle index so iteratively we`ll reduce the value of right to find the middle index
if left == right: # comparing the values for finding out the middle index.
return i # if there is any return the index whixh will be our required index.
left += num # we have to add the num iteratively.
return -1 | https://leetcode.com/problems/find-the-middle-index-in-array/discuss/2321632/Python-98.85-faster-or-Simplest-solution-with-explanation-or-Beg-to-Adv-or-Prefix-Sum | 8 | Given a 0-indexed integer array nums, find the leftmost middleIndex (i.e., the smallest amongst all the possible ones).
A middleIndex is an index where nums[0] + nums[1] + ... + nums[middleIndex-1] == nums[middleIndex+1] + nums[middleIndex+2] + ... + nums[nums.length-1].
If middleIndex == 0, the left side sum is considered to be 0. Similarly, if middleIndex == nums.length - 1, the right side sum is considered to be 0.
Return the leftmost middleIndex that satisfies the condition, or -1 if there is no such index.
Example 1:
Input: nums = [2,3,-1,8,4]
Output: 3
Explanation: The sum of the numbers before index 3 is: 2 + 3 + -1 = 4
The sum of the numbers after index 3 is: 4 = 4
Example 2:
Input: nums = [1,-1,4]
Output: 2
Explanation: The sum of the numbers before index 2 is: 1 + -1 = 0
The sum of the numbers after index 2 is: 0
Example 3:
Input: nums = [2,5]
Output: -1
Explanation: There is no valid middleIndex.
Constraints:
1 <= nums.length <= 100
-1000 <= nums[i] <= 1000
Note: This question is the same as 724: https://leetcode.com/problems/find-pivot-index/ | Python 98.85% faster | Simplest solution with explanation | Beg to Adv | Prefix Sum | 224 | find-the-middle-index-in-array | 0.673 | rlakshay14 | Easy | 27,770 | 1,991 |
find all groups of farmland | class Solution:
def findFarmland(self, land: List[List[int]]) -> List[List[int]]:
m, n = len(land), len(land[0])
ans = []
for i in range(m):
for j in range(n):
if land[i][j]: # found farmland
mini, minj = i, j
maxi, maxj = i, j
stack = [(i, j)]
land[i][j] = 0 # mark as visited
while stack:
i, j = stack.pop()
for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j):
if 0 <= ii < m and 0 <= jj < n and land[ii][jj]:
stack.append((ii, jj))
land[ii][jj] = 0
maxi = max(maxi, ii)
maxj = max(maxj, jj)
ans.append([mini, minj, maxi, maxj])
return ans | https://leetcode.com/problems/find-all-groups-of-farmland/discuss/1444115/Python3-dfs | 5 | You are given a 0-indexed m x n binary matrix land where a 0 represents a hectare of forested land and a 1 represents a hectare of farmland.
To keep the land organized, there are designated rectangular areas of hectares that consist entirely of farmland. These rectangular areas are called groups. No two groups are adjacent, meaning farmland in one group is not four-directionally adjacent to another farmland in a different group.
land can be represented by a coordinate system where the top left corner of land is (0, 0) and the bottom right corner of land is (m-1, n-1). Find the coordinates of the top left and bottom right corner of each group of farmland. A group of farmland with a top left corner at (r1, c1) and a bottom right corner at (r2, c2) is represented by the 4-length array [r1, c1, r2, c2].
Return a 2D array containing the 4-length arrays described above for each group of farmland in land. If there are no groups of farmland, return an empty array. You may return the answer in any order.
Example 1:
Input: land = [[1,0,0],[0,1,1],[0,1,1]]
Output: [[0,0,0,0],[1,1,2,2]]
Explanation:
The first group has a top left corner at land[0][0] and a bottom right corner at land[0][0].
The second group has a top left corner at land[1][1] and a bottom right corner at land[2][2].
Example 2:
Input: land = [[1,1],[1,1]]
Output: [[0,0,1,1]]
Explanation:
The first group has a top left corner at land[0][0] and a bottom right corner at land[1][1].
Example 3:
Input: land = [[0]]
Output: []
Explanation:
There are no groups of farmland.
Constraints:
m == land.length
n == land[i].length
1 <= m, n <= 300
land consists of only 0's and 1's.
Groups of farmland are rectangular in shape. | [Python3] dfs | 207 | find-all-groups-of-farmland | 0.687 | ye15 | Medium | 27,804 | 1,992 |
the number of good subsets | class Solution:
def numberOfGoodSubsets(self, nums: List[int]) -> int:
freq = [0] * 31
for x in nums: freq[x] += 1
masks = [0] * 31
for x in range(1, 31):
if x == 1: masks[x] = 0b10
else:
bits = 0
xx = x
for k in (2, 3, 5, 7, 11, 13, 17, 19, 23, 29):
while xx % k == 0:
if (bits >> k) & 1: break # repeated factors
bits ^= 1 << k
xx //= k
else: continue
break
else: masks[x] = bits
@cache
def fn(x, m):
"""Return number of good subsets."""
if x == 31: return int(m > 2)
ans = fn(x+1, m)
if freq[x] and masks[x]:
if x == 1: ans *= 2**freq[x]
elif not m & masks[x]: ans += freq[x] * fn(x+1, m | masks[x])
return ans % 1_000_000_007
return fn(1, 0) | https://leetcode.com/problems/the-number-of-good-subsets/discuss/1444318/Python3-dp | 2 | You are given an integer array nums. We call a subset of nums good if its product can be represented as a product of one or more distinct prime numbers.
For example, if nums = [1, 2, 3, 4]:
[2, 3], [1, 2, 3], and [1, 3] are good subsets with products 6 = 2*3, 6 = 2*3, and 3 = 3 respectively.
[1, 4] and [4] are not good subsets with products 4 = 2*2 and 4 = 2*2 respectively.
Return the number of different good subsets in nums modulo 109 + 7.
A subset of nums is any array that can be obtained by deleting some (possibly none or all) elements from nums. Two subsets are different if and only if the chosen indices to delete are different.
Example 1:
Input: nums = [1,2,3,4]
Output: 6
Explanation: The good subsets are:
- [1,2]: product is 2, which is the product of distinct prime 2.
- [1,2,3]: product is 6, which is the product of distinct primes 2 and 3.
- [1,3]: product is 3, which is the product of distinct prime 3.
- [2]: product is 2, which is the product of distinct prime 2.
- [2,3]: product is 6, which is the product of distinct primes 2 and 3.
- [3]: product is 3, which is the product of distinct prime 3.
Example 2:
Input: nums = [4,2,3,15]
Output: 5
Explanation: The good subsets are:
- [2]: product is 2, which is the product of distinct prime 2.
- [2,3]: product is 6, which is the product of distinct primes 2 and 3.
- [2,15]: product is 30, which is the product of distinct primes 2, 3, and 5.
- [3]: product is 3, which is the product of distinct prime 3.
- [15]: product is 15, which is the product of distinct primes 3 and 5.
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 30 | [Python3] dp | 203 | the-number-of-good-subsets | 0.344 | ye15 | Hard | 27,820 | 1,994 |
count special quadruplets | class Solution:
def countQuadruplets(self, nums: List[int]) -> int:
idx = defaultdict(list)
for i in range(len(nums)-1):
for j in range(i+1, len(nums)):
idx[nums[j]-nums[i]].append(i)
count = 0
for i in range(len(nums)-3):
for j in range(i+1, len(nums)-2):
count += sum(k > j for k in idx[nums[i]+nums[j]])
return count | https://leetcode.com/problems/count-special-quadruplets/discuss/1445362/Python-non-brute-force.-Time%3A-O(N2)-Space%3A-O(N2) | 4 | Given a 0-indexed integer array nums, return the number of distinct quadruplets (a, b, c, d) such that:
nums[a] + nums[b] + nums[c] == nums[d], and
a < b < c < d
Example 1:
Input: nums = [1,2,3,6]
Output: 1
Explanation: The only quadruplet that satisfies the requirement is (0, 1, 2, 3) because 1 + 2 + 3 == 6.
Example 2:
Input: nums = [3,3,6,4,5]
Output: 0
Explanation: There are no such quadruplets in [3,3,6,4,5].
Example 3:
Input: nums = [1,1,1,3,5]
Output: 4
Explanation: The 4 quadruplets that satisfy the requirement are:
- (0, 1, 2, 3): 1 + 1 + 1 == 3
- (0, 1, 3, 4): 1 + 1 + 3 == 5
- (0, 2, 3, 4): 1 + 1 + 3 == 5
- (1, 2, 3, 4): 1 + 1 + 3 == 5
Constraints:
4 <= nums.length <= 50
1 <= nums[i] <= 100 | Python, non-brute force. Time: O(N^2), Space: O(N^2) | 729 | count-special-quadruplets | 0.593 | blue_sky5 | Easy | 27,822 | 1,995 |
the number of weak characters in the game | class Solution:
def numberOfWeakCharacters(self, properties: List[List[int]]) -> int:
properties.sort(key=lambda x: (-x[0],x[1]))
ans = 0
curr_max = 0
for _, d in properties:
if d < curr_max:
ans += 1
else:
curr_max = d
return ans | https://leetcode.com/problems/the-number-of-weak-characters-in-the-game/discuss/1445198/Python-Sort | 209 | You are playing a game that contains multiple characters, and each of the characters has two main properties: attack and defense. You are given a 2D integer array properties where properties[i] = [attacki, defensei] represents the properties of the ith character in the game.
A character is said to be weak if any other character has both attack and defense levels strictly greater than this character's attack and defense levels. More formally, a character i is said to be weak if there exists another character j where attackj > attacki and defensej > defensei.
Return the number of weak characters.
Example 1:
Input: properties = [[5,5],[6,3],[3,6]]
Output: 0
Explanation: No character has strictly greater attack and defense than the other.
Example 2:
Input: properties = [[2,2],[3,3]]
Output: 1
Explanation: The first character is weak because the second character has a strictly greater attack and defense.
Example 3:
Input: properties = [[1,5],[10,4],[4,3]]
Output: 1
Explanation: The third character is weak because the second character has a strictly greater attack and defense.
Constraints:
2 <= properties.length <= 105
properties[i].length == 2
1 <= attacki, defensei <= 105 | Python - Sort | 9,000 | the-number-of-weak-characters-in-the-game | 0.44 | lokeshsenthilkumar | Medium | 27,837 | 1,996 |
first day where you have been in all the rooms | class Solution:
def firstDayBeenInAllRooms(self, nextVisit: List[int]) -> int:
odd = [0]
even = [1]
for i in range(1, len(nextVisit)):
odd.append((even[-1] + 1) % 1_000_000_007)
even.append((2*odd[-1] - odd[nextVisit[i]] + 1) % 1_000_000_007)
return odd[-1] | https://leetcode.com/problems/first-day-where-you-have-been-in-all-the-rooms/discuss/1446619/Python3-dp | 3 | There are n rooms you need to visit, labeled from 0 to n - 1. Each day is labeled, starting from 0. You will go in and visit one room a day.
Initially on day 0, you visit room 0. The order you visit the rooms for the coming days is determined by the following rules and a given 0-indexed array nextVisit of length n:
Assuming that on a day, you visit room i,
if you have been in room i an odd number of times (including the current visit), on the next day you will visit a room with a lower or equal room number specified by nextVisit[i] where 0 <= nextVisit[i] <= i;
if you have been in room i an even number of times (including the current visit), on the next day you will visit room (i + 1) mod n.
Return the label of the first day where you have been in all the rooms. It can be shown that such a day exists. Since the answer may be very large, return it modulo 109 + 7.
Example 1:
Input: nextVisit = [0,0]
Output: 2
Explanation:
- On day 0, you visit room 0. The total times you have been in room 0 is 1, which is odd.
On the next day you will visit room nextVisit[0] = 0
- On day 1, you visit room 0, The total times you have been in room 0 is 2, which is even.
On the next day you will visit room (0 + 1) mod 2 = 1
- On day 2, you visit room 1. This is the first day where you have been in all the rooms.
Example 2:
Input: nextVisit = [0,0,2]
Output: 6
Explanation:
Your room visiting order for each day is: [0,0,1,0,0,1,2,...].
Day 6 is the first day where you have been in all the rooms.
Example 3:
Input: nextVisit = [0,1,2,0]
Output: 6
Explanation:
Your room visiting order for each day is: [0,0,1,1,2,2,3,...].
Day 6 is the first day where you have been in all the rooms.
Constraints:
n == nextVisit.length
2 <= n <= 105
0 <= nextVisit[i] <= i | [Python3] dp | 139 | first-day-where-you-have-been-in-all-the-rooms | 0.367 | ye15 | Medium | 27,870 | 1,997 |
reverse prefix of word | class Solution:
def reversePrefix(self, word: str, ch: str) -> str:
try:
ix = word.index(ch)
return word[:ix+1][::-1] + word[ix+1:]
except ValueError:
return word | https://leetcode.com/problems/reverse-prefix-of-word/discuss/1472737/Easy-Python-Solution-(28ms)-or-Faster-than-93 | 6 | Given a 0-indexed string word and a character ch, reverse the segment of word that starts at index 0 and ends at the index of the first occurrence of ch (inclusive). If the character ch does not exist in word, do nothing.
For example, if word = "abcdefd" and ch = "d", then you should reverse the segment that starts at 0 and ends at 3 (inclusive). The resulting string will be "dcbaefd".
Return the resulting string.
Example 1:
Input: word = "abcdefd", ch = "d"
Output: "dcbaefd"
Explanation: The first occurrence of "d" is at index 3.
Reverse the part of word from 0 to 3 (inclusive), the resulting string is "dcbaefd".
Example 2:
Input: word = "xyxzxe", ch = "z"
Output: "zxyxxe"
Explanation: The first and only occurrence of "z" is at index 3.
Reverse the part of word from 0 to 3 (inclusive), the resulting string is "zxyxxe".
Example 3:
Input: word = "abcd", ch = "z"
Output: "abcd"
Explanation: "z" does not exist in word.
You should not do any reverse operation, the resulting string is "abcd".
Constraints:
1 <= word.length <= 250
word consists of lowercase English letters.
ch is a lowercase English letter. | Easy Python Solution (28ms) | Faster than 93% | 506 | reverse-prefix-of-word | 0.778 | the_sky_high | Easy | 27,875 | 2,000 |
number of pairs of interchangeable rectangles | class Solution:
def interchangeableRectangles(self, rectangles: List[List[int]]) -> int:
preSum = []
for rec in rectangles:
preSum.append(rec[1]/rec[0])
dic1 = {}
for i in range(len(preSum)-1, -1, -1):
if preSum[i] not in dic1.keys():
dic1[preSum[i]] = [0,1]
else:
dic1[preSum[i]][0] = dic1[preSum[i]][0] + dic1[preSum[i]][1]
dic1[preSum[i]][1] += 1
return sum ([v[0] for v in dic1.values()]) | https://leetcode.com/problems/number-of-pairs-of-interchangeable-rectangles/discuss/2818774/O(n)-solution-of-Combined-Dictionary-and-Pre-sum-in-Python | 0 | You are given n rectangles represented by a 0-indexed 2D integer array rectangles, where rectangles[i] = [widthi, heighti] denotes the width and height of the ith rectangle.
Two rectangles i and j (i < j) are considered interchangeable if they have the same width-to-height ratio. More formally, two rectangles are interchangeable if widthi/heighti == widthj/heightj (using decimal division, not integer division).
Return the number of pairs of interchangeable rectangles in rectangles.
Example 1:
Input: rectangles = [[4,8],[3,6],[10,20],[15,30]]
Output: 6
Explanation: The following are the interchangeable pairs of rectangles by index (0-indexed):
- Rectangle 0 with rectangle 1: 4/8 == 3/6.
- Rectangle 0 with rectangle 2: 4/8 == 10/20.
- Rectangle 0 with rectangle 3: 4/8 == 15/30.
- Rectangle 1 with rectangle 2: 3/6 == 10/20.
- Rectangle 1 with rectangle 3: 3/6 == 15/30.
- Rectangle 2 with rectangle 3: 10/20 == 15/30.
Example 2:
Input: rectangles = [[4,5],[7,8]]
Output: 0
Explanation: There are no interchangeable pairs of rectangles.
Constraints:
n == rectangles.length
1 <= n <= 105
rectangles[i].length == 2
1 <= widthi, heighti <= 105 | O(n) solution of Combined Dictionary and Pre sum in Python | 3 | number-of-pairs-of-interchangeable-rectangles | 0.451 | DNST | Medium | 27,917 | 2,001 |
maximum product of the length of two palindromic subsequences | class Solution:
def maxProduct(self, s: str) -> int:
subs = []
n = len(s)
def dfs(curr, ind, inds):
if ind == n:
if curr == curr[::-1]:
subs.append((curr, inds))
return
dfs(curr+s[ind], ind+1, inds|{ind})
dfs(curr, ind+1, inds)
dfs('', 0, set())
res = 0
n = len(subs)
for i in range(n):
s1, i1 = subs[i]
for j in range(i+1, n):
s2, i2 = subs[j]
if len(i1 & i2) == 0:
res = max(res, len(s1)*len(s2))
return res | https://leetcode.com/problems/maximum-product-of-the-length-of-two-palindromic-subsequences/discuss/1458484/Python-Bruteforce | 3 | Given a string s, find two disjoint palindromic subsequences of s such that the product of their lengths is maximized. The two subsequences are disjoint if they do not both pick a character at the same index.
Return the maximum possible product of the lengths of the two palindromic subsequences.
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. A string is palindromic if it reads the same forward and backward.
Example 1:
Input: s = "leetcodecom"
Output: 9
Explanation: An optimal solution is to choose "ete" for the 1st subsequence and "cdc" for the 2nd subsequence.
The product of their lengths is: 3 * 3 = 9.
Example 2:
Input: s = "bb"
Output: 1
Explanation: An optimal solution is to choose "b" (the first character) for the 1st subsequence and "b" (the second character) for the 2nd subsequence.
The product of their lengths is: 1 * 1 = 1.
Example 3:
Input: s = "accbcaxxcxx"
Output: 25
Explanation: An optimal solution is to choose "accca" for the 1st subsequence and "xxcxx" for the 2nd subsequence.
The product of their lengths is: 5 * 5 = 25.
Constraints:
2 <= s.length <= 12
s consists of lowercase English letters only. | Python - Bruteforce | 232 | maximum-product-of-the-length-of-two-palindromic-subsequences | 0.533 | ajith6198 | Medium | 27,929 | 2,002 |
smallest missing genetic value in each subtree | class Solution:
def smallestMissingValueSubtree(self, parents: List[int], nums: List[int]) -> List[int]:
ans = [1] * len(parents)
if 1 in nums:
tree = {}
for i, x in enumerate(parents):
tree.setdefault(x, []).append(i)
k = nums.index(1)
val = 1
seen = set()
while k != -1:
stack = [k]
while stack:
x = stack.pop()
seen.add(nums[x])
for xx in tree.get(x, []):
if nums[xx] not in seen:
stack.append(xx)
seen.add(nums[xx])
while val in seen: val += 1
ans[k] = val
k = parents[k]
return ans | https://leetcode.com/problems/smallest-missing-genetic-value-in-each-subtree/discuss/1461767/Python3-dfs | 0 | There is a family tree rooted at 0 consisting of n nodes numbered 0 to n - 1. You are given a 0-indexed integer array parents, where parents[i] is the parent for node i. Since node 0 is the root, parents[0] == -1.
There are 105 genetic values, each represented by an integer in the inclusive range [1, 105]. You are given a 0-indexed integer array nums, where nums[i] is a distinct genetic value for node i.
Return an array ans of length n where ans[i] is the smallest genetic value that is missing from the subtree rooted at node i.
The subtree rooted at a node x contains node x and all of its descendant nodes.
Example 1:
Input: parents = [-1,0,0,2], nums = [1,2,3,4]
Output: [5,1,1,1]
Explanation: The answer for each subtree is calculated as follows:
- 0: The subtree contains nodes [0,1,2,3] with values [1,2,3,4]. 5 is the smallest missing value.
- 1: The subtree contains only node 1 with value 2. 1 is the smallest missing value.
- 2: The subtree contains nodes [2,3] with values [3,4]. 1 is the smallest missing value.
- 3: The subtree contains only node 3 with value 4. 1 is the smallest missing value.
Example 2:
Input: parents = [-1,0,1,0,3,3], nums = [5,4,6,2,1,3]
Output: [7,1,1,4,2,1]
Explanation: The answer for each subtree is calculated as follows:
- 0: The subtree contains nodes [0,1,2,3,4,5] with values [5,4,6,2,1,3]. 7 is the smallest missing value.
- 1: The subtree contains nodes [1,2] with values [4,6]. 1 is the smallest missing value.
- 2: The subtree contains only node 2 with value 6. 1 is the smallest missing value.
- 3: The subtree contains nodes [3,4,5] with values [2,1,3]. 4 is the smallest missing value.
- 4: The subtree contains only node 4 with value 1. 2 is the smallest missing value.
- 5: The subtree contains only node 5 with value 3. 1 is the smallest missing value.
Example 3:
Input: parents = [-1,2,3,0,2,4,1], nums = [2,3,4,5,6,7,8]
Output: [1,1,1,1,1,1,1]
Explanation: The value 1 is missing from all the subtrees.
Constraints:
n == parents.length == nums.length
2 <= n <= 105
0 <= parents[i] <= n - 1 for i != 0
parents[0] == -1
parents represents a valid tree.
1 <= nums[i] <= 105
Each nums[i] is distinct. | [Python3] dfs | 89 | smallest-missing-genetic-value-in-each-subtree | 0.443 | ye15 | Hard | 27,936 | 2,003 |
count number of pairs with absolute difference k | class Solution:
def countKDifference(self, nums: List[int], k: int) -> int:
seen = defaultdict(int)
counter = 0
for num in nums:
tmp, tmp2 = num - k, num + k
if tmp in seen:
counter += seen[tmp]
if tmp2 in seen:
counter += seen[tmp2]
seen[num] += 1
return counter | https://leetcode.com/problems/count-number-of-pairs-with-absolute-difference-k/discuss/1471015/Python-Clean-and-concise.-Dictionary-T.C-O(N) | 36 | Given an integer array nums and an integer k, return the number of pairs (i, j) where i < j such that |nums[i] - nums[j]| == k.
The value of |x| is defined as:
x if x >= 0.
-x if x < 0.
Example 1:
Input: nums = [1,2,2,1], k = 1
Output: 4
Explanation: The pairs with an absolute difference of 1 are:
- [1,2,2,1]
- [1,2,2,1]
- [1,2,2,1]
- [1,2,2,1]
Example 2:
Input: nums = [1,3], k = 3
Output: 0
Explanation: There are no pairs with an absolute difference of 3.
Example 3:
Input: nums = [3,2,1,5,4], k = 2
Output: 3
Explanation: The pairs with an absolute difference of 2 are:
- [3,2,1,5,4]
- [3,2,1,5,4]
- [3,2,1,5,4]
Constraints:
1 <= nums.length <= 200
1 <= nums[i] <= 100
1 <= k <= 99 | [Python] Clean & concise. Dictionary T.C O(N) | 3,700 | count-number-of-pairs-with-absolute-difference-k | 0.823 | asbefu | Easy | 27,937 | 2,006 |
find original array from doubled array | class Solution:
def findOriginalArray(self, changed: List[int]) -> List[int]:
"""
The idea is to:
1st sort the numbers
2nd Create a counter to save the frequency of each number
3nd iterate the array and for each number check if the double exists.
4rd after taking len(changed) // 2 numbers return the answer
Time complexity: O(nlog(n))
Space complexity: O(n)
"""
if len(changed) % 2 != 0: # If there are not even amount the numbers there is no solution.
return []
changed.sort()
c = Counter(changed) # The counter is needed because we have 0s
answer = []
for num in changed:
if num in c and c[num] >= 1: # Check if the number is available (we may have taken it before)
c[num] -= 1 # we mark the number as used by decreasing the counter (only needed for the zeros)
if (num * 2) in c and c[(num * 2)] >= 1: # Take the one that doubles it if exists
answer.append(num)
c[num*2] -= 1 # The number has been taken.
if len(answer) == len(changed) // 2:
return answer
return [] | https://leetcode.com/problems/find-original-array-from-doubled-array/discuss/1470895/Python-Sorting.-Easy-to-understand-and-clean-T.C%3A-O(n-log-n)-S.C%3A-O(N) | 13 | An integer array original is transformed into a doubled array changed by appending twice the value of every element in original, and then randomly shuffling the resulting array.
Given an array changed, return original if changed is a doubled array. If changed is not a doubled array, return an empty array. The elements in original may be returned in any order.
Example 1:
Input: changed = [1,3,4,2,6,8]
Output: [1,3,4]
Explanation: One possible original array could be [1,3,4]:
- Twice the value of 1 is 1 * 2 = 2.
- Twice the value of 3 is 3 * 2 = 6.
- Twice the value of 4 is 4 * 2 = 8.
Other original arrays could be [4,3,1] or [3,1,4].
Example 2:
Input: changed = [6,3,0,1]
Output: []
Explanation: changed is not a doubled array.
Example 3:
Input: changed = [1]
Output: []
Explanation: changed is not a doubled array.
Constraints:
1 <= changed.length <= 105
0 <= changed[i] <= 105 | [Python] Sorting. Easy to understand and clean T.C: O(n log n) S.C: O(N) | 981 | find-original-array-from-doubled-array | 0.409 | asbefu | Medium | 27,983 | 2,007 |
maximum earnings from taxi | class Solution:
def maxTaxiEarnings(self, n: int, rides: List[List[int]]) -> int:
d = {}
for start,end,tip in rides:
if end not in d:
d[end] =[[start,tip]]
else:
d[end].append([start,tip])
dp = [0]*(n+1)
dp[0] = 0
for i in range(1,n+1):
dp[i] = dp[i-1]
if i in d:
temp_profit = 0
for start,tip in d[i]:
if (i-start)+tip+dp[start] > temp_profit:
temp_profit = i-start+tip+dp[start]
dp[i] = max(dp[i],temp_profit)
return dp[-1] | https://leetcode.com/problems/maximum-earnings-from-taxi/discuss/1485339/Python-Solution-Maximum-Earnings-from-Taxi | 2 | There are n points on a road you are driving your taxi on. The n points on the road are labeled from 1 to n in the direction you are going, and you want to drive from point 1 to point n to make money by picking up passengers. You cannot change the direction of the taxi.
The passengers are represented by a 0-indexed 2D integer array rides, where rides[i] = [starti, endi, tipi] denotes the ith passenger requesting a ride from point starti to point endi who is willing to give a tipi dollar tip.
For each passenger i you pick up, you earn endi - starti + tipi dollars. You may only drive at most one passenger at a time.
Given n and rides, return the maximum number of dollars you can earn by picking up the passengers optimally.
Note: You may drop off a passenger and pick up a different passenger at the same point.
Example 1:
Input: n = 5, rides = [[2,5,4],[1,5,1]]
Output: 7
Explanation: We can pick up passenger 0 to earn 5 - 2 + 4 = 7 dollars.
Example 2:
Input: n = 20, rides = [[1,6,1],[3,10,2],[10,12,3],[11,12,2],[12,15,2],[13,18,1]]
Output: 20
Explanation: We will pick up the following passengers:
- Drive passenger 1 from point 3 to point 10 for a profit of 10 - 3 + 2 = 9 dollars.
- Drive passenger 2 from point 10 to point 12 for a profit of 12 - 10 + 3 = 5 dollars.
- Drive passenger 5 from point 13 to point 18 for a profit of 18 - 13 + 1 = 6 dollars.
We earn 9 + 5 + 6 = 20 dollars in total.
Constraints:
1 <= n <= 105
1 <= rides.length <= 3 * 104
rides[i].length == 3
1 <= starti < endi <= n
1 <= tipi <= 105 | [Python] Solution - Maximum Earnings from Taxi | 2,100 | maximum-earnings-from-taxi | 0.432 | SaSha59 | Medium | 28,021 | 2,008 |
minimum number of operations to make array continuous | class Solution:
def minOperations(self, nums: List[int]) -> int:
n = len(nums)
nums = sorted(set(nums))
ans = ii = 0
for i, x in enumerate(nums):
if x - nums[ii] >= n: ii += 1
ans = max(ans, i - ii + 1)
return n - ans | https://leetcode.com/problems/minimum-number-of-operations-to-make-array-continuous/discuss/1471593/Python3-sliding-window | 5 | You are given an integer array nums. In one operation, you can replace any element in nums with any integer.
nums is considered continuous if both of the following conditions are fulfilled:
All elements in nums are unique.
The difference between the maximum element and the minimum element in nums equals nums.length - 1.
For example, nums = [4, 2, 5, 3] is continuous, but nums = [1, 2, 3, 5, 6] is not continuous.
Return the minimum number of operations to make nums continuous.
Example 1:
Input: nums = [4,2,5,3]
Output: 0
Explanation: nums is already continuous.
Example 2:
Input: nums = [1,2,3,5,6]
Output: 1
Explanation: One possible solution is to change the last element to 4.
The resulting array is [1,2,3,5,4], which is continuous.
Example 3:
Input: nums = [1,10,100,1000]
Output: 3
Explanation: One possible solution is to:
- Change the second element to 2.
- Change the third element to 3.
- Change the fourth element to 4.
The resulting array is [1,2,3,4], which is continuous.
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 109 | [Python3] sliding window | 218 | minimum-number-of-operations-to-make-array-continuous | 0.458 | ye15 | Hard | 28,030 | 2,009 |
final value of variable after performing operations | class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
x = 0
for o in operations:
if '+' in o:
x += 1
else:
x -= 1
return x | https://leetcode.com/problems/final-value-of-variable-after-performing-operations/discuss/1472568/Python3-A-Simple-Solution-and-A-One-Line-Solution | 18 | There is a programming language with only four operations and one variable X:
++X and X++ increments the value of the variable X by 1.
--X and X-- decrements the value of the variable X by 1.
Initially, the value of X is 0.
Given an array of strings operations containing a list of operations, return the final value of X after performing all the operations.
Example 1:
Input: operations = ["--X","X++","X++"]
Output: 1
Explanation: The operations are performed as follows:
Initially, X = 0.
--X: X is decremented by 1, X = 0 - 1 = -1.
X++: X is incremented by 1, X = -1 + 1 = 0.
X++: X is incremented by 1, X = 0 + 1 = 1.
Example 2:
Input: operations = ["++X","++X","X++"]
Output: 3
Explanation: The operations are performed as follows:
Initially, X = 0.
++X: X is incremented by 1, X = 0 + 1 = 1.
++X: X is incremented by 1, X = 1 + 1 = 2.
X++: X is incremented by 1, X = 2 + 1 = 3.
Example 3:
Input: operations = ["X++","++X","--X","X--"]
Output: 0
Explanation: The operations are performed as follows:
Initially, X = 0.
X++: X is incremented by 1, X = 0 + 1 = 1.
++X: X is incremented by 1, X = 1 + 1 = 2.
--X: X is decremented by 1, X = 2 - 1 = 1.
X--: X is decremented by 1, X = 1 - 1 = 0.
Constraints:
1 <= operations.length <= 100
operations[i] will be either "++X", "X++", "--X", or "X--". | [Python3] A Simple Solution and A One Line Solution | 1,800 | final-value-of-variable-after-performing-operations | 0.888 | terrencetang | Easy | 28,035 | 2,011 |
sum of beauty in the array | class Solution:
def sumOfBeauties(self, nums: List[int]) -> int:
beauty=[0]*len(nums)
for i in range(1,len(nums)-1):
leftarr=nums[:i]
rightarr=nums[i+1:]
if(max(leftarr)<nums[i] and min(rightarr)>nums[i]):
beauty[i]=2
elif(nums[i-1]<nums[i] and nums[i+1]>nums[i]):
beauty[i]=1
else:
beauty[i]=0
return sum(beauty) | https://leetcode.com/problems/sum-of-beauty-in-the-array/discuss/1477177/Python3-or-Brute-Force-(TLE)-and-O(n)-solution-with-explanation-or-86ile-runtime | 1 | You are given a 0-indexed integer array nums. For each index i (1 <= i <= nums.length - 2) the beauty of nums[i] equals:
2, if nums[j] < nums[i] < nums[k], for all 0 <= j < i and for all i < k <= nums.length - 1.
1, if nums[i - 1] < nums[i] < nums[i + 1], and the previous condition is not satisfied.
0, if none of the previous conditions holds.
Return the sum of beauty of all nums[i] where 1 <= i <= nums.length - 2.
Example 1:
Input: nums = [1,2,3]
Output: 2
Explanation: For each index i in the range 1 <= i <= 1:
- The beauty of nums[1] equals 2.
Example 2:
Input: nums = [2,4,6,4]
Output: 1
Explanation: For each index i in the range 1 <= i <= 2:
- The beauty of nums[1] equals 1.
- The beauty of nums[2] equals 0.
Example 3:
Input: nums = [3,2,1]
Output: 0
Explanation: For each index i in the range 1 <= i <= 1:
- The beauty of nums[1] equals 0.
Constraints:
3 <= nums.length <= 105
1 <= nums[i] <= 105 | Python3 | Brute Force (TLE) and O(n) solution with explanation | 86%ile runtime | 54 | sum-of-beauty-in-the-array | 0.467 | aaditya47 | Medium | 28,091 | 2,012 |
longest subsequence repeated k times | class Solution:
def longestSubsequenceRepeatedK(self, s: str, k: int) -> str:
freq = [0] * 26
for ch in s: freq[ord(ch)-97] += 1
cand = [chr(i+97) for i, x in enumerate(freq) if x >= k] # valid candidates
def fn(ss):
"""Return True if ss is a k-repeated sub-sequence of s."""
i = cnt = 0
for ch in s:
if ss[i] == ch:
i += 1
if i == len(ss):
if (cnt := cnt + 1) == k: return True
i = 0
return False
ans = ""
queue = deque([""])
while queue:
x = queue.popleft()
for ch in cand:
xx = x + ch
if fn(xx):
ans = xx
queue.append(xx)
return ans | https://leetcode.com/problems/longest-subsequence-repeated-k-times/discuss/1477019/Python3-bfs | 9 | You are given a string s of length n, and an integer k. You are tasked to find the longest subsequence repeated k times in string s.
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.
A subsequence seq is repeated k times in the string s if seq * k is a subsequence of s, where seq * k represents a string constructed by concatenating seq k times.
For example, "bba" is repeated 2 times in the string "bababcba", because the string "bbabba", constructed by concatenating "bba" 2 times, is a subsequence of the string "bababcba".
Return the longest subsequence repeated k times in string s. If multiple such subsequences are found, return the lexicographically largest one. If there is no such subsequence, return an empty string.
Example 1:
Input: s = "letsleetcode", k = 2
Output: "let"
Explanation: There are two longest subsequences repeated 2 times: "let" and "ete".
"let" is the lexicographically largest one.
Example 2:
Input: s = "bb", k = 2
Output: "b"
Explanation: The longest subsequence repeated 2 times is "b".
Example 3:
Input: s = "ab", k = 2
Output: ""
Explanation: There is no subsequence repeated 2 times. Empty string is returned.
Constraints:
n == s.length
2 <= n, k <= 2000
2 <= n < k * 8
s consists of lowercase English letters. | [Python3] bfs | 409 | longest-subsequence-repeated-k-times | 0.556 | ye15 | Hard | 28,101 | 2,014 |
maximum difference between increasing elements | class Solution:
def maximumDifference(self, nums: List[int]) -> int:
ans = -1
prefix = inf
for i, x in enumerate(nums):
if i and x > prefix: ans = max(ans, x - prefix)
prefix = min(prefix, x)
return ans | https://leetcode.com/problems/maximum-difference-between-increasing-elements/discuss/1486318/Python3-prefix-min | 6 | Given a 0-indexed integer array nums of size n, find the maximum difference between nums[i] and nums[j] (i.e., nums[j] - nums[i]), such that 0 <= i < j < n and nums[i] < nums[j].
Return the maximum difference. If no such i and j exists, return -1.
Example 1:
Input: nums = [7,1,5,4]
Output: 4
Explanation:
The maximum difference occurs with i = 1 and j = 2, nums[j] - nums[i] = 5 - 1 = 4.
Note that with i = 1 and j = 0, the difference nums[j] - nums[i] = 7 - 1 = 6, but i > j, so it is not valid.
Example 2:
Input: nums = [9,4,3,2]
Output: -1
Explanation:
There is no i and j such that i < j and nums[i] < nums[j].
Example 3:
Input: nums = [1,5,2,10]
Output: 9
Explanation:
The maximum difference occurs with i = 0 and j = 3, nums[j] - nums[i] = 10 - 1 = 9.
Constraints:
n == nums.length
2 <= n <= 1000
1 <= nums[i] <= 109 | [Python3] prefix min | 557 | maximum-difference-between-increasing-elements | 0.535 | ye15 | Easy | 28,104 | 2,016 |
grid game | class Solution(object):
def gridGame(self, grid):
top, bottom = grid
top_sum = sum(top)
bottom_sum = 0
res = float('inf')
for i in range(len(top)):
top_sum -= top[i]
res = min(res, max(top_sum, bottom_sum))
bottom_sum += bottom[i]
return res | https://leetcode.com/problems/grid-game/discuss/1486349/Python-Easy | 3 | You are given a 0-indexed 2D array grid of size 2 x n, where grid[r][c] represents the number of points at position (r, c) on the matrix. Two robots are playing a game on this matrix.
Both robots initially start at (0, 0) and want to reach (1, n-1). Each robot may only move to the right ((r, c) to (r, c + 1)) or down ((r, c) to (r + 1, c)).
At the start of the game, the first robot moves from (0, 0) to (1, n-1), collecting all the points from the cells on its path. For all cells (r, c) traversed on the path, grid[r][c] is set to 0. Then, the second robot moves from (0, 0) to (1, n-1), collecting the points on its path. Note that their paths may intersect with one another.
The first robot wants to minimize the number of points collected by the second robot. In contrast, the second robot wants to maximize the number of points it collects. If both robots play optimally, return the number of points collected by the second robot.
Example 1:
Input: grid = [[2,5,4],[1,5,1]]
Output: 4
Explanation: The optimal path taken by the first robot is shown in red, and the optimal path taken by the second robot is shown in blue.
The cells visited by the first robot are set to 0.
The second robot will collect 0 + 0 + 4 + 0 = 4 points.
Example 2:
Input: grid = [[3,3,1],[8,5,2]]
Output: 4
Explanation: The optimal path taken by the first robot is shown in red, and the optimal path taken by the second robot is shown in blue.
The cells visited by the first robot are set to 0.
The second robot will collect 0 + 3 + 1 + 0 = 4 points.
Example 3:
Input: grid = [[1,3,1,15],[1,3,3,1]]
Output: 7
Explanation: The optimal path taken by the first robot is shown in red, and the optimal path taken by the second robot is shown in blue.
The cells visited by the first robot are set to 0.
The second robot will collect 0 + 1 + 3 + 3 + 0 = 7 points.
Constraints:
grid.length == 2
n == grid[r].length
1 <= n <= 5 * 104
1 <= grid[r][c] <= 105 | Python - Easy | 181 | grid-game | 0.43 | lokeshsenthilkumar | Medium | 28,129 | 2,017 |
check if word can be placed in crossword | class Solution:
def placeWordInCrossword(self, board: List[List[str]], word: str) -> bool:
for x in board, zip(*board):
for row in x:
for s in "".join(row).split("#"):
for w in word, word[::-1]:
if len(s) == len(w) and all(ss in (" ", ww) for ss, ww in zip(s, w)): return True
return False | https://leetcode.com/problems/check-if-word-can-be-placed-in-crossword/discuss/1486326/Python3-row-by-row-and-col-by-col | 10 | You are given an m x n matrix board, representing the current state of a crossword puzzle. The crossword contains lowercase English letters (from solved words), ' ' to represent any empty cells, and '#' to represent any blocked cells.
A word can be placed horizontally (left to right or right to left) or vertically (top to bottom or bottom to top) in the board if:
It does not occupy a cell containing the character '#'.
The cell each letter is placed in must either be ' ' (empty) or match the letter already on the board.
There must not be any empty cells ' ' or other lowercase letters directly left or right of the word if the word was placed horizontally.
There must not be any empty cells ' ' or other lowercase letters directly above or below the word if the word was placed vertically.
Given a string word, return true if word can be placed in board, or false otherwise.
Example 1:
Input: board = [["#", " ", "#"], [" ", " ", "#"], ["#", "c", " "]], word = "abc"
Output: true
Explanation: The word "abc" can be placed as shown above (top to bottom).
Example 2:
Input: board = [[" ", "#", "a"], [" ", "#", "c"], [" ", "#", "a"]], word = "ac"
Output: false
Explanation: It is impossible to place the word because there will always be a space/letter above or below it.
Example 3:
Input: board = [["#", " ", "#"], [" ", " ", "#"], ["#", " ", "c"]], word = "ca"
Output: true
Explanation: The word "ca" can be placed as shown above (right to left).
Constraints:
m == board.length
n == board[i].length
1 <= m * n <= 2 * 105
board[i][j] will be ' ', '#', or a lowercase English letter.
1 <= word.length <= max(m, n)
word will contain only lowercase English letters. | [Python3] row-by-row & col-by-col | 1,300 | check-if-word-can-be-placed-in-crossword | 0.494 | ye15 | Medium | 28,137 | 2,018 |
the score of students solving math expression | class Solution:
def scoreOfStudents(self, s: str, answers: List[int]) -> int:
@cache
def fn(lo, hi):
"""Return possible answers of s[lo:hi]."""
if lo+1 == hi: return {int(s[lo])}
ans = set()
for mid in range(lo+1, hi, 2):
for x in fn(lo, mid):
for y in fn(mid+1, hi):
if s[mid] == "+" and x + y <= 1000: ans.add(x + y)
elif s[mid] == "*" and x * y <= 1000: ans.add(x * y)
return ans
target = eval(s)
cand = fn(0, len(s))
ans = 0
for x in answers:
if x == target: ans += 5
elif x in cand: ans += 2
return ans | https://leetcode.com/problems/the-score-of-students-solving-math-expression/discuss/1487285/Python3-somewhat-dp | 6 | You are given a string s that contains digits 0-9, addition symbols '+', and multiplication symbols '*' only, representing a valid math expression of single digit numbers (e.g., 3+5*2). This expression was given to n elementary school students. The students were instructed to get the answer of the expression by following this order of operations:
Compute multiplication, reading from left to right; Then,
Compute addition, reading from left to right.
You are given an integer array answers of length n, which are the submitted answers of the students in no particular order. You are asked to grade the answers, by following these rules:
If an answer equals the correct answer of the expression, this student will be rewarded 5 points;
Otherwise, if the answer could be interpreted as if the student applied the operators in the wrong order but had correct arithmetic, this student will be rewarded 2 points;
Otherwise, this student will be rewarded 0 points.
Return the sum of the points of the students.
Example 1:
Input: s = "7+3*1*2", answers = [20,13,42]
Output: 7
Explanation: As illustrated above, the correct answer of the expression is 13, therefore one student is rewarded 5 points: [20,13,42]
A student might have applied the operators in this wrong order: ((7+3)*1)*2 = 20. Therefore one student is rewarded 2 points: [20,13,42]
The points for the students are: [2,5,0]. The sum of the points is 2+5+0=7.
Example 2:
Input: s = "3+5*2", answers = [13,0,10,13,13,16,16]
Output: 19
Explanation: The correct answer of the expression is 13, therefore three students are rewarded 5 points each: [13,0,10,13,13,16,16]
A student might have applied the operators in this wrong order: ((3+5)*2 = 16. Therefore two students are rewarded 2 points: [13,0,10,13,13,16,16]
The points for the students are: [5,0,0,5,5,2,2]. The sum of the points is 5+0+0+5+5+2+2=19.
Example 3:
Input: s = "6+0*1", answers = [12,9,6,4,8,6]
Output: 10
Explanation: The correct answer of the expression is 6.
If a student had incorrectly done (6+0)*1, the answer would also be 6.
By the rules of grading, the students will still be rewarded 5 points (as they got the correct answer), not 2 points.
The points for the students are: [0,0,5,0,0,5]. The sum of the points is 10.
Constraints:
3 <= s.length <= 31
s represents a valid expression that contains only digits 0-9, '+', and '*' only.
All the integer operands in the expression are in the inclusive range [0, 9].
1 <= The count of all operators ('+' and '*') in the math expression <= 15
Test data are generated such that the correct answer of the expression is in the range of [0, 1000].
n == answers.length
1 <= n <= 104
0 <= answers[i] <= 1000 | [Python3] somewhat dp | 267 | the-score-of-students-solving-math-expression | 0.338 | ye15 | Hard | 28,146 | 2,019 |
convert 1d array into 2d array | class Solution:
def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:
ans = []
if len(original) == m*n:
for i in range(0, len(original), n):
ans.append(original[i:i+n])
return ans | https://leetcode.com/problems/convert-1d-array-into-2d-array/discuss/1499000/Python3-simulation | 36 | You are given a 0-indexed 1-dimensional (1D) integer array original, and two integers, m and n. You are tasked with creating a 2-dimensional (2D) array with m rows and n columns using all the elements from original.
The elements from indices 0 to n - 1 (inclusive) of original should form the first row of the constructed 2D array, the elements from indices n to 2 * n - 1 (inclusive) should form the second row of the constructed 2D array, and so on.
Return an m x n 2D array constructed according to the above procedure, or an empty 2D array if it is impossible.
Example 1:
Input: original = [1,2,3,4], m = 2, n = 2
Output: [[1,2],[3,4]]
Explanation: The constructed 2D array should contain 2 rows and 2 columns.
The first group of n=2 elements in original, [1,2], becomes the first row in the constructed 2D array.
The second group of n=2 elements in original, [3,4], becomes the second row in the constructed 2D array.
Example 2:
Input: original = [1,2,3], m = 1, n = 3
Output: [[1,2,3]]
Explanation: The constructed 2D array should contain 1 row and 3 columns.
Put all three elements in original into the first row of the constructed 2D array.
Example 3:
Input: original = [1,2], m = 1, n = 1
Output: []
Explanation: There are 2 elements in original.
It is impossible to fit 2 elements in a 1x1 2D array, so return an empty 2D array.
Constraints:
1 <= original.length <= 5 * 104
1 <= original[i] <= 105
1 <= m, n <= 4 * 104 | [Python3] simulation | 2,800 | convert-1d-array-into-2d-array | 0.584 | ye15 | Easy | 28,148 | 2,022 |
number of pairs of strings with concatenation equal to target | class Solution:
def numOfPairs(self, nums: List[str], target: str) -> int:
freq = Counter(nums)
ans = 0
for k, v in freq.items():
if target.startswith(k):
suffix = target[len(k):]
ans += v * freq[suffix]
if k == suffix: ans -= freq[suffix]
return ans | https://leetcode.com/problems/number-of-pairs-of-strings-with-concatenation-equal-to-target/discuss/1499007/Python3-freq-table | 36 | Given an array of digit strings nums and a digit string target, return the number of pairs of indices (i, j) (where i != j) such that the concatenation of nums[i] + nums[j] equals target.
Example 1:
Input: nums = ["777","7","77","77"], target = "7777"
Output: 4
Explanation: Valid pairs are:
- (0, 1): "777" + "7"
- (1, 0): "7" + "777"
- (2, 3): "77" + "77"
- (3, 2): "77" + "77"
Example 2:
Input: nums = ["123","4","12","34"], target = "1234"
Output: 2
Explanation: Valid pairs are:
- (0, 1): "123" + "4"
- (2, 3): "12" + "34"
Example 3:
Input: nums = ["1","1","1"], target = "11"
Output: 6
Explanation: Valid pairs are:
- (0, 1): "1" + "1"
- (1, 0): "1" + "1"
- (0, 2): "1" + "1"
- (2, 0): "1" + "1"
- (1, 2): "1" + "1"
- (2, 1): "1" + "1"
Constraints:
2 <= nums.length <= 100
1 <= nums[i].length <= 100
2 <= target.length <= 100
nums[i] and target consist of digits.
nums[i] and target do not have leading zeros. | [Python3] freq table | 2,600 | number-of-pairs-of-strings-with-concatenation-equal-to-target | 0.729 | ye15 | Medium | 28,182 | 2,023 |
maximize the confusion of an exam | class Solution:
def maxConsecutiveAnswers(self, string: str, k: int) -> int:
result = 0
j = 0
count1 = k
for i in range(len(string)):
if count1 == 0 and string[i] == "F":
while string[j] != "F":
j+=1
count1+=1
j+=1
if string[i] == "F":
if count1 > 0:
count1-=1
if i - j + 1 > result:
result = i - j + 1
j = 0
count2 = k
for i in range(len(string)):
if count2 == 0 and string[i] == "T":
while string[j] != "T":
j+=1
count2+=1
j+=1
if string[i] == "T":
if count2 > 0:
count2-=1
if i - j + 1 > result:
result = i - j + 1
return result | https://leetcode.com/problems/maximize-the-confusion-of-an-exam/discuss/1951750/WEEB-DOES-PYTHONC%2B%2B-SLIDING-WINDOW | 2 | A teacher is writing a test with n true/false questions, with 'T' denoting true and 'F' denoting false. He wants to confuse the students by maximizing the number of consecutive questions with the same answer (multiple trues or multiple falses in a row).
You are given a string answerKey, where answerKey[i] is the original answer to the ith question. In addition, you are given an integer k, the maximum number of times you may perform the following operation:
Change the answer key for any question to 'T' or 'F' (i.e., set answerKey[i] to 'T' or 'F').
Return the maximum number of consecutive 'T's or 'F's in the answer key after performing the operation at most k times.
Example 1:
Input: answerKey = "TTFF", k = 2
Output: 4
Explanation: We can replace both the 'F's with 'T's to make answerKey = "TTTT".
There are four consecutive 'T's.
Example 2:
Input: answerKey = "TFFT", k = 1
Output: 3
Explanation: We can replace the first 'T' with an 'F' to make answerKey = "FFFT".
Alternatively, we can replace the second 'T' with an 'F' to make answerKey = "TFFF".
In both cases, there are three consecutive 'F's.
Example 3:
Input: answerKey = "TTFTTFTT", k = 1
Output: 5
Explanation: We can replace the first 'F' to make answerKey = "TTTTTFTT"
Alternatively, we can replace the second 'F' to make answerKey = "TTFTTTTT".
In both cases, there are five consecutive 'T's.
Constraints:
n == answerKey.length
1 <= n <= 5 * 104
answerKey[i] is either 'T' or 'F'
1 <= k <= n | WEEB DOES PYTHON/C++ SLIDING WINDOW | 95 | maximize-the-confusion-of-an-exam | 0.598 | Skywalker5423 | Medium | 28,206 | 2,024 |
maximum number of ways to partition an array | class Solution:
def waysToPartition(self, nums: List[int], k: int) -> int:
prefix = [0]
loc = defaultdict(list)
for i, x in enumerate(nums):
prefix.append(prefix[-1] + x)
if i < len(nums)-1: loc[prefix[-1]].append(i)
ans = 0
if prefix[-1] % 2 == 0: ans = len(loc[prefix[-1]//2]) # unchanged
total = prefix[-1]
for i, x in enumerate(nums):
cnt = 0
diff = k - x
target = total + diff
if target % 2 == 0:
target //= 2
cnt += bisect_left(loc[target], i)
cnt += len(loc[target-diff]) - bisect_left(loc[target-diff], i)
ans = max(ans, cnt)
return ans | https://leetcode.com/problems/maximum-number-of-ways-to-partition-an-array/discuss/1499024/Python3-binary-search | 2 | You are given a 0-indexed integer array nums of length n. The number of ways to partition nums is the number of pivot indices that satisfy both conditions:
1 <= pivot < n
nums[0] + nums[1] + ... + nums[pivot - 1] == nums[pivot] + nums[pivot + 1] + ... + nums[n - 1]
You are also given an integer k. You can choose to change the value of one element of nums to k, or to leave the array unchanged.
Return the maximum possible number of ways to partition nums to satisfy both conditions after changing at most one element.
Example 1:
Input: nums = [2,-1,2], k = 3
Output: 1
Explanation: One optimal approach is to change nums[0] to k. The array becomes [3,-1,2].
There is one way to partition the array:
- For pivot = 2, we have the partition [3,-1 | 2]: 3 + -1 == 2.
Example 2:
Input: nums = [0,0,0], k = 1
Output: 2
Explanation: The optimal approach is to leave the array unchanged.
There are two ways to partition the array:
- For pivot = 1, we have the partition [0 | 0,0]: 0 == 0 + 0.
- For pivot = 2, we have the partition [0,0 | 0]: 0 + 0 == 0.
Example 3:
Input: nums = [22,4,-25,-20,-15,15,-16,7,19,-10,0,-13,-14], k = -33
Output: 4
Explanation: One optimal approach is to change nums[2] to k. The array becomes [22,4,-33,-20,-15,15,-16,7,19,-10,0,-13,-14].
There are four ways to partition the array.
Constraints:
n == nums.length
2 <= n <= 105
-105 <= k, nums[i] <= 105 | [Python3] binary search | 227 | maximum-number-of-ways-to-partition-an-array | 0.321 | ye15 | Hard | 28,221 | 2,025 |
minimum moves to convert string | class Solution:
def minimumMoves(self, s: str) -> int:
ans = i = 0
while i < len(s):
if s[i] == "X":
ans += 1
i += 3
else: i += 1
return ans | https://leetcode.com/problems/minimum-moves-to-convert-string/discuss/1500215/Python3-scan | 28 | You are given a string s consisting of n characters which are either 'X' or 'O'.
A move is defined as selecting three consecutive characters of s and converting them to 'O'. Note that if a move is applied to the character 'O', it will stay the same.
Return the minimum number of moves required so that all the characters of s are converted to 'O'.
Example 1:
Input: s = "XXX"
Output: 1
Explanation: XXX -> OOO
We select all the 3 characters and convert them in one move.
Example 2:
Input: s = "XXOX"
Output: 2
Explanation: XXOX -> OOOX -> OOOO
We select the first 3 characters in the first move, and convert them to 'O'.
Then we select the last 3 characters and convert them so that the final string contains all 'O's.
Example 3:
Input: s = "OOOO"
Output: 0
Explanation: There are no 'X's in s to convert.
Constraints:
3 <= s.length <= 1000
s[i] is either 'X' or 'O'. | [Python3] scan | 1,200 | minimum-moves-to-convert-string | 0.537 | ye15 | Easy | 28,223 | 2,027 |
find missing observations | class Solution:
def missingRolls(self, rolls: List[int], mean: int, n: int) -> List[int]:
missing_val, rem = divmod(mean * (len(rolls) + n) - sum(rolls), n)
if rem == 0:
if 1 <= missing_val <= 6:
return [missing_val] * n
elif 1 <= missing_val < 6:
return [missing_val + 1] * rem + [missing_val] * (n - rem)
return [] | https://leetcode.com/problems/find-missing-observations/discuss/1506196/Divmod-and-list-comprehension-96-speed | 2 | You have observations of n + m 6-sided dice rolls with each face numbered from 1 to 6. n of the observations went missing, and you only have the observations of m rolls. Fortunately, you have also calculated the average value of the n + m rolls.
You are given an integer array rolls of length m where rolls[i] is the value of the ith observation. You are also given the two integers mean and n.
Return an array of length n containing the missing observations such that the average value of the n + m rolls is exactly mean. If there are multiple valid answers, return any of them. If no such array exists, return an empty array.
The average value of a set of k numbers is the sum of the numbers divided by k.
Note that mean is an integer, so the sum of the n + m rolls should be divisible by n + m.
Example 1:
Input: rolls = [3,2,4,3], mean = 4, n = 2
Output: [6,6]
Explanation: The mean of all n + m rolls is (3 + 2 + 4 + 3 + 6 + 6) / 6 = 4.
Example 2:
Input: rolls = [1,5,6], mean = 3, n = 4
Output: [2,3,2,2]
Explanation: The mean of all n + m rolls is (1 + 5 + 6 + 2 + 3 + 2 + 2) / 7 = 3.
Example 3:
Input: rolls = [1,2,3,4], mean = 6, n = 4
Output: []
Explanation: It is impossible for the mean to be 6 no matter what the 4 missing rolls are.
Constraints:
m == rolls.length
1 <= n, m <= 105
1 <= rolls[i], mean <= 6 | Divmod and list comprehension, 96% speed | 133 | find-missing-observations | 0.439 | EvgenySH | Medium | 28,241 | 2,028 |
stone game ix | class Solution:
def stoneGameIX(self, stones: List[int]) -> bool:
freq = defaultdict(int)
for x in stones: freq[x % 3] += 1
if freq[0]%2 == 0: return freq[1] and freq[2]
return abs(freq[1] - freq[2]) >= 3 | https://leetcode.com/problems/stone-game-ix/discuss/1500343/Python3-freq-table | 3 | Alice and Bob continue their games with stones. There is a row of n stones, and each stone has an associated value. You are given an integer array stones, where stones[i] is the value of the ith stone.
Alice and Bob take turns, with Alice starting first. On each turn, the player may remove any stone from stones. The player who removes a stone loses if the sum of the values of all removed stones is divisible by 3. Bob will win automatically if there are no remaining stones (even if it is Alice's turn).
Assuming both players play optimally, return true if Alice wins and false if Bob wins.
Example 1:
Input: stones = [2,1]
Output: true
Explanation: The game will be played as follows:
- Turn 1: Alice can remove either stone.
- Turn 2: Bob removes the remaining stone.
The sum of the removed stones is 1 + 2 = 3 and is divisible by 3. Therefore, Bob loses and Alice wins the game.
Example 2:
Input: stones = [2]
Output: false
Explanation: Alice will remove the only stone, and the sum of the values on the removed stones is 2.
Since all the stones are removed and the sum of values is not divisible by 3, Bob wins the game.
Example 3:
Input: stones = [5,1,2,4,3]
Output: false
Explanation: Bob will always win. One possible way for Bob to win is shown below:
- Turn 1: Alice can remove the second stone with value 1. Sum of removed stones = 1.
- Turn 2: Bob removes the fifth stone with value 3. Sum of removed stones = 1 + 3 = 4.
- Turn 3: Alices removes the fourth stone with value 4. Sum of removed stones = 1 + 3 + 4 = 8.
- Turn 4: Bob removes the third stone with value 2. Sum of removed stones = 1 + 3 + 4 + 2 = 10.
- Turn 5: Alice removes the first stone with value 5. Sum of removed stones = 1 + 3 + 4 + 2 + 5 = 15.
Alice loses the game because the sum of the removed stones (15) is divisible by 3. Bob wins the game.
Constraints:
1 <= stones.length <= 105
1 <= stones[i] <= 104 | [Python3] freq table | 165 | stone-game-ix | 0.264 | ye15 | Medium | 28,250 | 2,029 |
smallest k length subsequence with occurrences of a letter | class Solution:
def smallestSubsequence(self, s: str, k: int, letter: str, repetition: int) -> str:
counts,total = 0, 0
n = len(s)
for ch in s:
if ch==letter:
total +=1
stack = []
occ = 0
for idx,ch in enumerate(s):
if ch==letter:
counts +=1
while stack and stack[-1]>ch and len(stack)+ (n-1-idx)>=k and (occ+total-counts-(stack[-1]==letter)+(ch==letter)>=repetition ):
occ -= stack.pop()==letter
if ch!=letter and len(stack)< k-max(0,(repetition-occ)):
stack.append(ch)
elif ch==letter and len(stack)+(total-counts)<k:
stack.append(ch)
occ +=1
return ''.join(stack) | https://leetcode.com/problems/smallest-k-length-subsequence-with-occurrences-of-a-letter/discuss/1502134/PYTHON3-O(n)-using-stack-with-explanation | 2 | You are given a string s, an integer k, a letter letter, and an integer repetition.
Return the lexicographically smallest subsequence of s of length k that has the letter letter appear at least repetition times. The test cases are generated so that the letter appears in s at least repetition times.
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.
A string a is lexicographically smaller than a string b if in the first position where a and b differ, string a has a letter that appears earlier in the alphabet than the corresponding letter in b.
Example 1:
Input: s = "leet", k = 3, letter = "e", repetition = 1
Output: "eet"
Explanation: There are four subsequences of length 3 that have the letter 'e' appear at least 1 time:
- "lee" (from "leet")
- "let" (from "leet")
- "let" (from "leet")
- "eet" (from "leet")
The lexicographically smallest subsequence among them is "eet".
Example 2:
Input: s = "leetcode", k = 4, letter = "e", repetition = 2
Output: "ecde"
Explanation: "ecde" is the lexicographically smallest subsequence of length 4 that has the letter "e" appear at least 2 times.
Example 3:
Input: s = "bb", k = 2, letter = "b", repetition = 2
Output: "bb"
Explanation: "bb" is the only subsequence of length 2 that has the letter "b" appear at least 2 times.
Constraints:
1 <= repetition <= k <= s.length <= 5 * 104
s consists of lowercase English letters.
letter is a lowercase English letter, and appears in s at least repetition times. | [PYTHON3] O(n) using stack with explanation | 300 | smallest-k-length-subsequence-with-occurrences-of-a-letter | 0.387 | irt | Hard | 28,252 | 2,030 |
two out of three | class Solution:
def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int]:
s1, s2, s3 = set(nums1), set(nums2), set(nums3)
return (s1&s2) | (s2&s3) | (s1&s3) | https://leetcode.com/problems/two-out-of-three/discuss/1513311/Python3-set | 20 | Given three integer arrays nums1, nums2, and nums3, return a distinct array containing all the values that are present in at least two out of the three arrays. You may return the values in any order.
Example 1:
Input: nums1 = [1,1,3,2], nums2 = [2,3], nums3 = [3]
Output: [3,2]
Explanation: The values that are present in at least two arrays are:
- 3, in all three arrays.
- 2, in nums1 and nums2.
Example 2:
Input: nums1 = [3,1], nums2 = [2,3], nums3 = [1,2]
Output: [2,3,1]
Explanation: The values that are present in at least two arrays are:
- 2, in nums2 and nums3.
- 3, in nums1 and nums2.
- 1, in nums1 and nums3.
Example 3:
Input: nums1 = [1,2,2], nums2 = [4,3,3], nums3 = [5]
Output: []
Explanation: No value is present in at least two arrays.
Constraints:
1 <= nums1.length, nums2.length, nums3.length <= 100
1 <= nums1[i], nums2[j], nums3[k] <= 100 | [Python3] set | 1,400 | two-out-of-three | 0.726 | ye15 | Easy | 28,255 | 2,032 |
minimum operations to make a uni value grid | class Solution:
def minOperations(self, grid: List[List[int]], x: int) -> int:
vals = [x for row in grid for x in row]
if len(set(val%x for val in vals)) > 1: return -1 # impossible
median = sorted(vals)[len(vals)//2] # O(N) possible via "quick select"
return sum(abs(val - median)//x for val in vals) | https://leetcode.com/problems/minimum-operations-to-make-a-uni-value-grid/discuss/1513319/Python3-median-4-line | 21 | You are given a 2D integer grid of size m x n and an integer x. In one operation, you can add x to or subtract x from any element in the grid.
A uni-value grid is a grid where all the elements of it are equal.
Return the minimum number of operations to make the grid uni-value. If it is not possible, return -1.
Example 1:
Input: grid = [[2,4],[6,8]], x = 2
Output: 4
Explanation: We can make every element equal to 4 by doing the following:
- Add x to 2 once.
- Subtract x from 6 once.
- Subtract x from 8 twice.
A total of 4 operations were used.
Example 2:
Input: grid = [[1,5],[2,3]], x = 1
Output: 5
Explanation: We can make every element equal to 3.
Example 3:
Input: grid = [[1,2],[3,4]], x = 2
Output: -1
Explanation: It is impossible to make every element equal.
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 105
1 <= m * n <= 105
1 <= x, grid[i][j] <= 104 | [Python3] median 4-line | 1,100 | minimum-operations-to-make-a-uni-value-grid | 0.524 | ye15 | Medium | 28,297 | 2,033 |
partition array into two arrays to minimize sum difference | class Solution:
def minimumDifference(self, nums: List[int]) -> int:
N = len(nums) // 2 # Note this is N/2, ie no. of elements required in each.
def get_sums(nums): # generate all combinations sum of k elements
ans = {}
N = len(nums)
for k in range(1, N+1): # takes k element for nums
sums = []
for comb in combinations(nums, k):
s = sum(comb)
sums.append(s)
ans[k] = sums
return ans
left_part, right_part = nums[:N], nums[N:]
left_sums, right_sums = get_sums(left_part), get_sums(right_part)
ans = abs(sum(left_part) - sum(right_part)) # the case when taking all N from left_part for left_ans, and vice versa
total = sum(nums)
half = total // 2 # the best sum required for each, we have to find sum nearest to this
for k in range(1, N):
left = left_sums[k] # if taking k no. from left_sums
right = right_sums[N-k] # then we have to take remaining N-k from right_sums.
right.sort() # sorting, so that we can binary search the required value
for x in left:
r = half - x # required, how much we need to add in x to bring it closer to half.
p = bisect.bisect_left(right, r) # we are finding index of value closest to r, present in right, using binary search
for q in [p, p-1]:
if 0 <= q < len(right):
left_ans_sum = x + right[q]
right_ans_sum = total - left_ans_sum
diff = abs(left_ans_sum - right_ans_sum)
ans = min(ans, diff)
return ans | https://leetcode.com/problems/partition-array-into-two-arrays-to-minimize-sum-difference/discuss/1513435/Python-or-Easy-Explanation-or-Meet-in-the-Middle | 117 | You are given an integer array nums of 2 * n integers. You need to partition nums into two arrays of length n to minimize the absolute difference of the sums of the arrays. To partition nums, put each element of nums into one of the two arrays.
Return the minimum possible absolute difference.
Example 1:
Input: nums = [3,9,7,3]
Output: 2
Explanation: One optimal partition is: [3,9] and [7,3].
The absolute difference between the sums of the arrays is abs((3 + 9) - (7 + 3)) = 2.
Example 2:
Input: nums = [-36,36]
Output: 72
Explanation: One optimal partition is: [-36] and [36].
The absolute difference between the sums of the arrays is abs((-36) - (36)) = 72.
Example 3:
Input: nums = [2,-1,0,4,-2,-9]
Output: 0
Explanation: One optimal partition is: [2,4,-9] and [-1,0,-2].
The absolute difference between the sums of the arrays is abs((2 + 4 + -9) - (-1 + 0 + -2)) = 0.
Constraints:
1 <= n <= 15
nums.length == 2 * n
-107 <= nums[i] <= 107 | Python | Easy Explanation | Meet in the Middle | 8,800 | partition-array-into-two-arrays-to-minimize-sum-difference | 0.183 | malraharsh | Hard | 28,307 | 2,035 |
minimum number of moves to seat everyone | class Solution:
def minMovesToSeat(self, seats: List[int], students: List[int]) -> int:
seats.sort()
students.sort()
return sum(abs(seat - student) for seat, student in zip(seats, students)) | https://leetcode.com/problems/minimum-number-of-moves-to-seat-everyone/discuss/1539518/O(n)-counting-sort-in-Python | 7 | There are n seats and n students in a room. You are given an array seats of length n, where seats[i] is the position of the ith seat. You are also given the array students of length n, where students[j] is the position of the jth student.
You may perform the following move any number of times:
Increase or decrease the position of the ith student by 1 (i.e., moving the ith student from position x to x + 1 or x - 1)
Return the minimum number of moves required to move each student to a seat such that no two students are in the same seat.
Note that there may be multiple seats or students in the same position at the beginning.
Example 1:
Input: seats = [3,1,5], students = [2,7,4]
Output: 4
Explanation: The students are moved as follows:
- The first student is moved from from position 2 to position 1 using 1 move.
- The second student is moved from from position 7 to position 5 using 2 moves.
- The third student is moved from from position 4 to position 3 using 1 move.
In total, 1 + 2 + 1 = 4 moves were used.
Example 2:
Input: seats = [4,1,5,9], students = [1,3,2,6]
Output: 7
Explanation: The students are moved as follows:
- The first student is not moved.
- The second student is moved from from position 3 to position 4 using 1 move.
- The third student is moved from from position 2 to position 5 using 3 moves.
- The fourth student is moved from from position 6 to position 9 using 3 moves.
In total, 0 + 1 + 3 + 3 = 7 moves were used.
Example 3:
Input: seats = [2,2,6,6], students = [1,3,2,6]
Output: 4
Explanation: Note that there are two seats at position 2 and two seats at position 6.
The students are moved as follows:
- The first student is moved from from position 1 to position 2 using 1 move.
- The second student is moved from from position 3 to position 6 using 3 moves.
- The third student is not moved.
- The fourth student is not moved.
In total, 1 + 3 + 0 + 0 = 4 moves were used.
Constraints:
n == seats.length == students.length
1 <= n <= 100
1 <= seats[i], students[j] <= 100 | O(n) counting sort in Python | 841 | minimum-number-of-moves-to-seat-everyone | 0.821 | mousun224 | Easy | 28,310 | 2,037 |
remove colored pieces if both neighbors are the same color | class Solution:
def winnerOfGame(self, s: str) -> bool:
a = b = 0
for i in range(1,len(s)-1):
if s[i-1] == s[i] == s[i+1]:
if s[i] == 'A':
a += 1
else:
b += 1
return a>b | https://leetcode.com/problems/remove-colored-pieces-if-both-neighbors-are-the-same-color/discuss/1524153/C%2B%2BPythonJava-Count-%22AAA%22-and-%22BBB%22 | 75 | There are n pieces arranged in a line, and each piece is colored either by 'A' or by 'B'. You are given a string colors of length n where colors[i] is the color of the ith piece.
Alice and Bob are playing a game where they take alternating turns removing pieces from the line. In this game, Alice moves first.
Alice is only allowed to remove a piece colored 'A' if both its neighbors are also colored 'A'. She is not allowed to remove pieces that are colored 'B'.
Bob is only allowed to remove a piece colored 'B' if both its neighbors are also colored 'B'. He is not allowed to remove pieces that are colored 'A'.
Alice and Bob cannot remove pieces from the edge of the line.
If a player cannot make a move on their turn, that player loses and the other player wins.
Assuming Alice and Bob play optimally, return true if Alice wins, or return false if Bob wins.
Example 1:
Input: colors = "AAABABB"
Output: true
Explanation:
AAABABB -> AABABB
Alice moves first.
She removes the second 'A' from the left since that is the only 'A' whose neighbors are both 'A'.
Now it's Bob's turn.
Bob cannot make a move on his turn since there are no 'B's whose neighbors are both 'B'.
Thus, Alice wins, so return true.
Example 2:
Input: colors = "AA"
Output: false
Explanation:
Alice has her turn first.
There are only two 'A's and both are on the edge of the line, so she cannot move on her turn.
Thus, Bob wins, so return false.
Example 3:
Input: colors = "ABBBBBBBAAA"
Output: false
Explanation:
ABBBBBBBAAA -> ABBBBBBBAA
Alice moves first.
Her only option is to remove the second to last 'A' from the right.
ABBBBBBBAA -> ABBBBBBAA
Next is Bob's turn.
He has many options for which 'B' piece to remove. He can pick any.
On Alice's second turn, she has no more pieces that she can remove.
Thus, Bob wins, so return false.
Constraints:
1 <= colors.length <= 105
colors consists of only the letters 'A' and 'B' | [C++/Python/Java] Count "AAA" and "BBB" | 5,000 | remove-colored-pieces-if-both-neighbors-are-the-same-color | 0.582 | lokeshsenthilkumar | Medium | 28,351 | 2,038 |
the time when the network becomes idle | class Solution:
def networkBecomesIdle(self, edges: List[List[int]], patience: List[int]) -> int:
graph = {}
for u, v in edges:
graph.setdefault(u, []).append(v)
graph.setdefault(v, []).append(u)
dist = [-1]*len(graph)
dist[0] = 0
val = 0
queue = [0]
while queue:
val += 2
newq = []
for u in queue:
for v in graph[u]:
if dist[v] == -1:
dist[v] = val
newq.append(v)
queue = newq
ans = 0
for d, p in zip(dist, patience):
if p:
k = d//p - int(d%p == 0)
ans = max(ans, d + k*p)
return ans + 1 | https://leetcode.com/problems/the-time-when-the-network-becomes-idle/discuss/1524183/Python3-graph | 5 | There is a network of n servers, labeled from 0 to n - 1. You are given a 2D integer array edges, where edges[i] = [ui, vi] indicates there is a message channel between servers ui and vi, and they can pass any number of messages to each other directly in one second. You are also given a 0-indexed integer array patience of length n.
All servers are connected, i.e., a message can be passed from one server to any other server(s) directly or indirectly through the message channels.
The server labeled 0 is the master server. The rest are data servers. Each data server needs to send its message to the master server for processing and wait for a reply. Messages move between servers optimally, so every message takes the least amount of time to arrive at the master server. The master server will process all newly arrived messages instantly and send a reply to the originating server via the reversed path the message had gone through.
At the beginning of second 0, each data server sends its message to be processed. Starting from second 1, at the beginning of every second, each data server will check if it has received a reply to the message it sent (including any newly arrived replies) from the master server:
If it has not, it will resend the message periodically. The data server i will resend the message every patience[i] second(s), i.e., the data server i will resend the message if patience[i] second(s) have elapsed since the last time the message was sent from this server.
Otherwise, no more resending will occur from this server.
The network becomes idle when there are no messages passing between servers or arriving at servers.
Return the earliest second starting from which the network becomes idle.
Example 1:
Input: edges = [[0,1],[1,2]], patience = [0,2,1]
Output: 8
Explanation:
At (the beginning of) second 0,
- Data server 1 sends its message (denoted 1A) to the master server.
- Data server 2 sends its message (denoted 2A) to the master server.
At second 1,
- Message 1A arrives at the master server. Master server processes message 1A instantly and sends a reply 1A back.
- Server 1 has not received any reply. 1 second (1 < patience[1] = 2) elapsed since this server has sent the message, therefore it does not resend the message.
- Server 2 has not received any reply. 1 second (1 == patience[2] = 1) elapsed since this server has sent the message, therefore it resends the message (denoted 2B).
At second 2,
- The reply 1A arrives at server 1. No more resending will occur from server 1.
- Message 2A arrives at the master server. Master server processes message 2A instantly and sends a reply 2A back.
- Server 2 resends the message (denoted 2C).
...
At second 4,
- The reply 2A arrives at server 2. No more resending will occur from server 2.
...
At second 7, reply 2D arrives at server 2.
Starting from the beginning of the second 8, there are no messages passing between servers or arriving at servers.
This is the time when the network becomes idle.
Example 2:
Input: edges = [[0,1],[0,2],[1,2]], patience = [0,10,10]
Output: 3
Explanation: Data servers 1 and 2 receive a reply back at the beginning of second 2.
From the beginning of the second 3, the network becomes idle.
Constraints:
n == patience.length
2 <= n <= 105
patience[0] == 0
1 <= patience[i] <= 105 for 1 <= i < n
1 <= edges.length <= min(105, n * (n - 1) / 2)
edges[i].length == 2
0 <= ui, vi < n
ui != vi
There are no duplicate edges.
Each server can directly or indirectly reach another server. | [Python3] graph | 176 | the-time-when-the-network-becomes-idle | 0.508 | ye15 | Medium | 28,361 | 2,039 |
kth smallest product of two sorted arrays | class Solution:
def kthSmallestProduct(self, nums1: List[int], nums2: List[int], k: int) -> int:
def fn(val):
"""Return count of products <= val."""
ans = 0
for x in nums1:
if x < 0: ans += len(nums2) - bisect_left(nums2, ceil(val/x))
elif x == 0:
if 0 <= val: ans += len(nums2)
else: ans += bisect_right(nums2, floor(val/x))
return ans
lo, hi = -10**10, 10**10 + 1
while lo < hi:
mid = lo + hi >> 1
if fn(mid) < k: lo = mid + 1
else: hi = mid
return lo | https://leetcode.com/problems/kth-smallest-product-of-two-sorted-arrays/discuss/1524190/Python3-binary-search | 8 | Given two sorted 0-indexed integer arrays nums1 and nums2 as well as an integer k, return the kth (1-based) smallest product of nums1[i] * nums2[j] where 0 <= i < nums1.length and 0 <= j < nums2.length.
Example 1:
Input: nums1 = [2,5], nums2 = [3,4], k = 2
Output: 8
Explanation: The 2 smallest products are:
- nums1[0] * nums2[0] = 2 * 3 = 6
- nums1[0] * nums2[1] = 2 * 4 = 8
The 2nd smallest product is 8.
Example 2:
Input: nums1 = [-4,-2,0,3], nums2 = [2,4], k = 6
Output: 0
Explanation: The 6 smallest products are:
- nums1[0] * nums2[1] = (-4) * 4 = -16
- nums1[0] * nums2[0] = (-4) * 2 = -8
- nums1[1] * nums2[1] = (-2) * 4 = -8
- nums1[1] * nums2[0] = (-2) * 2 = -4
- nums1[2] * nums2[0] = 0 * 2 = 0
- nums1[2] * nums2[1] = 0 * 4 = 0
The 6th smallest product is 0.
Example 3:
Input: nums1 = [-2,-1,0,1,2], nums2 = [-3,-1,2,4,5], k = 3
Output: -6
Explanation: The 3 smallest products are:
- nums1[0] * nums2[4] = (-2) * 5 = -10
- nums1[0] * nums2[3] = (-2) * 4 = -8
- nums1[4] * nums2[0] = 2 * (-3) = -6
The 3rd smallest product is -6.
Constraints:
1 <= nums1.length, nums2.length <= 5 * 104
-105 <= nums1[i], nums2[j] <= 105
1 <= k <= nums1.length * nums2.length
nums1 and nums2 are sorted. | [Python3] binary search | 1,300 | kth-smallest-product-of-two-sorted-arrays | 0.291 | ye15 | Hard | 28,368 | 2,040 |
check if numbers are ascending in a sentence | class Solution:
def areNumbersAscending(self, s: str) -> bool:
nums = [int(w) for w in s.split() if w.isdigit()]
return all(nums[i-1] < nums[i] for i in range(1, len(nums))) | https://leetcode.com/problems/check-if-numbers-are-ascending-in-a-sentence/discuss/1525219/Python3-2-line | 24 | A sentence is a list of tokens separated by a single space with no leading or trailing spaces. Every token is either a positive number consisting of digits 0-9 with no leading zeros, or a word consisting of lowercase English letters.
For example, "a puppy has 2 eyes 4 legs" is a sentence with seven tokens: "2" and "4" are numbers and the other tokens such as "puppy" are words.
Given a string s representing a sentence, you need to check if all the numbers in s are strictly increasing from left to right (i.e., other than the last number, each number is strictly smaller than the number on its right in s).
Return true if so, or false otherwise.
Example 1:
Input: s = "1 box has 3 blue 4 red 6 green and 12 yellow marbles"
Output: true
Explanation: The numbers in s are: 1, 3, 4, 6, 12.
They are strictly increasing from left to right: 1 < 3 < 4 < 6 < 12.
Example 2:
Input: s = "hello world 5 x 5"
Output: false
Explanation: The numbers in s are: 5, 5. They are not strictly increasing.
Example 3:
Input: s = "sunset is at 7 51 pm overnight lows will be in the low 50 and 60 s"
Output: false
Explanation: The numbers in s are: 7, 51, 50, 60. They are not strictly increasing.
Constraints:
3 <= s.length <= 200
s consists of lowercase English letters, spaces, and digits from 0 to 9, inclusive.
The number of tokens in s is between 2 and 100, inclusive.
The tokens in s are separated by a single space.
There are at least two numbers in s.
Each number in s is a positive number less than 100, with no leading zeros.
s contains no leading or trailing spaces. | [Python3] 2-line | 1,400 | check-if-numbers-are-ascending-in-a-sentence | 0.661 | ye15 | Easy | 28,372 | 2,042 |
count number of maximum bitwise or subsets | class Solution:
def countMaxOrSubsets(self, nums: List[int]) -> int:
target = reduce(or_, nums)
@cache
def fn(i, mask):
"""Return number of subsets to get target."""
if mask == target: return 2**(len(nums)-i)
if i == len(nums): return 0
return fn(i+1, mask | nums[i]) + fn(i+1, mask)
return fn(0, 0) | https://leetcode.com/problems/count-number-of-maximum-bitwise-or-subsets/discuss/1525225/Python3-top-down-dp | 8 | Given an integer array nums, find the maximum possible bitwise OR of a subset of nums and return the number of different non-empty subsets with the maximum bitwise OR.
An array a is a subset of an array b if a can be obtained from b by deleting some (possibly zero) elements of b. Two subsets are considered different if the indices of the elements chosen are different.
The bitwise OR of an array a is equal to a[0] OR a[1] OR ... OR a[a.length - 1] (0-indexed).
Example 1:
Input: nums = [3,1]
Output: 2
Explanation: The maximum possible bitwise OR of a subset is 3. There are 2 subsets with a bitwise OR of 3:
- [3]
- [3,1]
Example 2:
Input: nums = [2,2,2]
Output: 7
Explanation: All non-empty subsets of [2,2,2] have a bitwise OR of 2. There are 23 - 1 = 7 total subsets.
Example 3:
Input: nums = [3,2,1,5]
Output: 6
Explanation: The maximum possible bitwise OR of a subset is 7. There are 6 subsets with a bitwise OR of 7:
- [3,5]
- [3,1,5]
- [3,2,5]
- [3,2,1,5]
- [2,5]
- [2,1,5]
Constraints:
1 <= nums.length <= 16
1 <= nums[i] <= 105 | [Python3] top-down dp | 729 | count-number-of-maximum-bitwise-or-subsets | 0.748 | ye15 | Medium | 28,406 | 2,044 |
second minimum time to reach destination | class Solution:
def secondMinimum(self, n: int, edges: List[List[int]], time: int, change: int) -> int:
graph = [[] for _ in range(n)]
for u, v in edges:
graph[u-1].append(v-1)
graph[v-1].append(u-1)
pq = [(0, 0)]
seen = [[] for _ in range(n)]
least = None
while pq:
t, u = heappop(pq)
if u == n-1:
if least is None: least = t
elif least < t: return t
if (t//change) & 1: t = (t//change+1)*change # waiting for green
t += time
for v in graph[u]:
if not seen[v] or len(seen[v]) == 1 and seen[v][0] != t:
seen[v].append(t)
heappush(pq, (t, v)) | https://leetcode.com/problems/second-minimum-time-to-reach-destination/discuss/1525227/Python3-Dijkstra-and-BFS | 6 | A city is represented as a bi-directional connected graph with n vertices where each vertex is labeled from 1 to n (inclusive). The edges in the graph are represented as a 2D integer array edges, where each edges[i] = [ui, vi] denotes a bi-directional edge between vertex ui and vertex vi. Every vertex pair is connected by at most one edge, and no vertex has an edge to itself. The time taken to traverse any edge is time minutes.
Each vertex has a traffic signal which changes its color from green to red and vice versa every change minutes. All signals change at the same time. You can enter a vertex at any time, but can leave a vertex only when the signal is green. You cannot wait at a vertex if the signal is green.
The second minimum value is defined as the smallest value strictly larger than the minimum value.
For example the second minimum value of [2, 3, 4] is 3, and the second minimum value of [2, 2, 4] is 4.
Given n, edges, time, and change, return the second minimum time it will take to go from vertex 1 to vertex n.
Notes:
You can go through any vertex any number of times, including 1 and n.
You can assume that when the journey starts, all signals have just turned green.
Example 1:
Input: n = 5, edges = [[1,2],[1,3],[1,4],[3,4],[4,5]], time = 3, change = 5
Output: 13
Explanation:
The figure on the left shows the given graph.
The blue path in the figure on the right is the minimum time path.
The time taken is:
- Start at 1, time elapsed=0
- 1 -> 4: 3 minutes, time elapsed=3
- 4 -> 5: 3 minutes, time elapsed=6
Hence the minimum time needed is 6 minutes.
The red path shows the path to get the second minimum time.
- Start at 1, time elapsed=0
- 1 -> 3: 3 minutes, time elapsed=3
- 3 -> 4: 3 minutes, time elapsed=6
- Wait at 4 for 4 minutes, time elapsed=10
- 4 -> 5: 3 minutes, time elapsed=13
Hence the second minimum time is 13 minutes.
Example 2:
Input: n = 2, edges = [[1,2]], time = 3, change = 2
Output: 11
Explanation:
The minimum time path is 1 -> 2 with time = 3 minutes.
The second minimum time path is 1 -> 2 -> 1 -> 2 with time = 11 minutes.
Constraints:
2 <= n <= 104
n - 1 <= edges.length <= min(2 * 104, n * (n - 1) / 2)
edges[i].length == 2
1 <= ui, vi <= n
ui != vi
There are no duplicate edges.
Each vertex can be reached directly or indirectly from every other vertex.
1 <= time, change <= 103 | [Python3] Dijkstra & BFS | 462 | second-minimum-time-to-reach-destination | 0.389 | ye15 | Hard | 28,417 | 2,045 |
number of valid words in a sentence | class Solution:
def countValidWords(self, sentence: str) -> int:
def fn(word):
"""Return true if word is valid."""
seen = False
for i, ch in enumerate(word):
if ch.isdigit() or ch in "!.," and i != len(word)-1: return False
elif ch == '-':
if seen or i == 0 or i == len(word)-1 or not word[i+1].isalpha(): return False
seen = True
return True
return sum(fn(word) for word in sentence.split()) | https://leetcode.com/problems/number-of-valid-words-in-a-sentence/discuss/1537625/Python3-check-words | 20 | A sentence consists of lowercase letters ('a' to 'z'), digits ('0' to '9'), hyphens ('-'), punctuation marks ('!', '.', and ','), and spaces (' ') only. Each sentence can be broken down into one or more tokens separated by one or more spaces ' '.
A token is a valid word if all three of the following are true:
It only contains lowercase letters, hyphens, and/or punctuation (no digits).
There is at most one hyphen '-'. If present, it must be surrounded by lowercase characters ("a-b" is valid, but "-ab" and "ab-" are not valid).
There is at most one punctuation mark. If present, it must be at the end of the token ("ab,", "cd!", and "." are valid, but "a!b" and "c.," are not valid).
Examples of valid words include "a-b.", "afad", "ba-c", "a!", and "!".
Given a string sentence, return the number of valid words in sentence.
Example 1:
Input: sentence = "cat and dog"
Output: 3
Explanation: The valid words in the sentence are "cat", "and", and "dog".
Example 2:
Input: sentence = "!this 1-s b8d!"
Output: 0
Explanation: There are no valid words in the sentence.
"!this" is invalid because it starts with a punctuation mark.
"1-s" and "b8d" are invalid because they contain digits.
Example 3:
Input: sentence = "alice and bob are playing stone-game10"
Output: 5
Explanation: The valid words in the sentence are "alice", "and", "bob", "are", and "playing".
"stone-game10" is invalid because it contains digits.
Constraints:
1 <= sentence.length <= 1000
sentence only contains lowercase English letters, digits, ' ', '-', '!', '.', and ','.
There will be at least 1 token. | [Python3] check words | 1,200 | number-of-valid-words-in-a-sentence | 0.295 | ye15 | Easy | 28,420 | 2,047 |
next greater numerically balanced number | class Solution:
def nextBeautifulNumber(self, n: int) -> int:
while True:
n += 1
nn = n
freq = defaultdict(int)
while nn:
nn, d = divmod(nn, 10)
freq[d] += 1
if all(k == v for k, v in freq.items()): return n | https://leetcode.com/problems/next-greater-numerically-balanced-number/discuss/1537537/Python3-brute-force | 3 | An integer x is numerically balanced if for every digit d in the number x, there are exactly d occurrences of that digit in x.
Given an integer n, return the smallest numerically balanced number strictly greater than n.
Example 1:
Input: n = 1
Output: 22
Explanation:
22 is numerically balanced since:
- The digit 2 occurs 2 times.
It is also the smallest numerically balanced number strictly greater than 1.
Example 2:
Input: n = 1000
Output: 1333
Explanation:
1333 is numerically balanced since:
- The digit 1 occurs 1 time.
- The digit 3 occurs 3 times.
It is also the smallest numerically balanced number strictly greater than 1000.
Note that 1022 cannot be the answer because 0 appeared more than 0 times.
Example 3:
Input: n = 3000
Output: 3133
Explanation:
3133 is numerically balanced since:
- The digit 1 occurs 1 time.
- The digit 3 occurs 3 times.
It is also the smallest numerically balanced number strictly greater than 3000.
Constraints:
0 <= n <= 106 | [Python3] brute-force | 151 | next-greater-numerically-balanced-number | 0.471 | ye15 | Medium | 28,436 | 2,048 |