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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
merge strings alternately | class Solution:
def mergeAlternately(self, word1: str, word2: str) -> str:
res=''
for i in range(min(len(word1),len(word2))):
res += word1[i] + word2[i]
return res + word1[i+1:] + word2[i+1:] | https://leetcode.com/problems/merge-strings-alternately/discuss/1075531/Simple-Python-Solution | 36 | You are given two strings word1 and word2. Merge the strings by adding letters in alternating order, starting with word1. If a string is longer than the other, append the additional letters onto the end of the merged string.
Return the merged string.
Example 1:
Input: word1 = "abc", word2 = "pqr"
Output: "apbqcr"
Explanation: The merged string will be merged as so:
word1: a b c
word2: p q r
merged: a p b q c r
Example 2:
Input: word1 = "ab", word2 = "pqrs"
Output: "apbqrs"
Explanation: Notice that as word2 is longer, "rs" is appended to the end.
word1: a b
word2: p q r s
merged: a p b q r s
Example 3:
Input: word1 = "abcd", word2 = "pq"
Output: "apbqcd"
Explanation: Notice that as word1 is longer, "cd" is appended to the end.
word1: a b c d
word2: p q
merged: a p b q c d
Constraints:
1 <= word1.length, word2.length <= 100
word1 and word2 consist of lowercase English letters. | Simple Python Solution | 2,500 | merge-strings-alternately | 0.761 | lokeshsenthilkumar | Easy | 25,315 | 1,768 |
minimum number of operations to move all balls to each box | class Solution:
def minOperations(self, boxes: str) -> List[int]:
ans = [0]*len(boxes)
leftCount, leftCost, rightCount, rightCost, n = 0, 0, 0, 0, len(boxes)
for i in range(1, n):
if boxes[i-1] == '1': leftCount += 1
leftCost += leftCount # each step move to right, the cost increases by # of 1s on the left
ans[i] = leftCost
for i in range(n-2, -1, -1):
if boxes[i+1] == '1': rightCount += 1
rightCost += rightCount
ans[i] += rightCost
return ans | https://leetcode.com/problems/minimum-number-of-operations-to-move-all-balls-to-each-box/discuss/1075895/Easy-Python-beats-100-time-and-space | 126 | You have n boxes. You are given a binary string boxes of length n, where boxes[i] is '0' if the ith box is empty, and '1' if it contains one ball.
In one operation, you can move one ball from a box to an adjacent box. Box i is adjacent to box j if abs(i - j) == 1. Note that after doing so, there may be more than one ball in some boxes.
Return an array answer of size n, where answer[i] is the minimum number of operations needed to move all the balls to the ith box.
Each answer[i] is calculated considering the initial state of the boxes.
Example 1:
Input: boxes = "110"
Output: [1,1,3]
Explanation: The answer for each box is as follows:
1) First box: you will have to move one ball from the second box to the first box in one operation.
2) Second box: you will have to move one ball from the first box to the second box in one operation.
3) Third box: you will have to move one ball from the first box to the third box in two operations, and move one ball from the second box to the third box in one operation.
Example 2:
Input: boxes = "001011"
Output: [11,8,5,4,3,4]
Constraints:
n == boxes.length
1 <= n <= 2000
boxes[i] is either '0' or '1'. | Easy Python beats 100% time and space | 6,000 | minimum-number-of-operations-to-move-all-balls-to-each-box | 0.852 | trungnguyen276 | Medium | 25,363 | 1,769 |
maximum score from performing multiplication operations | class Solution:
def maximumScore(self, nums: List[int], multipliers: List[int]) -> int:
n, m = len(nums), len(multipliers)
dp = [[0]*m for _ in range(m+1)]
for i in reversed(range(m)):
for j in range(i, m):
k = i + m - j - 1
dp[i][j] = max(nums[i] * multipliers[k] + dp[i+1][j], nums[j-m+n] * multipliers[k] + dp[i][j-1])
return dp[0][-1] | https://leetcode.com/problems/maximum-score-from-performing-multiplication-operations/discuss/1075495/Python3-bottom-up-dp | 64 | You are given two 0-indexed integer arrays nums and multipliers of size n and m respectively, where n >= m.
You begin with a score of 0. You want to perform exactly m operations. On the ith operation (0-indexed) you will:
Choose one integer x from either the start or the end of the array nums.
Add multipliers[i] * x to your score.
Note that multipliers[0] corresponds to the first operation, multipliers[1] to the second operation, and so on.
Remove x from nums.
Return the maximum score after performing m operations.
Example 1:
Input: nums = [1,2,3], multipliers = [3,2,1]
Output: 14
Explanation: An optimal solution is as follows:
- Choose from the end, [1,2,3], adding 3 * 3 = 9 to the score.
- Choose from the end, [1,2], adding 2 * 2 = 4 to the score.
- Choose from the end, [1], adding 1 * 1 = 1 to the score.
The total score is 9 + 4 + 1 = 14.
Example 2:
Input: nums = [-5,-3,-3,-2,7,1], multipliers = [-10,-5,3,4,6]
Output: 102
Explanation: An optimal solution is as follows:
- Choose from the start, [-5,-3,-3,-2,7,1], adding -5 * -10 = 50 to the score.
- Choose from the start, [-3,-3,-2,7,1], adding -3 * -5 = 15 to the score.
- Choose from the start, [-3,-2,7,1], adding -3 * 3 = -9 to the score.
- Choose from the end, [-2,7,1], adding 1 * 4 = 4 to the score.
- Choose from the end, [-2,7], adding 7 * 6 = 42 to the score.
The total score is 50 + 15 - 9 + 4 + 42 = 102.
Constraints:
n == nums.length
m == multipliers.length
1 <= m <= 300
m <= n <= 105
-1000 <= nums[i], multipliers[i] <= 1000 | [Python3] bottom-up dp | 5,800 | maximum-score-from-performing-multiplication-operations | 0.366 | ye15 | Hard | 25,400 | 1,770 |
maximize palindrome length from subsequences | class Solution:
def longestPalindrome(self, word1: str, word2: str) -> int:
@cache
def fn(lo, hi):
"""Return length of longest palindromic subsequence."""
if lo >= hi: return int(lo == hi)
if word[lo] == word[hi]: return 2 + fn(lo+1, hi-1)
return max(fn(lo+1, hi), fn(lo, hi-1))
ans = 0
word = word1 + word2
for x in ascii_lowercase:
i = word1.find(x)
j = word2.rfind(x)
if i != -1 and j != -1: ans = max(ans, fn(i, j + len(word1)))
return ans | https://leetcode.com/problems/maximize-palindrome-length-from-subsequences/discuss/1075709/Python3-top-down-dp | 13 | You are given two strings, word1 and word2. You want to construct a string in the following manner:
Choose some non-empty subsequence subsequence1 from word1.
Choose some non-empty subsequence subsequence2 from word2.
Concatenate the subsequences: subsequence1 + subsequence2, to make the string.
Return the length of the longest palindrome that can be constructed in the described manner. If no palindromes can be constructed, return 0.
A subsequence of a string s is a string that can be made by deleting some (possibly none) characters from s without changing the order of the remaining characters.
A palindrome is a string that reads the same forward as well as backward.
Example 1:
Input: word1 = "cacb", word2 = "cbba"
Output: 5
Explanation: Choose "ab" from word1 and "cba" from word2 to make "abcba", which is a palindrome.
Example 2:
Input: word1 = "ab", word2 = "ab"
Output: 3
Explanation: Choose "ab" from word1 and "a" from word2 to make "aba", which is a palindrome.
Example 3:
Input: word1 = "aa", word2 = "bb"
Output: 0
Explanation: You cannot construct a palindrome from the described method, so return 0.
Constraints:
1 <= word1.length, word2.length <= 1000
word1 and word2 consist of lowercase English letters. | [Python3] top-down dp | 425 | maximize-palindrome-length-from-subsequences | 0.352 | ye15 | Hard | 25,423 | 1,771 |
count items matching a rule | class Solution:
def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
d = {'type': 0, 'color': 1, 'name': 2}
return sum(1 for item in items if item[d[ruleKey]] == ruleValue) | https://leetcode.com/problems/count-items-matching-a-rule/discuss/1085906/Python-3-or-2-liner-or-Explanation | 46 | You are given an array items, where each items[i] = [typei, colori, namei] describes the type, color, and name of the ith item. You are also given a rule represented by two strings, ruleKey and ruleValue.
The ith item is said to match the rule if one of the following is true:
ruleKey == "type" and ruleValue == typei.
ruleKey == "color" and ruleValue == colori.
ruleKey == "name" and ruleValue == namei.
Return the number of items that match the given rule.
Example 1:
Input: items = [["phone","blue","pixel"],["computer","silver","lenovo"],["phone","gold","iphone"]], ruleKey = "color", ruleValue = "silver"
Output: 1
Explanation: There is only one item matching the given rule, which is ["computer","silver","lenovo"].
Example 2:
Input: items = [["phone","blue","pixel"],["computer","silver","phone"],["phone","gold","iphone"]], ruleKey = "type", ruleValue = "phone"
Output: 2
Explanation: There are only two items matching the given rule, which are ["phone","blue","pixel"] and ["phone","gold","iphone"]. Note that the item ["computer","silver","phone"] does not match.
Constraints:
1 <= items.length <= 104
1 <= typei.length, colori.length, namei.length, ruleValue.length <= 10
ruleKey is equal to either "type", "color", or "name".
All strings consist only of lowercase letters. | Python 3 | 2-liner | Explanation | 3,200 | count-items-matching-a-rule | 0.843 | idontknoooo | Easy | 25,426 | 1,773 |
closest dessert cost | class Solution:
def closestCost(self, baseCosts: List[int], toppingCosts: List[int], target: int) -> int:
toppingCosts *= 2
@cache
def fn(i, x):
"""Return sum of subsequence of toppingCosts[i:] closest to x."""
if x < 0 or i == len(toppingCosts): return 0
return min(fn(i+1, x), toppingCosts[i] + fn(i+1, x-toppingCosts[i]), key=lambda y: (abs(y-x), y))
ans = inf
for bc in baseCosts:
ans = min(ans, bc + fn(0, target - bc), key=lambda x: (abs(x-target), x))
return ans | https://leetcode.com/problems/closest-dessert-cost/discuss/1085820/Python3-top-down-dp | 18 | You would like to make dessert and are preparing to buy the ingredients. You have n ice cream base flavors and m types of toppings to choose from. You must follow these rules when making your dessert:
There must be exactly one ice cream base.
You can add one or more types of topping or have no toppings at all.
There are at most two of each type of topping.
You are given three inputs:
baseCosts, an integer array of length n, where each baseCosts[i] represents the price of the ith ice cream base flavor.
toppingCosts, an integer array of length m, where each toppingCosts[i] is the price of one of the ith topping.
target, an integer representing your target price for dessert.
You want to make a dessert with a total cost as close to target as possible.
Return the closest possible cost of the dessert to target. If there are multiple, return the lower one.
Example 1:
Input: baseCosts = [1,7], toppingCosts = [3,4], target = 10
Output: 10
Explanation: Consider the following combination (all 0-indexed):
- Choose base 1: cost 7
- Take 1 of topping 0: cost 1 x 3 = 3
- Take 0 of topping 1: cost 0 x 4 = 0
Total: 7 + 3 + 0 = 10.
Example 2:
Input: baseCosts = [2,3], toppingCosts = [4,5,100], target = 18
Output: 17
Explanation: Consider the following combination (all 0-indexed):
- Choose base 1: cost 3
- Take 1 of topping 0: cost 1 x 4 = 4
- Take 2 of topping 1: cost 2 x 5 = 10
- Take 0 of topping 2: cost 0 x 100 = 0
Total: 3 + 4 + 10 + 0 = 17. You cannot make a dessert with a total cost of 18.
Example 3:
Input: baseCosts = [3,10], toppingCosts = [2,5], target = 9
Output: 8
Explanation: It is possible to make desserts with cost 8 and 10. Return 8 as it is the lower cost.
Constraints:
n == baseCosts.length
m == toppingCosts.length
1 <= n, m <= 10
1 <= baseCosts[i], toppingCosts[i] <= 104
1 <= target <= 104 | [Python3] top-down dp | 3,000 | closest-dessert-cost | 0.468 | ye15 | Medium | 25,471 | 1,774 |
equal sum arrays with minimum number of operations | class Solution:
def minOperations(self, nums1: List[int], nums2: List[int]) -> int:
if 6*len(nums1) < len(nums2) or 6*len(nums2) < len(nums1): return -1 # impossible
if sum(nums1) < sum(nums2): nums1, nums2 = nums2, nums1
s1, s2 = sum(nums1), sum(nums2)
nums1 = [-x for x in nums1] # max-heap
heapify(nums1)
heapify(nums2)
ans = 0
while s1 > s2:
x1, x2 = nums1[0], nums2[0]
if -1-x1 > 6-x2: # change x1 to 1
s1 += x1 + 1
heapreplace(nums1, -1)
else:
s2 += 6 - x2
heapreplace(nums2, 6)
ans += 1
return ans | https://leetcode.com/problems/equal-sum-arrays-with-minimum-number-of-operations/discuss/1085806/Python3-two-heaps | 18 | You are given two arrays of integers nums1 and nums2, possibly of different lengths. The values in the arrays are between 1 and 6, inclusive.
In one operation, you can change any integer's value in any of the arrays to any value between 1 and 6, inclusive.
Return the minimum number of operations required to make the sum of values in nums1 equal to the sum of values in nums2. Return -1 if it is not possible to make the sum of the two arrays equal.
Example 1:
Input: nums1 = [1,2,3,4,5,6], nums2 = [1,1,2,2,2,2]
Output: 3
Explanation: You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed.
- Change nums2[0] to 6. nums1 = [1,2,3,4,5,6], nums2 = [6,1,2,2,2,2].
- Change nums1[5] to 1. nums1 = [1,2,3,4,5,1], nums2 = [6,1,2,2,2,2].
- Change nums1[2] to 2. nums1 = [1,2,2,4,5,1], nums2 = [6,1,2,2,2,2].
Example 2:
Input: nums1 = [1,1,1,1,1,1,1], nums2 = [6]
Output: -1
Explanation: There is no way to decrease the sum of nums1 or to increase the sum of nums2 to make them equal.
Example 3:
Input: nums1 = [6,6], nums2 = [1]
Output: 3
Explanation: You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed.
- Change nums1[0] to 2. nums1 = [2,6], nums2 = [1].
- Change nums1[1] to 2. nums1 = [2,2], nums2 = [1].
- Change nums2[0] to 4. nums1 = [2,2], nums2 = [4].
Constraints:
1 <= nums1.length, nums2.length <= 105
1 <= nums1[i], nums2[i] <= 6 | [Python3] two heaps | 848 | equal-sum-arrays-with-minimum-number-of-operations | 0.527 | ye15 | Medium | 25,483 | 1,775 |
car fleet ii | class Solution:
def getCollisionTimes(self, cars: List[List[int]]) -> List[float]:
# Stack: go from back and use stack to get ans
# Time: O(n)
# Space: O(n)
stack = [] # index
ans = [-1] * len(cars)
for i in range(len(cars)-1,-1,-1):
# remove cars that are faster than current car since it will never collide
while stack and cars[i][1] <= cars[stack[-1]][1]:
stack.pop()
while stack: # if car left, we can compute collide time with current car.
collision_t = (cars[stack[-1]][0] - cars[i][0]) / (cars[i][1] - cars[stack[-1]][1])
# if current car's collide time is greater than previous car's collide time
# (previous collided before current), then we have to find previous car's previous car
# to compute collide time with that car, so we pop from stack and re-process
# Otherwise, we add that collide time to answer and break
if ans[stack[-1]] == -1 or collision_t <= ans[stack[-1]]:
ans[i] = collision_t
break
stack.pop()
stack.append(i)
return ans | https://leetcode.com/problems/car-fleet-ii/discuss/1557743/Python3-Stack-Time%3A-O(n)-and-Space%3A-O(n) | 4 | There are n cars traveling at different speeds in the same direction along a one-lane road. You are given an array cars of length n, where cars[i] = [positioni, speedi] represents:
positioni is the distance between the ith car and the beginning of the road in meters. It is guaranteed that positioni < positioni+1.
speedi is the initial speed of the ith car in meters per second.
For simplicity, cars can be considered as points moving along the number line. Two cars collide when they occupy the same position. Once a car collides with another car, they unite and form a single car fleet. The cars in the formed fleet will have the same position and the same speed, which is the initial speed of the slowest car in the fleet.
Return an array answer, where answer[i] is the time, in seconds, at which the ith car collides with the next car, or -1 if the car does not collide with the next car. Answers within 10-5 of the actual answers are accepted.
Example 1:
Input: cars = [[1,2],[2,1],[4,3],[7,2]]
Output: [1.00000,-1.00000,3.00000,-1.00000]
Explanation: After exactly one second, the first car will collide with the second car, and form a car fleet with speed 1 m/s. After exactly 3 seconds, the third car will collide with the fourth car, and form a car fleet with speed 2 m/s.
Example 2:
Input: cars = [[3,4],[5,4],[6,3],[9,1]]
Output: [2.00000,1.00000,1.50000,-1.00000]
Constraints:
1 <= cars.length <= 105
1 <= positioni, speedi <= 106
positioni < positioni+1 | [Python3] Stack - Time: O(n) & Space: O(n) | 261 | car-fleet-ii | 0.534 | jae2021 | Hard | 25,493 | 1,776 |
find nearest point that has the same x or y coordinate | class Solution:
def nearestValidPoint(self, x: int, y: int, points: List[List[int]]) -> int:
minDist = math.inf
ans = -1
for i in range(len(points)):
if points[i][0]==x or points[i][1]==y:
manDist = abs(points[i][0]-x)+abs(points[i][1]-y)
if manDist<minDist:
ans = i
minDist = manDist
return ans | https://leetcode.com/problems/find-nearest-point-that-has-the-same-x-or-y-coordinate/discuss/1229047/Python-Easy-solution | 20 | You are given two integers, x and y, which represent your current location on a Cartesian grid: (x, y). You are also given an array points where each points[i] = [ai, bi] represents that a point exists at (ai, bi). A point is valid if it shares the same x-coordinate or the same y-coordinate as your location.
Return the index (0-indexed) of the valid point with the smallest Manhattan distance from your current location. If there are multiple, return the valid point with the smallest index. If there are no valid points, return -1.
The Manhattan distance between two points (x1, y1) and (x2, y2) is abs(x1 - x2) + abs(y1 - y2).
Example 1:
Input: x = 3, y = 4, points = [[1,2],[3,1],[2,4],[2,3],[4,4]]
Output: 2
Explanation: Of all the points, only [3,1], [2,4] and [4,4] are valid. Of the valid points, [2,4] and [4,4] have the smallest Manhattan distance from your current location, with a distance of 1. [2,4] has the smallest index, so return 2.
Example 2:
Input: x = 3, y = 4, points = [[3,4]]
Output: 0
Explanation: The answer is allowed to be on the same location as your current location.
Example 3:
Input: x = 3, y = 4, points = [[2,3]]
Output: -1
Explanation: There are no valid points.
Constraints:
1 <= points.length <= 104
points[i].length == 2
1 <= x, y, ai, bi <= 104 | [Python] Easy solution | 2,300 | find-nearest-point-that-has-the-same-x-or-y-coordinate | 0.673 | arkumari2000 | Easy | 25,498 | 1,779 |
check if number is a sum of powers of three | class Solution:
def checkPowersOfThree(self, n: int) -> bool:
while n:
n, rem = divmod(n, 3)
if rem == 2:
return False
return True | https://leetcode.com/problems/check-if-number-is-a-sum-of-powers-of-three/discuss/1341617/While-loop-99-speed | 3 | Given an integer n, return true if it is possible to represent n as the sum of distinct powers of three. Otherwise, return false.
An integer y is a power of three if there exists an integer x such that y == 3x.
Example 1:
Input: n = 12
Output: true
Explanation: 12 = 31 + 32
Example 2:
Input: n = 91
Output: true
Explanation: 91 = 30 + 32 + 34
Example 3:
Input: n = 21
Output: false
Constraints:
1 <= n <= 107 | While loop, 99% speed | 245 | check-if-number-is-a-sum-of-powers-of-three | 0.654 | EvgenySH | Medium | 25,543 | 1,780 |
sum of beauty of all substrings | class Solution:
def beautySum(self, s: str) -> int:
ans = 0
for i in range(len(s)):
freq = [0]*26
for j in range(i, len(s)):
freq[ord(s[j])-97] += 1
ans += max(freq) - min(x for x in freq if x)
return ans | https://leetcode.com/problems/sum-of-beauty-of-all-substrings/discuss/1096392/Python3-freq-table | 41 | The beauty of a string is the difference in frequencies between the most frequent and least frequent characters.
For example, the beauty of "abaacc" is 3 - 1 = 2.
Given a string s, return the sum of beauty of all of its substrings.
Example 1:
Input: s = "aabcb"
Output: 5
Explanation: The substrings with non-zero beauty are ["aab","aabc","aabcb","abcb","bcb"], each with beauty equal to 1.
Example 2:
Input: s = "aabcbaa"
Output: 17
Constraints:
1 <= s.length <= 500
s consists of only lowercase English letters. | [Python3] freq table | 2,800 | sum-of-beauty-of-all-substrings | 0.605 | ye15 | Medium | 25,556 | 1,781 |
count pairs of nodes | class Solution:
def countPairs(self, n: int, edges: List[List[int]], queries: List[int]) -> List[int]:
degree = [0]*n
freq = defaultdict(int)
for u, v in edges:
degree[u-1] += 1
degree[v-1] += 1
freq[min(u-1, v-1), max(u-1, v-1)] += 1
vals = sorted(degree)
ans = []
for query in queries:
cnt = 0
lo, hi = 0, n-1
while lo < hi:
if query < vals[lo] + vals[hi]:
cnt += hi - lo # (lo, hi), (lo+1, hi), ..., (hi-1, hi) all valid
hi -= 1
else: lo += 1
for u, v in freq:
if degree[u] + degree[v] - freq[u, v] <= query < degree[u] + degree[v]: cnt -= 1
ans.append(cnt)
return ans | https://leetcode.com/problems/count-pairs-of-nodes/discuss/1096612/Python3-2-pointer | 14 | You are given an undirected graph defined by an integer n, the number of nodes, and a 2D integer array edges, the edges in the graph, where edges[i] = [ui, vi] indicates that there is an undirected edge between ui and vi. You are also given an integer array queries.
Let incident(a, b) be defined as the number of edges that are connected to either node a or b.
The answer to the jth query is the number of pairs of nodes (a, b) that satisfy both of the following conditions:
a < b
incident(a, b) > queries[j]
Return an array answers such that answers.length == queries.length and answers[j] is the answer of the jth query.
Note that there can be multiple edges between the same two nodes.
Example 1:
Input: n = 4, edges = [[1,2],[2,4],[1,3],[2,3],[2,1]], queries = [2,3]
Output: [6,5]
Explanation: The calculations for incident(a, b) are shown in the table above.
The answers for each of the queries are as follows:
- answers[0] = 6. All the pairs have an incident(a, b) value greater than 2.
- answers[1] = 5. All the pairs except (3, 4) have an incident(a, b) value greater than 3.
Example 2:
Input: n = 5, edges = [[1,5],[1,5],[3,4],[2,5],[1,3],[5,1],[2,3],[2,5]], queries = [1,2,3,4,5]
Output: [10,10,9,8,6]
Constraints:
2 <= n <= 2 * 104
1 <= edges.length <= 105
1 <= ui, vi <= n
ui != vi
1 <= queries.length <= 20
0 <= queries[j] < edges.length | [Python3] 2-pointer | 352 | count-pairs-of-nodes | 0.38 | ye15 | Hard | 25,564 | 1,782 |
check if binary string has at most one segment of ones | class Solution:
def checkOnesSegment(self, s: str) -> bool:
return "01" not in s | https://leetcode.com/problems/check-if-binary-string-has-at-most-one-segment-of-ones/discuss/1097225/Python-3-Check-for-%2201%22-(1-Liner) | 32 | Given a binary string s without leading zeros, return true if s contains at most one contiguous segment of ones. Otherwise, return false.
Example 1:
Input: s = "1001"
Output: false
Explanation: The ones do not form a contiguous segment.
Example 2:
Input: s = "110"
Output: true
Constraints:
1 <= s.length <= 100
s[i] is either '0' or '1'.
s[0] is '1'. | [Python 3] - Check for "01" (1 Liner) | 977 | check-if-binary-string-has-at-most-one-segment-of-ones | 0.404 | mb557x | Easy | 25,565 | 1,784 |
minimum elements to add to form a given sum | class Solution:
def minElements(self, nums: List[int], limit: int, goal: int) -> int:
return math.ceil(abs(goal - sum(nums)) / limit) | https://leetcode.com/problems/minimum-elements-to-add-to-form-a-given-sum/discuss/1121048/Python-3-or-1-liner-or-Explanation | 6 | You are given an integer array nums and two integers limit and goal. The array nums has an interesting property that abs(nums[i]) <= limit.
Return the minimum number of elements you need to add to make the sum of the array equal to goal. The array must maintain its property that abs(nums[i]) <= limit.
Note that abs(x) equals x if x >= 0, and -x otherwise.
Example 1:
Input: nums = [1,-1,1], limit = 3, goal = -4
Output: 2
Explanation: You can add -2 and -3, then the sum of the array will be 1 - 1 + 1 - 2 - 3 = -4.
Example 2:
Input: nums = [1,-10,9,1], limit = 100, goal = 0
Output: 1
Constraints:
1 <= nums.length <= 105
1 <= limit <= 106
-limit <= nums[i] <= limit
-109 <= goal <= 109 | Python 3 | 1-liner | Explanation | 285 | minimum-elements-to-add-to-form-a-given-sum | 0.424 | idontknoooo | Medium | 25,592 | 1,785 |
number of restricted paths from first to last node | class Solution:
def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:
graph = {} # graph as adjacency list
for u, v, w in edges:
graph.setdefault(u, []).append((v, w))
graph.setdefault(v, []).append((u, w))
queue = [n]
dist = {n: 0}
while queue:
newq = []
for u in queue:
for v, w in graph[u]:
if v not in dist or dist[u] + w < dist[v]:
dist[v] = dist[u] + w
newq.append(v)
queue = newq
@cache
def fn(u):
"""Return number of restricted paths from u to n."""
if u == n: return 1 # boundary condition
ans = 0
for v, _ in graph[u]:
if dist[u] > dist[v]: ans += fn(v)
return ans
return fn(1) % 1_000_000_007 | https://leetcode.com/problems/number-of-restricted-paths-from-first-to-last-node/discuss/1097219/Python3-Dijkstra-%2B-dp | 4 | There is an undirected weighted connected graph. You are given a positive integer n which denotes that the graph has n nodes labeled from 1 to n, and an array edges where each edges[i] = [ui, vi, weighti] denotes that there is an edge between nodes ui and vi with weight equal to weighti.
A path from node start to node end is a sequence of nodes [z0, z1, z2, ..., zk] such that z0 = start and zk = end and there is an edge between zi and zi+1 where 0 <= i <= k-1.
The distance of a path is the sum of the weights on the edges of the path. Let distanceToLastNode(x) denote the shortest distance of a path between node n and node x. A restricted path is a path that also satisfies that distanceToLastNode(zi) > distanceToLastNode(zi+1) where 0 <= i <= k-1.
Return the number of restricted paths from node 1 to node n. Since that number may be too large, return it modulo 109 + 7.
Example 1:
Input: n = 5, edges = [[1,2,3],[1,3,3],[2,3,1],[1,4,2],[5,2,2],[3,5,1],[5,4,10]]
Output: 3
Explanation: Each circle contains the node number in black and its distanceToLastNode value in blue. The three restricted paths are:
1) 1 --> 2 --> 5
2) 1 --> 2 --> 3 --> 5
3) 1 --> 3 --> 5
Example 2:
Input: n = 7, edges = [[1,3,1],[4,1,2],[7,3,4],[2,5,3],[5,6,1],[6,7,2],[7,5,3],[2,6,4]]
Output: 1
Explanation: Each circle contains the node number in black and its distanceToLastNode value in blue. The only restricted path is 1 --> 3 --> 7.
Constraints:
1 <= n <= 2 * 104
n - 1 <= edges.length <= 4 * 104
edges[i].length == 3
1 <= ui, vi <= n
ui != vi
1 <= weighti <= 105
There is at most one edge between any two nodes.
There is at least one path between any two nodes. | [Python3] Dijkstra + dp | 401 | number-of-restricted-paths-from-first-to-last-node | 0.393 | ye15 | Medium | 25,603 | 1,786 |
make the xor of all segments equal to zero | class Solution:
def minChanges(self, nums: List[int], k: int) -> int:
freq = defaultdict(lambda: defaultdict(int))
for i, x in enumerate(nums): freq[i%k][x] += 1 # freq by row
n = 1 << 10
dp = [0] + [-inf]*(n-1)
for i in range(k):
mx = max(dp)
tmp = [0]*n
for x, c in enumerate(dp):
for xx, cc in freq[i].items():
tmp[x^xx] = max(tmp[x^xx], c + cc, mx)
dp = tmp
return len(nums) - dp[0] | https://leetcode.com/problems/make-the-xor-of-all-segments-equal-to-zero/discuss/1100417/Python3-dp | 3 | You are given an array nums and an integer k. The XOR of a segment [left, right] where left <= right is the XOR of all the elements with indices between left and right, inclusive: nums[left] XOR nums[left+1] XOR ... XOR nums[right].
Return the minimum number of elements to change in the array such that the XOR of all segments of size k is equal to zero.
Example 1:
Input: nums = [1,2,0,3,0], k = 1
Output: 3
Explanation: Modify the array from [1,2,0,3,0] to from [0,0,0,0,0].
Example 2:
Input: nums = [3,4,5,2,1,7,3,4,7], k = 3
Output: 3
Explanation: Modify the array from [3,4,5,2,1,7,3,4,7] to [3,4,7,3,4,7,3,4,7].
Example 3:
Input: nums = [1,2,4,1,2,5,1,2,6], k = 3
Output: 3
Explanation: Modify the array from [1,2,4,1,2,5,1,2,6] to [1,2,3,1,2,3,1,2,3].
Constraints:
1 <= k <= nums.length <= 2000
0 <= nums[i] < 210 | [Python3] dp | 184 | make-the-xor-of-all-segments-equal-to-zero | 0.395 | ye15 | Hard | 25,608 | 1,787 |
check if one string swap can make strings equal | class Solution:
def areAlmostEqual(self, s1: str, s2: str) -> bool:
diff = [[x, y] for x, y in zip(s1, s2) if x != y]
return not diff or len(diff) == 2 and diff[0][::-1] == diff[1] | https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal/discuss/1108295/Python3-check-diff | 67 | You are given two strings s1 and s2 of equal length. A string swap is an operation where you choose two indices in a string (not necessarily different) and swap the characters at these indices.
Return true if it is possible to make both strings equal by performing at most one string swap on exactly one of the strings. Otherwise, return false.
Example 1:
Input: s1 = "bank", s2 = "kanb"
Output: true
Explanation: For example, swap the first character with the last character of s2 to make "bank".
Example 2:
Input: s1 = "attack", s2 = "defend"
Output: false
Explanation: It is impossible to make them equal with one string swap.
Example 3:
Input: s1 = "kelb", s2 = "kelb"
Output: true
Explanation: The two strings are already equal, so no string swap operation is required.
Constraints:
1 <= s1.length, s2.length <= 100
s1.length == s2.length
s1 and s2 consist of only lowercase English letters. | [Python3] check diff | 5,900 | check-if-one-string-swap-can-make-strings-equal | 0.456 | ye15 | Easy | 25,609 | 1,790 |
find center of star graph | class Solution:
def findCenter(self, edges: List[List[int]]) -> int:
""" From the Constraints: A valid STAR GRAPH is confirmed.
That means the center will be common to every edges.
Therefore we can get the center by comparing only first 2 elements"""
for i in range (1):
# Check if first element of first edge mathches with any element of second edges
if edges[i][0] == edges [i+1][0] or edges[i][0] == edges[i+1][1]:
return edges[i][0]
#Otherwise second element of first edge will be the answer
else:
return edges[i][1] | https://leetcode.com/problems/find-center-of-star-graph/discuss/1568945/Beginner-Friendly-solution-in-O(1)-time-with-detailed-explanation | 4 | There is an undirected star graph consisting of n nodes labeled from 1 to n. A star graph is a graph where there is one center node and exactly n - 1 edges that connect the center node with every other node.
You are given a 2D integer array edges where each edges[i] = [ui, vi] indicates that there is an edge between the nodes ui and vi. Return the center of the given star graph.
Example 1:
Input: edges = [[1,2],[2,3],[4,2]]
Output: 2
Explanation: As shown in the figure above, node 2 is connected to every other node, so 2 is the center.
Example 2:
Input: edges = [[1,2],[5,1],[1,3],[1,4]]
Output: 1
Constraints:
3 <= n <= 105
edges.length == n - 1
edges[i].length == 2
1 <= ui, vi <= n
ui != vi
The given edges represent a valid star graph. | Beginner Friendly solution in O(1) time with detailed explanation | 331 | find-center-of-star-graph | 0.835 | stormbreaker_x | Easy | 25,648 | 1,791 |
maximum average pass ratio | class Solution:
def maxAverageRatio(self, classes: List[List[int]], extraStudents: int) -> float:
n = len(classes)
impacts = [0]*n
minRatioIndex = 0
# calculate and store impacts for each class in form of tuples -> (-impactValue, passCount, totalCount)
for i in range(n):
passCount = classes[i][0]
totalCount = classes[i][1]
# calculate the impact for class i
currentRatio = passCount/totalCount
expectedRatioAfterUpdate = (passCount+1)/(totalCount+1)
impact = expectedRatioAfterUpdate - currentRatio
impacts[i] = (-impact, passCount, totalCount) # note the - sign for impact
heapq.heapify(impacts)
while(extraStudents > 0):
# pick the next class with greatest impact
_, passCount, totalCount = heapq.heappop(impacts)
# assign a student to the class
passCount+=1
totalCount+=1
# calculate the updated impact for current class
currentRatio = passCount/totalCount
expectedRatioAfterUpdate = (passCount+1)/(totalCount+1)
impact = expectedRatioAfterUpdate - currentRatio
# insert updated impact back into the heap
heapq.heappush(impacts, (-impact, passCount, totalCount))
extraStudents -= 1
result = 0
# for all the updated classes calculate the total passRatio
for _, passCount, totalCount in impacts:
result += passCount/totalCount
# return the average pass ratio
return result/n | https://leetcode.com/problems/maximum-average-pass-ratio/discuss/1108491/Python-100-Efficient-solution-easy-to-understand-with-comments-and-explanation | 14 | There is a school that has classes of students and each class will be having a final exam. You are given a 2D integer array classes, where classes[i] = [passi, totali]. You know beforehand that in the ith class, there are totali total students, but only passi number of students will pass the exam.
You are also given an integer extraStudents. There are another extraStudents brilliant students that are guaranteed to pass the exam of any class they are assigned to. You want to assign each of the extraStudents students to a class in a way that maximizes the average pass ratio across all the classes.
The pass ratio of a class is equal to the number of students of the class that will pass the exam divided by the total number of students of the class. The average pass ratio is the sum of pass ratios of all the classes divided by the number of the classes.
Return the maximum possible average pass ratio after assigning the extraStudents students. Answers within 10-5 of the actual answer will be accepted.
Example 1:
Input: classes = [[1,2],[3,5],[2,2]], extraStudents = 2
Output: 0.78333
Explanation: You can assign the two extra students to the first class. The average pass ratio will be equal to (3/4 + 3/5 + 2/2) / 3 = 0.78333.
Example 2:
Input: classes = [[2,4],[3,9],[4,5],[2,10]], extraStudents = 4
Output: 0.53485
Constraints:
1 <= classes.length <= 105
classes[i].length == 2
1 <= passi <= totali <= 105
1 <= extraStudents <= 105 | [Python] 100% Efficient solution, easy to understand with comments and explanation | 1,000 | maximum-average-pass-ratio | 0.521 | CaptainX | Medium | 25,697 | 1,792 |
maximum score of a good subarray | class Solution:
def maximumScore(self, nums: List[int], k: int) -> int:
ans = mn = nums[k]
lo = hi = k
while 0 <= lo-1 or hi+1 < len(nums):
if lo == 0 or hi+1 < len(nums) and nums[lo-1] < nums[hi+1]:
hi += 1
mn = min(mn, nums[hi])
else:
lo -= 1
mn = min(mn, nums[lo])
ans = max(ans, mn * (hi-lo+1))
return ans | https://leetcode.com/problems/maximum-score-of-a-good-subarray/discuss/1108326/Python3-greedy-(2-pointer) | 9 | You are given an array of integers nums (0-indexed) and an integer k.
The score of a subarray (i, j) is defined as min(nums[i], nums[i+1], ..., nums[j]) * (j - i + 1). A good subarray is a subarray where i <= k <= j.
Return the maximum possible score of a good subarray.
Example 1:
Input: nums = [1,4,3,7,4,5], k = 3
Output: 15
Explanation: The optimal subarray is (1, 5) with a score of min(4,3,7,4,5) * (5-1+1) = 3 * 5 = 15.
Example 2:
Input: nums = [5,5,4,5,4,1,1,1], k = 0
Output: 20
Explanation: The optimal subarray is (0, 4) with a score of min(5,5,4,5,4) * (4-0+1) = 4 * 5 = 20.
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 2 * 104
0 <= k < nums.length | [Python3 ] greedy (2-pointer) | 300 | maximum-score-of-a-good-subarray | 0.535 | ye15 | Hard | 25,705 | 1,793 |
second largest digit in a string | class Solution:
def secondHighest(self, s: str) -> int:
s=set(s)
a=[]
for i in s:
if i.isnumeric() :
a.append(int(i))
a.sort()
if len(a)<2:
return -1
return a[len(a)-2] | https://leetcode.com/problems/second-largest-digit-in-a-string/discuss/1739076/Python3-or-Faster-Solution-or-Easiest-or-brute-force | 5 | Given an alphanumeric string s, return the second largest numerical digit that appears in s, or -1 if it does not exist.
An alphanumeric string is a string consisting of lowercase English letters and digits.
Example 1:
Input: s = "dfa12321afd"
Output: 2
Explanation: The digits that appear in s are [1, 2, 3]. The second largest digit is 2.
Example 2:
Input: s = "abc1111"
Output: -1
Explanation: The digits that appear in s are [1]. There is no second largest digit.
Constraints:
1 <= s.length <= 500
s consists of only lowercase English letters and/or digits. | โ Python3 | Faster Solution | Easiest | brute force | 184 | second-largest-digit-in-a-string | 0.491 | Anilchouhan181 | Easy | 25,711 | 1,796 |
maximum number of consecutive values you can make | class Solution:
def getMaximumConsecutive(self, coins: List[int]) -> int:
coins.sort()
res = 1
for coin in coins:
if (res >= coin):
res += coin
return res | https://leetcode.com/problems/maximum-number-of-consecutive-values-you-can-make/discuss/1153726/Python3-Simple-Solution | 1 | You are given an integer array coins of length n which represents the n coins that you own. The value of the ith coin is coins[i]. You can make some value x if you can choose some of your n coins such that their values sum up to x.
Return the maximum number of consecutive integer values that you can make with your coins starting from and including 0.
Note that you may have multiple coins of the same value.
Example 1:
Input: coins = [1,3]
Output: 2
Explanation: You can make the following values:
- 0: take []
- 1: take [1]
You can make 2 consecutive integer values starting from 0.
Example 2:
Input: coins = [1,1,1,4]
Output: 8
Explanation: You can make the following values:
- 0: take []
- 1: take [1]
- 2: take [1,1]
- 3: take [1,1,1]
- 4: take [4]
- 5: take [4,1]
- 6: take [4,1,1]
- 7: take [4,1,1,1]
You can make 8 consecutive integer values starting from 0.
Example 3:
Input: nums = [1,4,10,3,1]
Output: 20
Constraints:
coins.length == n
1 <= n <= 4 * 104
1 <= coins[i] <= 4 * 104 | Python3 Simple Solution | 154 | maximum-number-of-consecutive-values-you-can-make | 0.545 | victor72 | Medium | 25,744 | 1,798 |
maximize score after n operations | class Solution:
def maxScore(self, nums: List[int]) -> int:
@cache
def fn(nums, k):
"""Return max score from nums at kth step."""
if not nums: return 0 # boundary condition
ans = 0
for i in range(len(nums)):
for j in range(i+1, len(nums)):
rest = nums[:i] + nums[i+1:j] + nums[j+1:]
ans = max(ans, k*gcd(nums[i], nums[j]) + fn(tuple(rest), k+1))
return ans
return fn(tuple(nums), 1) | https://leetcode.com/problems/maximize-score-after-n-operations/discuss/1118782/Python3-dp | 17 | You are given nums, an array of positive integers of size 2 * n. You must perform n operations on this array.
In the ith operation (1-indexed), you will:
Choose two elements, x and y.
Receive a score of i * gcd(x, y).
Remove x and y from nums.
Return the maximum score you can receive after performing n operations.
The function gcd(x, y) is the greatest common divisor of x and y.
Example 1:
Input: nums = [1,2]
Output: 1
Explanation: The optimal choice of operations is:
(1 * gcd(1, 2)) = 1
Example 2:
Input: nums = [3,4,6,8]
Output: 11
Explanation: The optimal choice of operations is:
(1 * gcd(3, 6)) + (2 * gcd(4, 8)) = 3 + 8 = 11
Example 3:
Input: nums = [1,2,3,4,5,6]
Output: 14
Explanation: The optimal choice of operations is:
(1 * gcd(1, 5)) + (2 * gcd(2, 4)) + (3 * gcd(3, 6)) = 1 + 4 + 9 = 14
Constraints:
1 <= n <= 7
nums.length == 2 * n
1 <= nums[i] <= 106 | [Python3] dp | 1,500 | maximize-score-after-n-operations | 0.458 | ye15 | Hard | 25,747 | 1,799 |
maximum ascending subarray sum | class Solution:
def maxAscendingSum(self, nums: List[int]) -> int:
ans = 0
for i, x in enumerate(nums):
if not i or nums[i-1] >= nums[i]: val = 0 # reset val
val += nums[i]
ans = max(ans, val)
return ans | https://leetcode.com/problems/maximum-ascending-subarray-sum/discuss/1119686/Python3-line-sweep | 6 | Given an array of positive integers nums, return the maximum possible sum of an ascending subarray in nums.
A subarray is defined as a contiguous sequence of numbers in an array.
A subarray [numsl, numsl+1, ..., numsr-1, numsr] is ascending if for all i where l <= i < r, numsi < numsi+1. Note that a subarray of size 1 is ascending.
Example 1:
Input: nums = [10,20,30,5,10,50]
Output: 65
Explanation: [5,10,50] is the ascending subarray with the maximum sum of 65.
Example 2:
Input: nums = [10,20,30,40,50]
Output: 150
Explanation: [10,20,30,40,50] is the ascending subarray with the maximum sum of 150.
Example 3:
Input: nums = [12,17,15,13,10,11,12]
Output: 33
Explanation: [10,11,12] is the ascending subarray with the maximum sum of 33.
Constraints:
1 <= nums.length <= 100
1 <= nums[i] <= 100 | [Python3] line sweep | 617 | maximum-ascending-subarray-sum | 0.637 | ye15 | Easy | 25,751 | 1,800 |
number of orders in the backlog | class Solution:
def getNumberOfBacklogOrders(self, orders: List[List[int]]) -> int:
ans = 0
buy, sell = [], [] # max-heap & min-heap
for p, q, t in orders:
ans += q
if t: # sell order
while q and buy and -buy[0][0] >= p: # match
pb, qb = heappop(buy)
ans -= 2*min(q, qb)
if q < qb:
heappush(buy, (pb, qb-q))
q = 0
else: q -= qb
if q: heappush(sell, (p, q))
else: # buy order
while q and sell and sell[0][0] <= p: # match
ps, qs = heappop(sell)
ans -= 2*min(q, qs)
if q < qs:
heappush(sell, (ps, qs-q))
q = 0
else: q -= qs
if q: heappush(buy, (-p, q))
return ans % 1_000_000_007 | https://leetcode.com/problems/number-of-orders-in-the-backlog/discuss/1119692/Python3-priority-queue | 6 | You are given a 2D integer array orders, where each orders[i] = [pricei, amounti, orderTypei] denotes that amounti orders have been placed of type orderTypei at the price pricei. The orderTypei is:
0 if it is a batch of buy orders, or
1 if it is a batch of sell orders.
Note that orders[i] represents a batch of amounti independent orders with the same price and order type. All orders represented by orders[i] will be placed before all orders represented by orders[i+1] for all valid i.
There is a backlog that consists of orders that have not been executed. The backlog is initially empty. When an order is placed, the following happens:
If the order is a buy order, you look at the sell order with the smallest price in the backlog. If that sell order's price is smaller than or equal to the current buy order's price, they will match and be executed, and that sell order will be removed from the backlog. Else, the buy order is added to the backlog.
Vice versa, if the order is a sell order, you look at the buy order with the largest price in the backlog. If that buy order's price is larger than or equal to the current sell order's price, they will match and be executed, and that buy order will be removed from the backlog. Else, the sell order is added to the backlog.
Return the total amount of orders in the backlog after placing all the orders from the input. Since this number can be large, return it modulo 109 + 7.
Example 1:
Input: orders = [[10,5,0],[15,2,1],[25,1,1],[30,4,0]]
Output: 6
Explanation: Here is what happens with the orders:
- 5 orders of type buy with price 10 are placed. There are no sell orders, so the 5 orders are added to the backlog.
- 2 orders of type sell with price 15 are placed. There are no buy orders with prices larger than or equal to 15, so the 2 orders are added to the backlog.
- 1 order of type sell with price 25 is placed. There are no buy orders with prices larger than or equal to 25 in the backlog, so this order is added to the backlog.
- 4 orders of type buy with price 30 are placed. The first 2 orders are matched with the 2 sell orders of the least price, which is 15 and these 2 sell orders are removed from the backlog. The 3rd order is matched with the sell order of the least price, which is 25 and this sell order is removed from the backlog. Then, there are no more sell orders in the backlog, so the 4th order is added to the backlog.
Finally, the backlog has 5 buy orders with price 10, and 1 buy order with price 30. So the total number of orders in the backlog is 6.
Example 2:
Input: orders = [[7,1000000000,1],[15,3,0],[5,999999995,0],[5,1,1]]
Output: 999999984
Explanation: Here is what happens with the orders:
- 109 orders of type sell with price 7 are placed. There are no buy orders, so the 109 orders are added to the backlog.
- 3 orders of type buy with price 15 are placed. They are matched with the 3 sell orders with the least price which is 7, and those 3 sell orders are removed from the backlog.
- 999999995 orders of type buy with price 5 are placed. The least price of a sell order is 7, so the 999999995 orders are added to the backlog.
- 1 order of type sell with price 5 is placed. It is matched with the buy order of the highest price, which is 5, and that buy order is removed from the backlog.
Finally, the backlog has (1000000000-3) sell orders with price 7, and (999999995-1) buy orders with price 5. So the total number of orders = 1999999991, which is equal to 999999984 % (109 + 7).
Constraints:
1 <= orders.length <= 105
orders[i].length == 3
1 <= pricei, amounti <= 109
orderTypei is either 0 or 1. | [Python3] priority queue | 596 | number-of-orders-in-the-backlog | 0.474 | ye15 | Medium | 25,778 | 1,801 |
maximum value at a given index in a bounded array | class Solution:
def maxValue(self, n: int, index: int, maxSum: int) -> int:
res_i, crr_sum = 0, n
l, r, w_hill = index + 1, index - 1, 1 # left/right indices and width of the hill
while crr_sum <= maxSum:
l -= 1
r += 1
if l == index and r == index:
crr_sum += w_hill
else:
l_, r_ = max(l, 0), min(r, n - 1)
'''
when the hill has the same width as the ground,
simply just speed up growing by adding the result
of dividing (maxSum - crr_sum) by w_hill
'''
if l < l_ and r > r_:
rm = maxSum - crr_sum
res_i += int(rm / w_hill) + 1
break
else:
w_hill = r_ - l_ + 1
crr_sum += w_hill
res_i += 1
return res_i | https://leetcode.com/problems/maximum-value-at-a-given-index-in-a-bounded-array/discuss/1119650/Growing-A-HillPyramid-with-Visualization-in-Python3 | 5 | You are given three positive integers: n, index, and maxSum. You want to construct an array nums (0-indexed) that satisfies the following conditions:
nums.length == n
nums[i] is a positive integer where 0 <= i < n.
abs(nums[i] - nums[i+1]) <= 1 where 0 <= i < n-1.
The sum of all the elements of nums does not exceed maxSum.
nums[index] is maximized.
Return nums[index] of the constructed array.
Note that abs(x) equals x if x >= 0, and -x otherwise.
Example 1:
Input: n = 4, index = 2, maxSum = 6
Output: 2
Explanation: nums = [1,2,2,1] is one array that satisfies all the conditions.
There are no arrays that satisfy all the conditions and have nums[2] == 3, so 2 is the maximum nums[2].
Example 2:
Input: n = 6, index = 1, maxSum = 10
Output: 3
Constraints:
1 <= n <= maxSum <= 109
0 <= index < n | Growing A [Hill/Pyramid] with Visualization in [Python3] | 396 | maximum-value-at-a-given-index-in-a-bounded-array | 0.319 | BryanBoCao | Medium | 25,784 | 1,802 |
number of different integers in a string | class Solution:
def numDifferentIntegers(self, word: str) -> int:
word = re.findall('(\d+)', word)
numbers = [int(i) for i in word]
return len(set(numbers)) | https://leetcode.com/problems/number-of-different-integers-in-a-string/discuss/1491046/Python-3-Short-and-easy-to-understand | 5 | You are given a string word that consists of digits and lowercase English letters.
You will replace every non-digit character with a space. For example, "a123bc34d8ef34" will become " 123 34 8 34". Notice that you are left with some integers that are separated by at least one space: "123", "34", "8", and "34".
Return the number of different integers after performing the replacement operations on word.
Two integers are considered different if their decimal representations without any leading zeros are different.
Example 1:
Input: word = "a123bc34d8ef34"
Output: 3
Explanation: The three different integers are "123", "34", and "8". Notice that "34" is only counted once.
Example 2:
Input: word = "leet1234code234"
Output: 2
Example 3:
Input: word = "a1b01c001"
Output: 1
Explanation: The three integers "1", "01", and "001" all represent the same integer because
the leading zeros are ignored when comparing their decimal values.
Constraints:
1 <= word.length <= 1000
word consists of digits and lowercase English letters. | Python 3 Short and easy to understand | 313 | number-of-different-integers-in-a-string | 0.362 | frolovdmn | Easy | 25,788 | 1,805 |
minimum number of operations to reinitialize a permutation | class Solution:
def reinitializePermutation(self, n: int) -> int:
ans = 0
perm = list(range(n))
while True:
ans += 1
perm = [perm[n//2+(i-1)//2] if i&1 else perm[i//2] for i in range(n)]
if all(perm[i] == i for i in range(n)): return ans | https://leetcode.com/problems/minimum-number-of-operations-to-reinitialize-a-permutation/discuss/1130760/Python3-simulation | 4 | You are given an even integer n. You initially have a permutation perm of size n where perm[i] == i (0-indexed).
In one operation, you will create a new array arr, and for each i:
If i % 2 == 0, then arr[i] = perm[i / 2].
If i % 2 == 1, then arr[i] = perm[n / 2 + (i - 1) / 2].
You will then assign arr to perm.
Return the minimum non-zero number of operations you need to perform on perm to return the permutation to its initial value.
Example 1:
Input: n = 2
Output: 1
Explanation: perm = [0,1] initially.
After the 1st operation, perm = [0,1]
So it takes only 1 operation.
Example 2:
Input: n = 4
Output: 2
Explanation: perm = [0,1,2,3] initially.
After the 1st operation, perm = [0,2,1,3]
After the 2nd operation, perm = [0,1,2,3]
So it takes only 2 operations.
Example 3:
Input: n = 6
Output: 4
Constraints:
2 <= n <= 1000
n is even. | [Python3] simulation | 217 | minimum-number-of-operations-to-reinitialize-a-permutation | 0.714 | ye15 | Medium | 25,827 | 1,806 |
evaluate the bracket pairs of a string | class Solution:
def evaluate(self, s: str, knowledge: List[List[str]]) -> str:
knowledge = dict(knowledge)
answer, start = [], None
for i, char in enumerate(s):
if char == '(':
start = i + 1
elif char == ')':
answer.append(knowledge.get(s[start:i], '?'))
start = None
elif start is None:
answer.append(char)
return ''.join(answer) | https://leetcode.com/problems/evaluate-the-bracket-pairs-of-a-string/discuss/1286887/Python-or-Dictionary-or-Simple-Solution | 2 | You are given a string s that contains some bracket pairs, with each pair containing a non-empty key.
For example, in the string "(name)is(age)yearsold", there are two bracket pairs that contain the keys "name" and "age".
You know the values of a wide range of keys. This is represented by a 2D string array knowledge where each knowledge[i] = [keyi, valuei] indicates that key keyi has a value of valuei.
You are tasked to evaluate all of the bracket pairs. When you evaluate a bracket pair that contains some key keyi, you will:
Replace keyi and the bracket pair with the key's corresponding valuei.
If you do not know the value of the key, you will replace keyi and the bracket pair with a question mark "?" (without the quotation marks).
Each key will appear at most once in your knowledge. There will not be any nested brackets in s.
Return the resulting string after evaluating all of the bracket pairs.
Example 1:
Input: s = "(name)is(age)yearsold", knowledge = [["name","bob"],["age","two"]]
Output: "bobistwoyearsold"
Explanation:
The key "name" has a value of "bob", so replace "(name)" with "bob".
The key "age" has a value of "two", so replace "(age)" with "two".
Example 2:
Input: s = "hi(name)", knowledge = [["a","b"]]
Output: "hi?"
Explanation: As you do not know the value of the key "name", replace "(name)" with "?".
Example 3:
Input: s = "(a)(a)(a)aaa", knowledge = [["a","yes"]]
Output: "yesyesyesaaa"
Explanation: The same key can appear multiple times.
The key "a" has a value of "yes", so replace all occurrences of "(a)" with "yes".
Notice that the "a"s not in a bracket pair are not evaluated.
Constraints:
1 <= s.length <= 105
0 <= knowledge.length <= 105
knowledge[i].length == 2
1 <= keyi.length, valuei.length <= 10
s consists of lowercase English letters and round brackets '(' and ')'.
Every open bracket '(' in s will have a corresponding close bracket ')'.
The key in each bracket pair of s will be non-empty.
There will not be any nested bracket pairs in s.
keyi and valuei consist of lowercase English letters.
Each keyi in knowledge is unique. | Python | Dictionary | Simple Solution | 102 | evaluate-the-bracket-pairs-of-a-string | 0.667 | leeteatsleep | Medium | 25,831 | 1,807 |
maximize number of nice divisors | class Solution:
def maxNiceDivisors(self, primeFactors: int) -> int:
mod = 1_000_000_007
if primeFactors % 3 == 0: return pow(3, primeFactors//3, mod)
if primeFactors % 3 == 1: return 1 if primeFactors == 1 else 4*pow(3, (primeFactors-4)//3, mod) % mod
return 2*pow(3, primeFactors//3, mod) % mod | https://leetcode.com/problems/maximize-number-of-nice-divisors/discuss/1130780/Python3-math | 2 | You are given a positive integer primeFactors. You are asked to construct a positive integer n that satisfies the following conditions:
The number of prime factors of n (not necessarily distinct) is at most primeFactors.
The number of nice divisors of n is maximized. Note that a divisor of n is nice if it is divisible by every prime factor of n. For example, if n = 12, then its prime factors are [2,2,3], then 6 and 12 are nice divisors, while 3 and 4 are not.
Return the number of nice divisors of n. Since that number can be too large, return it modulo 109 + 7.
Note that a prime number is a natural number greater than 1 that is not a product of two smaller natural numbers. The prime factors of a number n is a list of prime numbers such that their product equals n.
Example 1:
Input: primeFactors = 5
Output: 6
Explanation: 200 is a valid value of n.
It has 5 prime factors: [2,2,2,5,5], and it has 6 nice divisors: [10,20,40,50,100,200].
There is not other value of n that has at most 5 prime factors and more nice divisors.
Example 2:
Input: primeFactors = 8
Output: 18
Constraints:
1 <= primeFactors <= 109 | [Python3] math | 74 | maximize-number-of-nice-divisors | 0.313 | ye15 | Hard | 25,846 | 1,808 |
determine color of a chessboard square | class Solution:
def squareIsWhite(self, c: str) -> bool:
if c[0] in 'aceg':
return int(c[1])%2==0
elif c[0] in 'bdfh':
return int(c[1])%2==1
return False | https://leetcode.com/problems/determine-color-of-a-chessboard-square/discuss/1140948/PythonPython3-or-Simple-and-Easy-code-or-self-explanatory | 12 | You are given coordinates, a string that represents the coordinates of a square of the chessboard. Below is a chessboard for your reference.
Return true if the square is white, and false if the square is black.
The coordinate will always represent a valid chessboard square. The coordinate will always have the letter first, and the number second.
Example 1:
Input: coordinates = "a1"
Output: false
Explanation: From the chessboard above, the square with coordinates "a1" is black, so return false.
Example 2:
Input: coordinates = "h3"
Output: true
Explanation: From the chessboard above, the square with coordinates "h3" is white, so return true.
Example 3:
Input: coordinates = "c7"
Output: false
Constraints:
coordinates.length == 2
'a' <= coordinates[0] <= 'h'
'1' <= coordinates[1] <= '8' | [Python/Python3 | Simple and Easy code | self-explanatory | 513 | determine-color-of-a-chessboard-square | 0.774 | Sukhdev_143 | Easy | 25,847 | 1,812 |
sentence similarity iii | class Solution:
def areSentencesSimilar(self, sentence1: str, sentence2: str) -> bool:
if len(sentence2)>len(sentence1):
return self.areSentencesSimilar(sentence2,sentence1)
sentence1=sentence1.split(" ")
sentence2=sentence2.split(" ")
s1=sentence1[:]
s2=sentence2[:]
while s1[0]==s2[0]:
s1.pop(0)
s2.pop(0)
if not s2:
return True
if not s2:
return True
while s1[-1]==s2[-1]:
s1.pop()
s2.pop()
if not s2:
return True
if not s2:
return True
return False | https://leetcode.com/problems/sentence-similarity-iii/discuss/1461165/PYTHON3-Easy-Peezy-code-using-Stack-crisp-and-clear | 2 | A sentence is a list of words that are separated by a single space with no leading or trailing spaces. For example, "Hello World", "HELLO", "hello world hello world" are all sentences. Words consist of only uppercase and lowercase English letters.
Two sentences sentence1 and sentence2 are similar if it is possible to insert an arbitrary sentence (possibly empty) inside one of these sentences such that the two sentences become equal. For example, sentence1 = "Hello my name is Jane" and sentence2 = "Hello Jane" can be made equal by inserting "my name is" between "Hello" and "Jane" in sentence2.
Given two sentences sentence1 and sentence2, return true if sentence1 and sentence2 are similar. Otherwise, return false.
Example 1:
Input: sentence1 = "My name is Haley", sentence2 = "My Haley"
Output: true
Explanation: sentence2 can be turned to sentence1 by inserting "name is" between "My" and "Haley".
Example 2:
Input: sentence1 = "of", sentence2 = "A lot of words"
Output: false
Explanation: No single sentence can be inserted inside one of the sentences to make it equal to the other.
Example 3:
Input: sentence1 = "Eating right now", sentence2 = "Eating"
Output: true
Explanation: sentence2 can be turned to sentence1 by inserting "right now" at the end of the sentence.
Constraints:
1 <= sentence1.length, sentence2.length <= 100
sentence1 and sentence2 consist of lowercase and uppercase English letters and spaces.
The words in sentence1 and sentence2 are separated by a single space. | PYTHON3 Easy Peezy code using Stack crisp and clear | 102 | sentence-similarity-iii | 0.331 | mathur17021play | Medium | 25,887 | 1,813 |
count nice pairs in an array | class Solution:
def countNicePairs(self, nums: List[int]) -> int:
# define constants
n = len(nums)
MOD = 10**9 + 7
# handle scenario for no pairs
if n<=1:
return 0
# utility method to calculate reverse of a number
# e.g. rev(123) -> 321
def rev(i):
new = 0
while(i!=0):
r = i%10
new = new*10+r
i = i//10
return new
# calculate frequency of all the diffs
freq_counter = defaultdict(int)
for num in nums:
freq_counter[num-rev(num)] += 1
# for all the frequencies calculate the number of paris
# which is basically nC2 (read as - "n choose 2") -> n*(n-1)/2
answer = 0
for freq in freq_counter.keys():
count = freq_counter[freq]
# note the modulo operation being performed to handle large answer
answer = (answer + (count*(count-1))//2)%MOD
return answer | https://leetcode.com/problems/count-nice-pairs-in-an-array/discuss/1140577/Accepted-Python-simple-and-easy-to-understand-solution-with-comments | 5 | You are given an array nums that consists of non-negative integers. Let us define rev(x) as the reverse of the non-negative integer x. For example, rev(123) = 321, and rev(120) = 21. A pair of indices (i, j) is nice if it satisfies all of the following conditions:
0 <= i < j < nums.length
nums[i] + rev(nums[j]) == nums[j] + rev(nums[i])
Return the number of nice pairs of indices. Since that number can be too large, return it modulo 109 + 7.
Example 1:
Input: nums = [42,11,1,97]
Output: 2
Explanation: The two pairs are:
- (0,3) : 42 + rev(97) = 42 + 79 = 121, 97 + rev(42) = 97 + 24 = 121.
- (1,2) : 11 + rev(1) = 11 + 1 = 12, 1 + rev(11) = 1 + 11 = 12.
Example 2:
Input: nums = [13,10,35,24,76]
Output: 4
Constraints:
1 <= nums.length <= 105
0 <= nums[i] <= 109 | [Accepted] Python simple and easy to understand solution with comments | 502 | count-nice-pairs-in-an-array | 0.42 | CaptainX | Medium | 25,894 | 1,814 |
maximum number of groups getting fresh donuts | class Solution:
def maxHappyGroups(self, bs: int, gs: List[int]) -> int:
c = {i: 0 for i in range(bs)}
for g in gs:
c[g % bs] += 1
ret = c[0]
c[0] = 0
def get_keys(num):
keys = []
def rec(stack):
if len(stack) == num:
if sum(stack) % bs == 0:
keys.append(Counter(stack))
else:
for i in range(stack[-1] if stack else bs - 1, - 1, - 1):
stack.append(i)
rec(stack)
stack.pop()
rec([])
return keys
def get_diff_keys(num):
keys = []
def rec(stack):
if len(stack) == num:
if sum(stack) % bs == 0:
keys.append(Counter(stack))
else:
for i in range(stack[-1] - 1 if stack else bs - 1, - 1, - 1):
stack.append(i)
rec(stack)
stack.pop()
rec([])
return keys
for tc in range(2, bs):
for keys in get_diff_keys(tc):
add = min(c[key] // keys[key] for key in keys)
if add == 0: continue
ret += add
for key in keys:
c[key] -= add * keys[key]
tc = 2
while True:
for keys in get_keys(tc):
add = min(c[key] // keys[key] for key in keys)
if add == 0: continue
ret += add
for key in keys:
c[key] -= add * keys[key]
if tc > sum(c.values()): break
tc += 1
return ret + bool(sum(c.values()))
``` | https://leetcode.com/problems/maximum-number-of-groups-getting-fresh-donuts/discuss/1140716/Python3-Fastest-solution-with-explanation | 0 | There is a donuts shop that bakes donuts in batches of batchSize. They have a rule where they must serve all of the donuts of a batch before serving any donuts of the next batch. You are given an integer batchSize and an integer array groups, where groups[i] denotes that there is a group of groups[i] customers that will visit the shop. Each customer will get exactly one donut.
When a group visits the shop, all customers of the group must be served before serving any of the following groups. A group will be happy if they all get fresh donuts. That is, the first customer of the group does not receive a donut that was left over from the previous group.
You can freely rearrange the ordering of the groups. Return the maximum possible number of happy groups after rearranging the groups.
Example 1:
Input: batchSize = 3, groups = [1,2,3,4,5,6]
Output: 4
Explanation: You can arrange the groups as [6,2,4,5,1,3]. Then the 1st, 2nd, 4th, and 6th groups will be happy.
Example 2:
Input: batchSize = 4, groups = [1,3,2,5,2,2,1,6]
Output: 4
Constraints:
1 <= batchSize <= 9
1 <= groups.length <= 30
1 <= groups[i] <= 109 | [Python3] Fastest solution with explanation | 102 | maximum-number-of-groups-getting-fresh-donuts | 0.402 | timetoai | Hard | 25,900 | 1,815 |
truncate sentence | class Solution:
def truncateSentence(self, s: str, k: int) -> str:
words = s.split(" ")
return " ".join(words[0:k]) | https://leetcode.com/problems/truncate-sentence/discuss/1142293/2-lines-of-code-with-100-less-space-used | 15 | A sentence is a list of words that are separated by a single space with no leading or trailing spaces. Each of the words consists of only uppercase and lowercase English letters (no punctuation).
For example, "Hello World", "HELLO", and "hello world hello world" are all sentences.
You are given a sentence s and an integer k. You want to truncate s such that it contains only the first k words. Return s after truncating it.
Example 1:
Input: s = "Hello how are you Contestant", k = 4
Output: "Hello how are you"
Explanation:
The words in s are ["Hello", "how" "are", "you", "Contestant"].
The first 4 words are ["Hello", "how", "are", "you"].
Hence, you should return "Hello how are you".
Example 2:
Input: s = "What is the solution to this problem", k = 4
Output: "What is the solution"
Explanation:
The words in s are ["What", "is" "the", "solution", "to", "this", "problem"].
The first 4 words are ["What", "is", "the", "solution"].
Hence, you should return "What is the solution".
Example 3:
Input: s = "chopper is not a tanuki", k = 5
Output: "chopper is not a tanuki"
Constraints:
1 <= s.length <= 500
k is in the range [1, the number of words in s].
s consist of only lowercase and uppercase English letters and spaces.
The words in s are separated by a single space.
There are no leading or trailing spaces. | 2 lines of code with 100% less space used | 1,000 | truncate-sentence | 0.821 | vashisht7 | Easy | 25,901 | 1,816 |
finding the users active minutes | class Solution:
def findingUsersActiveMinutes(self, logs: List[List[int]], k: int) -> List[int]:
mp = {}
for i, t in logs:
mp.setdefault(i, set()).add(t)
ans = [0]*k
for v in mp.values():
if len(v) <= k:
ans[len(v)-1] += 1
return ans | https://leetcode.com/problems/finding-the-users-active-minutes/discuss/1141356/Python3-hash-map | 9 | You are given the logs for users' actions on LeetCode, and an integer k. The logs are represented by a 2D integer array logs where each logs[i] = [IDi, timei] indicates that the user with IDi performed an action at the minute timei.
Multiple users can perform actions simultaneously, and a single user can perform multiple actions in the same minute.
The user active minutes (UAM) for a given user is defined as the number of unique minutes in which the user performed an action on LeetCode. A minute can only be counted once, even if multiple actions occur during it.
You are to calculate a 1-indexed array answer of size k such that, for each j (1 <= j <= k), answer[j] is the number of users whose UAM equals j.
Return the array answer as described above.
Example 1:
Input: logs = [[0,5],[1,2],[0,2],[0,5],[1,3]], k = 5
Output: [0,2,0,0,0]
Explanation:
The user with ID=0 performed actions at minutes 5, 2, and 5 again. Hence, they have a UAM of 2 (minute 5 is only counted once).
The user with ID=1 performed actions at minutes 2 and 3. Hence, they have a UAM of 2.
Since both users have a UAM of 2, answer[2] is 2, and the remaining answer[j] values are 0.
Example 2:
Input: logs = [[1,1],[2,2],[2,3]], k = 4
Output: [1,1,0,0]
Explanation:
The user with ID=1 performed a single action at minute 1. Hence, they have a UAM of 1.
The user with ID=2 performed actions at minutes 2 and 3. Hence, they have a UAM of 2.
There is one user with a UAM of 1 and one with a UAM of 2.
Hence, answer[1] = 1, answer[2] = 1, and the remaining values are 0.
Constraints:
1 <= logs.length <= 104
0 <= IDi <= 109
1 <= timei <= 105
k is in the range [The maximum UAM for a user, 105]. | [Python3] hash map | 597 | finding-the-users-active-minutes | 0.807 | ye15 | Medium | 25,949 | 1,817 |
minimum absolute sum difference | class Solution:
def minAbsoluteSumDiff(self, nums1: List[int], nums2: List[int]) -> int:
n = len(nums1)
diff = []
sum = 0
for i in range(n):
temp = abs(nums1[i]-nums2[i])
diff.append(temp)
sum += temp
nums1.sort()
best_diff = []
for i in range(n):
idx = bisect.bisect_left(nums1, nums2[i])
if idx != 0 and idx != n:
best_diff.append(
min(abs(nums2[i]-nums1[idx]), abs(nums2[i]-nums1[idx-1])))
elif idx == 0:
best_diff.append(abs(nums2[i]-nums1[idx]))
else:
best_diff.append(abs(nums2[i]-nums1[idx-1]))
saved = 0
for i in range(n):
saved = max(saved, diff[i]-best_diff[i])
return (sum-saved) % ((10**9)+(7)) | https://leetcode.com/problems/minimum-absolute-sum-difference/discuss/1715575/Python-%2B-Fully-Explained-%2B-Best-Solution | 10 | You are given two positive integer arrays nums1 and nums2, both of length n.
The absolute sum difference of arrays nums1 and nums2 is defined as the sum of |nums1[i] - nums2[i]| for each 0 <= i < n (0-indexed).
You can replace at most one element of nums1 with any other element in nums1 to minimize the absolute sum difference.
Return the minimum absolute sum difference after replacing at most one element in the array nums1. Since the answer may be large, return it modulo 109 + 7.
|x| is defined as:
x if x >= 0, or
-x if x < 0.
Example 1:
Input: nums1 = [1,7,5], nums2 = [2,3,5]
Output: 3
Explanation: There are two possible optimal solutions:
- Replace the second element with the first: [1,7,5] => [1,1,5], or
- Replace the second element with the third: [1,7,5] => [1,5,5].
Both will yield an absolute sum difference of |1-2| + (|1-3| or |5-3|) + |5-5| = 3.
Example 2:
Input: nums1 = [2,4,6,8,10], nums2 = [2,4,6,8,10]
Output: 0
Explanation: nums1 is equal to nums2 so no replacement is needed. This will result in an
absolute sum difference of 0.
Example 3:
Input: nums1 = [1,10,4,4,2,7], nums2 = [9,3,5,1,7,4]
Output: 20
Explanation: Replace the first element with the second: [1,10,4,4,2,7] => [10,10,4,4,2,7].
This yields an absolute sum difference of |10-9| + |10-3| + |4-5| + |4-1| + |2-7| + |7-4| = 20
Constraints:
n == nums1.length
n == nums2.length
1 <= n <= 105
1 <= nums1[i], nums2[i] <= 105 | [Python] + Fully Explained + Best Solution โ | 540 | minimum-absolute-sum-difference | 0.302 | leet_satyam | Medium | 25,970 | 1,818 |
number of different subsequences gcds | class Solution:
def countDifferentSubsequenceGCDs(self, nums: List[int]) -> int:
nums = set(nums)
ans = 0
m = max(nums)
for x in range(1, m+1):
g = 0
for xx in range(x, m+1, x):
if xx in nums:
g = gcd(g, xx)
if g == x: ans += 1
return ans | https://leetcode.com/problems/number-of-different-subsequences-gcds/discuss/1144445/Python3-enumerate-all-possibilities | 4 | You are given an array nums that consists of positive integers.
The GCD of a sequence of numbers is defined as the greatest integer that divides all the numbers in the sequence evenly.
For example, the GCD of the sequence [4,6,16] is 2.
A subsequence of an array is a sequence that can be formed by removing some elements (possibly none) of the array.
For example, [2,5,10] is a subsequence of [1,2,1,2,4,1,5,10].
Return the number of different GCDs among all non-empty subsequences of nums.
Example 1:
Input: nums = [6,10,3]
Output: 5
Explanation: The figure shows all the non-empty subsequences and their GCDs.
The different GCDs are 6, 10, 3, 2, and 1.
Example 2:
Input: nums = [5,15,40,5,6]
Output: 7
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 2 * 105 | [Python3] enumerate all possibilities | 234 | number-of-different-subsequences-gcds | 0.385 | ye15 | Hard | 25,978 | 1,819 |
sign of the product of an array | class Solution:
def arraySign(self, nums: List[int]) -> int:
ans = 1
for x in nums:
if x == 0: return 0
if x < 0: ans *= -1
return ans | https://leetcode.com/problems/sign-of-the-product-of-an-array/discuss/1152412/Python3-line-sweep | 58 | There is a function signFunc(x) that returns:
1 if x is positive.
-1 if x is negative.
0 if x is equal to 0.
You are given an integer array nums. Let product be the product of all values in the array nums.
Return signFunc(product).
Example 1:
Input: nums = [-1,-2,-3,-4,3,2,1]
Output: 1
Explanation: The product of all values in the array is 144, and signFunc(144) = 1
Example 2:
Input: nums = [1,5,0,2,-3]
Output: 0
Explanation: The product of all values in the array is 0, and signFunc(0) = 0
Example 3:
Input: nums = [-1,1,-1,1,-1]
Output: -1
Explanation: The product of all values in the array is -1, and signFunc(-1) = -1
Constraints:
1 <= nums.length <= 1000
-100 <= nums[i] <= 100 | [Python3] line sweep | 6,300 | sign-of-the-product-of-an-array | 0.66 | ye15 | Easy | 25,979 | 1,822 |
find the winner of the circular game | class Solution:
def findTheWinner(self, n: int, k: int) -> int:
nums = list(range(n))
i = 0
while len(nums) > 1:
i = (i + k-1) % len(nums)
nums.pop(i)
return nums[0] + 1 | https://leetcode.com/problems/find-the-winner-of-the-circular-game/discuss/1152420/Python3-simulation | 16 | There are n friends that are playing a game. The friends are sitting in a circle and are numbered from 1 to n in clockwise order. More formally, moving clockwise from the ith friend brings you to the (i+1)th friend for 1 <= i < n, and moving clockwise from the nth friend brings you to the 1st friend.
The rules of the game are as follows:
Start at the 1st friend.
Count the next k friends in the clockwise direction including the friend you started at. The counting wraps around the circle and may count some friends more than once.
The last friend you counted leaves the circle and loses the game.
If there is still more than one friend in the circle, go back to step 2 starting from the friend immediately clockwise of the friend who just lost and repeat.
Else, the last friend in the circle wins the game.
Given the number of friends, n, and an integer k, return the winner of the game.
Example 1:
Input: n = 5, k = 2
Output: 3
Explanation: Here are the steps of the game:
1) Start at friend 1.
2) Count 2 friends clockwise, which are friends 1 and 2.
3) Friend 2 leaves the circle. Next start is friend 3.
4) Count 2 friends clockwise, which are friends 3 and 4.
5) Friend 4 leaves the circle. Next start is friend 5.
6) Count 2 friends clockwise, which are friends 5 and 1.
7) Friend 1 leaves the circle. Next start is friend 3.
8) Count 2 friends clockwise, which are friends 3 and 5.
9) Friend 5 leaves the circle. Only friend 3 is left, so they are the winner.
Example 2:
Input: n = 6, k = 5
Output: 1
Explanation: The friends leave in this order: 5, 4, 6, 2, 3. The winner is friend 1.
Constraints:
1 <= k <= n <= 500
Follow up:
Could you solve this problem in linear time with constant space? | [Python3] simulation | 1,900 | find-the-winner-of-the-circular-game | 0.779 | ye15 | Medium | 26,018 | 1,823 |
minimum sideway jumps | class Solution:
def minSideJumps(self, obstacles: List[int]) -> int:
n = len(obstacles)
dp = [[sys.maxsize] * n for _ in range(3)]
dp[0][0]= 1
dp[1][0]= 0
dp[2][0]= 1
for i in range(1, n):
dp[0][i] = dp[0][i-1] if obstacles[i] != 1 else sys.maxsize
dp[1][i] = dp[1][i-1] if obstacles[i] != 2 else sys.maxsize
dp[2][i] = dp[2][i-1] if obstacles[i] != 3 else sys.maxsize
if obstacles[i] != 1:
for j in [1, 2]:
dp[0][i] = min(dp[0][i], dp[j][i] + 1 if obstacles[i] != j+1 else sys.maxsize)
if obstacles[i] != 2:
for j in [0, 2]:
dp[1][i] = min(dp[1][i], dp[j][i] + 1 if obstacles[i] != j+1 else sys.maxsize)
if obstacles[i] != 3:
for j in [0, 1]:
dp[2][i] = min(dp[2][i], dp[j][i] + 1 if obstacles[i] != j+1 else sys.maxsize)
return min(dp[0][-1], dp[1][-1], dp[2][-1]) | https://leetcode.com/problems/minimum-sideway-jumps/discuss/1480131/Python-3-or-DP-or-Explanation | 4 | There is a 3 lane road of length n that consists of n + 1 points labeled from 0 to n. A frog starts at point 0 in the second lane and wants to jump to point n. However, there could be obstacles along the way.
You are given an array obstacles of length n + 1 where each obstacles[i] (ranging from 0 to 3) describes an obstacle on the lane obstacles[i] at point i. If obstacles[i] == 0, there are no obstacles at point i. There will be at most one obstacle in the 3 lanes at each point.
For example, if obstacles[2] == 1, then there is an obstacle on lane 1 at point 2.
The frog can only travel from point i to point i + 1 on the same lane if there is not an obstacle on the lane at point i + 1. To avoid obstacles, the frog can also perform a side jump to jump to another lane (even if they are not adjacent) at the same point if there is no obstacle on the new lane.
For example, the frog can jump from lane 3 at point 3 to lane 1 at point 3.
Return the minimum number of side jumps the frog needs to reach any lane at point n starting from lane 2 at point 0.
Note: There will be no obstacles on points 0 and n.
Example 1:
Input: obstacles = [0,1,2,3,0]
Output: 2
Explanation: The optimal solution is shown by the arrows above. There are 2 side jumps (red arrows).
Note that the frog can jump over obstacles only when making side jumps (as shown at point 2).
Example 2:
Input: obstacles = [0,1,1,3,3,0]
Output: 0
Explanation: There are no obstacles on lane 2. No side jumps are required.
Example 3:
Input: obstacles = [0,2,1,0,3,0]
Output: 2
Explanation: The optimal solution is shown by the arrows above. There are 2 side jumps.
Constraints:
obstacles.length == n + 1
1 <= n <= 5 * 105
0 <= obstacles[i] <= 3
obstacles[0] == obstacles[n] == 0 | Python 3 | DP | Explanation | 539 | minimum-sideway-jumps | 0.495 | idontknoooo | Medium | 26,045 | 1,824 |
minimum operations to make the array increasing | class Solution:
def minOperations(self, nums: List[int]) -> int:
count = 0
for i in range(1,len(nums)):
if nums[i] <= nums[i-1]:
x = nums[i]
nums[i] += (nums[i-1] - nums[i]) + 1
count += nums[i] - x
return count | https://leetcode.com/problems/minimum-operations-to-make-the-array-increasing/discuss/1178397/Python3-simple-solution-beats-90-users | 8 | You are given an integer array nums (0-indexed). In one operation, you can choose an element of the array and increment it by 1.
For example, if nums = [1,2,3], you can choose to increment nums[1] to make nums = [1,3,3].
Return the minimum number of operations needed to make nums strictly increasing.
An array nums is strictly increasing if nums[i] < nums[i+1] for all 0 <= i < nums.length - 1. An array of length 1 is trivially strictly increasing.
Example 1:
Input: nums = [1,1,1]
Output: 3
Explanation: You can do the following operations:
1) Increment nums[2], so nums becomes [1,1,2].
2) Increment nums[1], so nums becomes [1,2,2].
3) Increment nums[2], so nums becomes [1,2,3].
Example 2:
Input: nums = [1,5,2,4,1]
Output: 14
Example 3:
Input: nums = [8]
Output: 0
Constraints:
1 <= nums.length <= 5000
1 <= nums[i] <= 104 | Python3 simple solution beats 90% users | 764 | minimum-operations-to-make-the-array-increasing | 0.782 | EklavyaJoshi | Easy | 26,056 | 1,827 |
queries on number of points inside a circle | class Solution:
def countPoints(self, points: List[List[int]], queries: List[List[int]]) -> List[int]:
return [sum(math.sqrt((x0-x1)**2 + (y0-y1)**2) <= r for x1, y1 in points) for x0, y0, r in queries] | https://leetcode.com/problems/queries-on-number-of-points-inside-a-circle/discuss/1163133/Python-One-liner | 21 | You are given an array points where points[i] = [xi, yi] is the coordinates of the ith point on a 2D plane. Multiple points can have the same coordinates.
You are also given an array queries where queries[j] = [xj, yj, rj] describes a circle centered at (xj, yj) with a radius of rj.
For each query queries[j], compute the number of points inside the jth circle. Points on the border of the circle are considered inside.
Return an array answer, where answer[j] is the answer to the jth query.
Example 1:
Input: points = [[1,3],[3,3],[5,3],[2,2]], queries = [[2,3,1],[4,3,1],[1,1,2]]
Output: [3,2,2]
Explanation: The points and circles are shown above.
queries[0] is the green circle, queries[1] is the red circle, and queries[2] is the blue circle.
Example 2:
Input: points = [[1,1],[2,2],[3,3],[4,4],[5,5]], queries = [[1,2,2],[2,2,2],[4,3,2],[4,3,3]]
Output: [2,3,2,4]
Explanation: The points and circles are shown above.
queries[0] is green, queries[1] is red, queries[2] is blue, and queries[3] is purple.
Constraints:
1 <= points.length <= 500
points[i].length == 2
0 <= xi, yi <= 500
1 <= queries.length <= 500
queries[j].length == 3
0 <= xj, yj <= 500
1 <= rj <= 500
All coordinates are integers.
Follow up: Could you find the answer for each query in better complexity than O(n)? | Python One-liner | 4,000 | queries-on-number-of-points-inside-a-circle | 0.864 | Black_Pegasus | Medium | 26,091 | 1,828 |
maximum xor for each query | class Solution:
def getMaximumXor(self, nums: List[int], maximumBit: int) -> List[int]:
res = []
for i in range(1,len(nums)):
res.append(2**maximumBit - 1 - nums[i-1])
nums[i] = nums[i-1]^nums[i]
res.append(2**maximumBit - 1 - nums[-1])
return res[::-1] | https://leetcode.com/problems/maximum-xor-for-each-query/discuss/1281679/Python3-solution-using-single-for-loop | 3 | You are given a sorted array nums of n non-negative integers and an integer maximumBit. You want to perform the following query n times:
Find a non-negative integer k < 2maximumBit such that nums[0] XOR nums[1] XOR ... XOR nums[nums.length-1] XOR k is maximized. k is the answer to the ith query.
Remove the last element from the current array nums.
Return an array answer, where answer[i] is the answer to the ith query.
Example 1:
Input: nums = [0,1,1,3], maximumBit = 2
Output: [0,3,2,3]
Explanation: The queries are answered as follows:
1st query: nums = [0,1,1,3], k = 0 since 0 XOR 1 XOR 1 XOR 3 XOR 0 = 3.
2nd query: nums = [0,1,1], k = 3 since 0 XOR 1 XOR 1 XOR 3 = 3.
3rd query: nums = [0,1], k = 2 since 0 XOR 1 XOR 2 = 3.
4th query: nums = [0], k = 3 since 0 XOR 3 = 3.
Example 2:
Input: nums = [2,3,4,7], maximumBit = 3
Output: [5,2,6,5]
Explanation: The queries are answered as follows:
1st query: nums = [2,3,4,7], k = 5 since 2 XOR 3 XOR 4 XOR 7 XOR 5 = 7.
2nd query: nums = [2,3,4], k = 2 since 2 XOR 3 XOR 4 XOR 2 = 7.
3rd query: nums = [2,3], k = 6 since 2 XOR 3 XOR 6 = 7.
4th query: nums = [2], k = 5 since 2 XOR 5 = 7.
Example 3:
Input: nums = [0,1,2,2,5,7], maximumBit = 3
Output: [4,3,6,4,6,7]
Constraints:
nums.length == n
1 <= n <= 105
1 <= maximumBit <= 20
0 <= nums[i] < 2maximumBit
nums is sorted in ascending order. | Python3 solution using single for loop | 111 | maximum-xor-for-each-query | 0.769 | EklavyaJoshi | Medium | 26,116 | 1,829 |
minimum number of operations to make string sorted | class Solution:
def makeStringSorted(self, s: str) -> int:
freq = [0]*26
for c in s: freq[ord(c) - 97] += 1
MOD = 1_000_000_007
fac = cache(lambda x: x*fac(x-1)%MOD if x else 1)
ifac = cache(lambda x: pow(fac(x), MOD-2, MOD)) # Fermat's little theorem (a**(p-1) = 1 (mod p))
ans, n = 0, len(s)
for c in s:
val = ord(c) - 97
mult = fac(n-1)
for k in range(26): mult *= ifac(freq[k])
for k in range(val): ans += freq[k] * mult
n -= 1
freq[val] -= 1
return ans % MOD | https://leetcode.com/problems/minimum-number-of-operations-to-make-string-sorted/discuss/1202007/Python3-math-solution | 1 | You are given a string s (0-indexed). You are asked to perform the following operation on s until you get a sorted string:
Find the largest index i such that 1 <= i < s.length and s[i] < s[i - 1].
Find the largest index j such that i <= j < s.length and s[k] < s[i - 1] for all the possible values of k in the range [i, j] inclusive.
Swap the two characters at indices i - 1 and j.
Reverse the suffix starting at index i.
Return the number of operations needed to make the string sorted. Since the answer can be too large, return it modulo 109 + 7.
Example 1:
Input: s = "cba"
Output: 5
Explanation: The simulation goes as follows:
Operation 1: i=2, j=2. Swap s[1] and s[2] to get s="cab", then reverse the suffix starting at 2. Now, s="cab".
Operation 2: i=1, j=2. Swap s[0] and s[2] to get s="bac", then reverse the suffix starting at 1. Now, s="bca".
Operation 3: i=2, j=2. Swap s[1] and s[2] to get s="bac", then reverse the suffix starting at 2. Now, s="bac".
Operation 4: i=1, j=1. Swap s[0] and s[1] to get s="abc", then reverse the suffix starting at 1. Now, s="acb".
Operation 5: i=2, j=2. Swap s[1] and s[2] to get s="abc", then reverse the suffix starting at 2. Now, s="abc".
Example 2:
Input: s = "aabaa"
Output: 2
Explanation: The simulation goes as follows:
Operation 1: i=3, j=4. Swap s[2] and s[4] to get s="aaaab", then reverse the substring starting at 3. Now, s="aaaba".
Operation 2: i=4, j=4. Swap s[3] and s[4] to get s="aaaab", then reverse the substring starting at 4. Now, s="aaaab".
Constraints:
1 <= s.length <= 3000
s consists only of lowercase English letters. | [Python3] math solution | 240 | minimum-number-of-operations-to-make-string-sorted | 0.491 | ye15 | Hard | 26,131 | 1,830 |
check if the sentence is pangram | class Solution:
def checkIfPangram(self, sentence: str) -> bool:
lst=[0]*26
for i in sentence:
lst[ord(i)-ord('a')]+=1
return 0 not in lst | https://leetcode.com/problems/check-if-the-sentence-is-pangram/discuss/2712076/Multiple-solution-in-python | 19 | A pangram is a sentence where every letter of the English alphabet appears at least once.
Given a string sentence containing only lowercase English letters, return true if sentence is a pangram, or false otherwise.
Example 1:
Input: sentence = "thequickbrownfoxjumpsoverthelazydog"
Output: true
Explanation: sentence contains at least one of every letter of the English alphabet.
Example 2:
Input: sentence = "leetcode"
Output: false
Constraints:
1 <= sentence.length <= 1000
sentence consists of lowercase English letters. | Multiple solution in python | 732 | check-if-the-sentence-is-pangram | 0.839 | shubham_1307 | Easy | 26,132 | 1,832 |
maximum ice cream bars | class Solution:
def maxIceCream(self, costs: List[int], coins: int) -> int:
'''
1. If the minimum of all costs is greater than amount of coins, the boy can't buy any bar, return 0
2. Else, sort the list of costs in a non-decreasing order
3. For each 'cost' in costs, if the cost is less than current coins
-increase the count of ice cream bars that can be bought by 1
-decrease the current coins amount by 'cost'
4. If the cost is greater than current coins, return the ice cream bar count value
'''
if min(costs)>coins: #minimum cost is greater than the coins available
return 0 #can't buy any ice cream bar
costs=sorted(costs) #sort the list of costs in a non-decreasing order
res = 0 #the resultant count of ice cream bars that can be bought
for cost in costs:
if cost<=coins: #in this case, the boy can buy the ice cream bar
res+=1 #increase the ice cream bar count
coins-=cost #spent an amount equal to 'cost', decrease current coins amount by cost
else:
break #not enough coins, return the bars count
return res | https://leetcode.com/problems/maximum-ice-cream-bars/discuss/1165500/Python3-with-Explanation-100-faster-and-100-memory-efficient | 3 | It is a sweltering summer day, and a boy wants to buy some ice cream bars.
At the store, there are n ice cream bars. You are given an array costs of length n, where costs[i] is the price of the ith ice cream bar in coins. The boy initially has coins coins to spend, and he wants to buy as many ice cream bars as possible.
Note: The boy can buy the ice cream bars in any order.
Return the maximum number of ice cream bars the boy can buy with coins coins.
You must solve the problem by counting sort.
Example 1:
Input: costs = [1,3,2,4,1], coins = 7
Output: 4
Explanation: The boy can buy ice cream bars at indices 0,1,2,4 for a total price of 1 + 3 + 2 + 1 = 7.
Example 2:
Input: costs = [10,6,8,7,7,8], coins = 5
Output: 0
Explanation: The boy cannot afford any of the ice cream bars.
Example 3:
Input: costs = [1,6,3,1,2,5], coins = 20
Output: 6
Explanation: The boy can buy all the ice cream bars for a total price of 1 + 6 + 3 + 1 + 2 + 5 = 18.
Constraints:
costs.length == n
1 <= n <= 105
1 <= costs[i] <= 105
1 <= coins <= 108 | Python3 with Explanation, 100% faster and 100% memory efficient | 279 | maximum-ice-cream-bars | 0.656 | bPapan | Medium | 26,180 | 1,833 |
single threaded cpu | class Solution:
def getOrder(self, tasks: List[List[int]]) -> List[int]:
dic=defaultdict(list)
for i in range(len(tasks)):
dic[tasks[i][0]].append((tasks[i][1],i))
ans=[]
keys=sorted(dic.keys())
while keys:
k=keys.pop(0)
pq=dic[k]
heapq.heapify(pq)
time=k
while pq:
p_time,ind=heapq.heappop(pq)
ans.append(ind)
time+=p_time
while keys:
if keys[0]>time:
break
for item in dic[keys.pop(0)]:
heapq.heappush(pq,item)
return ans | https://leetcode.com/problems/single-threaded-cpu/discuss/2004757/Python-or-Priority-Queue | 1 | You are given n tasks labeled from 0 to n - 1 represented by a 2D integer array tasks, where tasks[i] = [enqueueTimei, processingTimei] means that the ith task will be available to process at enqueueTimei and will take processingTimei to finish processing.
You have a single-threaded CPU that can process at most one task at a time and will act in the following way:
If the CPU is idle and there are no available tasks to process, the CPU remains idle.
If the CPU is idle and there are available tasks, the CPU will choose the one with the shortest processing time. If multiple tasks have the same shortest processing time, it will choose the task with the smallest index.
Once a task is started, the CPU will process the entire task without stopping.
The CPU can finish a task then start a new one instantly.
Return the order in which the CPU will process the tasks.
Example 1:
Input: tasks = [[1,2],[2,4],[3,2],[4,1]]
Output: [0,2,3,1]
Explanation: The events go as follows:
- At time = 1, task 0 is available to process. Available tasks = {0}.
- Also at time = 1, the idle CPU starts processing task 0. Available tasks = {}.
- At time = 2, task 1 is available to process. Available tasks = {1}.
- At time = 3, task 2 is available to process. Available tasks = {1, 2}.
- Also at time = 3, the CPU finishes task 0 and starts processing task 2 as it is the shortest. Available tasks = {1}.
- At time = 4, task 3 is available to process. Available tasks = {1, 3}.
- At time = 5, the CPU finishes task 2 and starts processing task 3 as it is the shortest. Available tasks = {1}.
- At time = 6, the CPU finishes task 3 and starts processing task 1. Available tasks = {}.
- At time = 10, the CPU finishes task 1 and becomes idle.
Example 2:
Input: tasks = [[7,10],[7,12],[7,5],[7,4],[7,2]]
Output: [4,3,2,0,1]
Explanation: The events go as follows:
- At time = 7, all the tasks become available. Available tasks = {0,1,2,3,4}.
- Also at time = 7, the idle CPU starts processing task 4. Available tasks = {0,1,2,3}.
- At time = 9, the CPU finishes task 4 and starts processing task 3. Available tasks = {0,1,2}.
- At time = 13, the CPU finishes task 3 and starts processing task 2. Available tasks = {0,1}.
- At time = 18, the CPU finishes task 2 and starts processing task 0. Available tasks = {1}.
- At time = 28, the CPU finishes task 0 and starts processing task 1. Available tasks = {}.
- At time = 40, the CPU finishes task 1 and becomes idle.
Constraints:
tasks.length == n
1 <= n <= 105
1 <= enqueueTimei, processingTimei <= 109 | Python | Priority Queue | 83 | single-threaded-cpu | 0.42 | heckt27 | Medium | 26,202 | 1,834 |
find xor sum of all pairs bitwise and | class Solution:
#example 1
#result =[(1&6)^(1&5)^(2&6)^(2&5)^(3&6)^(3&5)]
\ / \ / \ /
# (1&(6^5)) ^ (2&(6^5)) ^ (3&(6^5))
\ | /
\ | /
\ | /
\ | /
# ((1^2^3) & (6^5))
def getXORSum(self, a, b):
x = 0
for i in range(len(a)):
x = x ^ a[i]
y = 0
for j in range(len(b)):
y = y ^ b[j]
return x & y | https://leetcode.com/problems/find-xor-sum-of-all-pairs-bitwise-and/discuss/2724403/Simple-python-code-with-explanation | 1 | The XOR sum of a list is the bitwise XOR of all its elements. If the list only contains one element, then its XOR sum will be equal to this element.
For example, the XOR sum of [1,2,3,4] is equal to 1 XOR 2 XOR 3 XOR 4 = 4, and the XOR sum of [3] is equal to 3.
You are given two 0-indexed arrays arr1 and arr2 that consist only of non-negative integers.
Consider the list containing the result of arr1[i] AND arr2[j] (bitwise AND) for every (i, j) pair where 0 <= i < arr1.length and 0 <= j < arr2.length.
Return the XOR sum of the aforementioned list.
Example 1:
Input: arr1 = [1,2,3], arr2 = [6,5]
Output: 0
Explanation: The list = [1 AND 6, 1 AND 5, 2 AND 6, 2 AND 5, 3 AND 6, 3 AND 5] = [0,1,2,0,2,1].
The XOR sum = 0 XOR 1 XOR 2 XOR 0 XOR 2 XOR 1 = 0.
Example 2:
Input: arr1 = [12], arr2 = [4]
Output: 4
Explanation: The list = [12 AND 4] = [4]. The XOR sum = 4.
Constraints:
1 <= arr1.length, arr2.length <= 105
0 <= arr1[i], arr2[j] <= 109 | Simple python code with explanation | 23 | find-xor-sum-of-all-pairs-bitwise-and | 0.601 | thomanani | Hard | 26,211 | 1,835 |
sum of digits in base k | class Solution:
def sumBase(self, n: int, k: int) -> int:
ans = 0
while n:
n, x = divmod(n, k)
ans += x
return ans | https://leetcode.com/problems/sum-of-digits-in-base-k/discuss/1175067/Python3-self-explained | 12 | Given an integer n (in base 10) and a base k, return the sum of the digits of n after converting n from base 10 to base k.
After converting, each digit should be interpreted as a base 10 number, and the sum should be returned in base 10.
Example 1:
Input: n = 34, k = 6
Output: 9
Explanation: 34 (base 10) expressed in base 6 is 54. 5 + 4 = 9.
Example 2:
Input: n = 10, k = 10
Output: 1
Explanation: n is already in base 10. 1 + 0 = 1.
Constraints:
1 <= n <= 100
2 <= k <= 10 | [Python3] self-explained | 1,200 | sum-of-digits-in-base-k | 0.768 | ye15 | Easy | 26,219 | 1,837 |
frequency of the most frequent element | class Solution:
def maxFrequency(self, nums: List[int], k: int) -> int:
nums.sort()
n = len(nums)
sum_s_w = nums[0]
fin = 1
i=0
for j in range(1,n):
sum_s_w+=nums[j]
mx = nums[j]
while sum_s_w+k<mx*(j-i+1):
sum_s_w -= nums[i]
i += 1
fin = max(fin,j-i+1)
return fin | https://leetcode.com/problems/frequency-of-the-most-frequent-element/discuss/1179374/Python-3-Sliding-Window-Explanation-with-Code | 14 | The frequency of an element is the number of times it occurs in an array.
You are given an integer array nums and an integer k. In one operation, you can choose an index of nums and increment the element at that index by 1.
Return the maximum possible frequency of an element after performing at most k operations.
Example 1:
Input: nums = [1,2,4], k = 5
Output: 3
Explanation: Increment the first element three times and the second element two times to make nums = [4,4,4].
4 has a frequency of 3.
Example 2:
Input: nums = [1,4,8,13], k = 5
Output: 2
Explanation: There are multiple optimal solutions:
- Increment the first element three times to make nums = [4,4,8,13]. 4 has a frequency of 2.
- Increment the second element four times to make nums = [1,8,8,13]. 8 has a frequency of 2.
- Increment the third element five times to make nums = [1,4,13,13]. 13 has a frequency of 2.
Example 3:
Input: nums = [3,9,6], k = 2
Output: 1
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 105
1 <= k <= 105 | [Python 3] Sliding Window Explanation with Code | 826 | frequency-of-the-most-frequent-element | 0.386 | vamsi81523 | Medium | 26,237 | 1,838 |
longest substring of all vowels in order | class Solution:
def longestBeautifulSubstring(self, word: str) -> int:
vowels = "aeiou"
ans = 0
cnt = prev = -1
for i, x in enumerate(word):
curr = vowels.index(x)
if cnt >= 0: # in the middle of counting
if 0 <= curr - prev <= 1:
cnt += 1
if x == "u": ans = max(ans, cnt)
elif x == "a": cnt = 1
else: cnt = -1
elif x == "a": cnt = 1
prev = curr
return ans | https://leetcode.com/problems/longest-substring-of-all-vowels-in-order/discuss/1175044/Python3-greedy | 9 | A string is considered beautiful if it satisfies the following conditions:
Each of the 5 English vowels ('a', 'e', 'i', 'o', 'u') must appear at least once in it.
The letters must be sorted in alphabetical order (i.e. all 'a's before 'e's, all 'e's before 'i's, etc.).
For example, strings "aeiou" and "aaaaaaeiiiioou" are considered beautiful, but "uaeio", "aeoiu", and "aaaeeeooo" are not beautiful.
Given a string word consisting of English vowels, return the length of the longest beautiful substring of word. If no such substring exists, return 0.
A substring is a contiguous sequence of characters in a string.
Example 1:
Input: word = "aeiaaioaaaaeiiiiouuuooaauuaeiu"
Output: 13
Explanation: The longest beautiful substring in word is "aaaaeiiiiouuu" of length 13.
Example 2:
Input: word = "aeeeiiiioooauuuaeiou"
Output: 5
Explanation: The longest beautiful substring in word is "aeiou" of length 5.
Example 3:
Input: word = "a"
Output: 0
Explanation: There is no beautiful substring, so return 0.
Constraints:
1 <= word.length <= 5 * 105
word consists of characters 'a', 'e', 'i', 'o', and 'u'. | [Python3] greedy | 703 | longest-substring-of-all-vowels-in-order | 0.486 | ye15 | Medium | 26,248 | 1,839 |
maximum building height | class Solution:
def maxBuilding(self, n: int, restrictions: List[List[int]]) -> int:
restrictions.extend([[1, 0], [n, n-1]])
restrictions.sort()
for i in reversed(range(len(restrictions)-1)):
restrictions[i][1] = min(restrictions[i][1], restrictions[i+1][1] + restrictions[i+1][0] - restrictions[i][0])
ans = 0
for i in range(1, len(restrictions)):
restrictions[i][1] = min(restrictions[i][1], restrictions[i-1][1] + restrictions[i][0] - restrictions[i-1][0])
ans = max(ans, (restrictions[i-1][1] + restrictions[i][0] - restrictions[i-1][0] + restrictions[i][1])//2)
return ans | https://leetcode.com/problems/maximum-building-height/discuss/1175057/Python3-greedy | 2 | You want to build n new buildings in a city. The new buildings will be built in a line and are labeled from 1 to n.
However, there are city restrictions on the heights of the new buildings:
The height of each building must be a non-negative integer.
The height of the first building must be 0.
The height difference between any two adjacent buildings cannot exceed 1.
Additionally, there are city restrictions on the maximum height of specific buildings. These restrictions are given as a 2D integer array restrictions where restrictions[i] = [idi, maxHeighti] indicates that building idi must have a height less than or equal to maxHeighti.
It is guaranteed that each building will appear at most once in restrictions, and building 1 will not be in restrictions.
Return the maximum possible height of the tallest building.
Example 1:
Input: n = 5, restrictions = [[2,1],[4,1]]
Output: 2
Explanation: The green area in the image indicates the maximum allowed height for each building.
We can build the buildings with heights [0,1,2,1,2], and the tallest building has a height of 2.
Example 2:
Input: n = 6, restrictions = []
Output: 5
Explanation: The green area in the image indicates the maximum allowed height for each building.
We can build the buildings with heights [0,1,2,3,4,5], and the tallest building has a height of 5.
Example 3:
Input: n = 10, restrictions = [[5,3],[2,5],[7,4],[10,3]]
Output: 5
Explanation: The green area in the image indicates the maximum allowed height for each building.
We can build the buildings with heights [0,1,2,3,3,4,4,5,4,3], and the tallest building has a height of 5.
Constraints:
2 <= n <= 109
0 <= restrictions.length <= min(n - 1, 105)
2 <= idi <= n
idi is unique.
0 <= maxHeighti <= 109 | [Python3] greedy | 257 | maximum-building-height | 0.353 | ye15 | Hard | 26,270 | 1,840 |
replace all digits with characters | class Solution:
def replaceDigits(self, s: str) -> str:
ans = ""
def shift(char, num):
return chr(ord(char) + int(num))
for index in range(len(s)):
ans += shift(s[index-1], s[index]) if index % 2 else s[index]
return ans | https://leetcode.com/problems/replace-all-digits-with-characters/discuss/1243646/Python3-simple-code-96-time-with-explanation | 5 | You are given a 0-indexed string s that has lowercase English letters in its even indices and digits in its odd indices.
There is a function shift(c, x), where c is a character and x is a digit, that returns the xth character after c.
For example, shift('a', 5) = 'f' and shift('x', 0) = 'x'.
For every odd index i, you want to replace the digit s[i] with shift(s[i-1], s[i]).
Return s after replacing all digits. It is guaranteed that shift(s[i-1], s[i]) will never exceed 'z'.
Example 1:
Input: s = "a1c1e1"
Output: "abcdef"
Explanation: The digits are replaced as follows:
- s[1] -> shift('a',1) = 'b'
- s[3] -> shift('c',1) = 'd'
- s[5] -> shift('e',1) = 'f'
Example 2:
Input: s = "a1b2c3d4e"
Output: "abbdcfdhe"
Explanation: The digits are replaced as follows:
- s[1] -> shift('a',1) = 'b'
- s[3] -> shift('b',2) = 'd'
- s[5] -> shift('c',3) = 'f'
- s[7] -> shift('d',4) = 'h'
Constraints:
1 <= s.length <= 100
s consists only of lowercase English letters and digits.
shift(s[i-1], s[i]) <= 'z' for all odd indices i. | Python3 simple code 96% time, with explanation | 327 | replace-all-digits-with-characters | 0.798 | albezx0 | Easy | 26,272 | 1,844 |
maximum element after decreasing and rearranging | class Solution:
def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int:
counter = collections.Counter(arr)
available = sum(n > len(arr) for n in arr)
i = ans = len(arr)
while i > 0:
# This number is not in arr
if not counter[i]:
# Use another number to fill in its place. If we cannot, we have to decrease our max
if available: available -= 1
else: ans -= 1
# Other occurences can be used for future.
else:
available += counter[i] - 1
i -= 1
return ans | https://leetcode.com/problems/maximum-element-after-decreasing-and-rearranging/discuss/1503918/Python-O(N)-Time-and-Space.-Easy-to-understand | 1 | You are given an array of positive integers arr. Perform some operations (possibly none) on arr so that it satisfies these conditions:
The value of the first element in arr must be 1.
The absolute difference between any 2 adjacent elements must be less than or equal to 1. In other words, abs(arr[i] - arr[i - 1]) <= 1 for each i where 1 <= i < arr.length (0-indexed). abs(x) is the absolute value of x.
There are 2 types of operations that you can perform any number of times:
Decrease the value of any element of arr to a smaller positive integer.
Rearrange the elements of arr to be in any order.
Return the maximum possible value of an element in arr after performing the operations to satisfy the conditions.
Example 1:
Input: arr = [2,2,1,2,1]
Output: 2
Explanation:
We can satisfy the conditions by rearranging arr so it becomes [1,2,2,2,1].
The largest element in arr is 2.
Example 2:
Input: arr = [100,1,1000]
Output: 3
Explanation:
One possible way to satisfy the conditions is by doing the following:
1. Rearrange arr so it becomes [1,100,1000].
2. Decrease the value of the second element to 2.
3. Decrease the value of the third element to 3.
Now arr = [1,2,3], which satisfies the conditions.
The largest element in arr is 3.
Example 3:
Input: arr = [1,2,3,4,5]
Output: 5
Explanation: The array already satisfies the conditions, and the largest element is 5.
Constraints:
1 <= arr.length <= 105
1 <= arr[i] <= 109 | [Python] O(N) Time and Space. Easy to understand | 205 | maximum-element-after-decreasing-and-rearranging | 0.591 | JummyEgg | Medium | 26,310 | 1,846 |
closest room | class Solution:
def closestRoom(self, rooms: List[List[int]], queries: List[List[int]]) -> List[int]:
ans = [0] * len(queries)
# sort queries to handle largest size queries first
q = deque(sorted([(size, room, i) for i, (room, size) in enumerate(queries)], key=lambda a: (-a[0], a[1], a[2])))
# sort rooms by descending size
rooms = deque(sorted(rooms, key=lambda x: -x[1]))
# current available room ids
cands = []
while q:
size, room, i = q.popleft()
# add room ids to candidates as long as top of room size meet the requirements
while rooms and rooms[0][1] >= size:
bisect.insort(cands, rooms.popleft()[0])
# if no room size available, return -1
if not cands: ans[i] = -1
# else use bisect to find optimal room ids
else:
loc = bisect.bisect_left(cands, room)
if loc == 0: ans[i] = cands[loc]
elif loc == len(cands): ans[i] = cands[-1]
else: ans[i] = cands[loc - 1] if room - cands[loc - 1] <= cands[loc] - room else cands[loc]
return ans | https://leetcode.com/problems/closest-room/discuss/1186155/Python-3-Aggregate-sorted-list-detailed-explanation-(2080-ms) | 1 | There is a hotel with n rooms. The rooms are represented by a 2D integer array rooms where rooms[i] = [roomIdi, sizei] denotes that there is a room with room number roomIdi and size equal to sizei. Each roomIdi is guaranteed to be unique.
You are also given k queries in a 2D array queries where queries[j] = [preferredj, minSizej]. The answer to the jth query is the room number id of a room such that:
The room has a size of at least minSizej, and
abs(id - preferredj) is minimized, where abs(x) is the absolute value of x.
If there is a tie in the absolute difference, then use the room with the smallest such id. If there is no such room, the answer is -1.
Return an array answer of length k where answer[j] contains the answer to the jth query.
Example 1:
Input: rooms = [[2,2],[1,2],[3,2]], queries = [[3,1],[3,3],[5,2]]
Output: [3,-1,3]
Explanation: The answers to the queries are as follows:
Query = [3,1]: Room number 3 is the closest as abs(3 - 3) = 0, and its size of 2 is at least 1. The answer is 3.
Query = [3,3]: There are no rooms with a size of at least 3, so the answer is -1.
Query = [5,2]: Room number 3 is the closest as abs(3 - 5) = 2, and its size of 2 is at least 2. The answer is 3.
Example 2:
Input: rooms = [[1,4],[2,3],[3,5],[4,1],[5,2]], queries = [[2,3],[2,4],[2,5]]
Output: [2,1,3]
Explanation: The answers to the queries are as follows:
Query = [2,3]: Room number 2 is the closest as abs(2 - 2) = 0, and its size of 3 is at least 3. The answer is 2.
Query = [2,4]: Room numbers 1 and 3 both have sizes of at least 4. The answer is 1 since it is smaller.
Query = [2,5]: Room number 3 is the only room with a size of at least 5. The answer is 3.
Constraints:
n == rooms.length
1 <= n <= 105
k == queries.length
1 <= k <= 104
1 <= roomIdi, preferredj <= 107
1 <= sizei, minSizej <= 107 | [Python 3] Aggregate sorted list, detailed explanation (2080 ms) | 111 | closest-room | 0.353 | chestnut890123 | Hard | 26,320 | 1,847 |
minimum distance to the target element | class Solution:
def getMinDistance(self, nums: List[int], target: int, start: int) -> int:
ans = inf
for i, x in enumerate(nums):
if x == target:
ans = min(ans, abs(i - start))
return ans | https://leetcode.com/problems/minimum-distance-to-the-target-element/discuss/1186862/Python3-linear-sweep | 9 | Given an integer array nums (0-indexed) and two integers target and start, find an index i such that nums[i] == target and abs(i - start) is minimized. Note that abs(x) is the absolute value of x.
Return abs(i - start).
It is guaranteed that target exists in nums.
Example 1:
Input: nums = [1,2,3,4,5], target = 5, start = 3
Output: 1
Explanation: nums[4] = 5 is the only value equal to target, so the answer is abs(4 - 3) = 1.
Example 2:
Input: nums = [1], target = 1, start = 0
Output: 0
Explanation: nums[0] = 1 is the only value equal to target, so the answer is abs(0 - 0) = 0.
Example 3:
Input: nums = [1,1,1,1,1,1,1,1,1,1], target = 1, start = 0
Output: 0
Explanation: Every value of nums is 1, but nums[0] minimizes abs(i - start), which is abs(0 - 0) = 0.
Constraints:
1 <= nums.length <= 1000
1 <= nums[i] <= 104
0 <= start < nums.length
target is in nums. | [Python3] linear sweep | 302 | minimum-distance-to-the-target-element | 0.585 | ye15 | Easy | 26,321 | 1,848 |
splitting a string into descending consecutive values | class Solution:
def splitString(self, s: str) -> bool:
"""
Time = O(2^N)
Space = O(N) space from stack
"""
def dfs(index: int, last: int) -> bool:
if index == len(s):
return True
# j: [index, len(s)-1]
for j in range(index, len(s)):
# cur: [index, index] ~ [index, len(s)-1]
cur = int(s[index:j + 1])
# last: [...,index-1]
# cur: [index+1, j]
# last = cur -> next: [j+1,...)
# DFS condition: cur = last - 1 && dfs(j+1, cur) == true
if cur == last - 1 and dfs(j + 1, cur):
return True
return False
for i in range(len(s) - 1):
last = int(s[:i+1])
if dfs(i + 1, last):
return True
return False | https://leetcode.com/problems/splitting-a-string-into-descending-consecutive-values/discuss/2632013/Clear-Python-DFS-with-comments | 0 | You are given a string s that consists of only digits.
Check if we can split s into two or more non-empty substrings such that the numerical values of the substrings are in descending order and the difference between numerical values of every two adjacent substrings is equal to 1.
For example, the string s = "0090089" can be split into ["0090", "089"] with numerical values [90,89]. The values are in descending order and adjacent values differ by 1, so this way is valid.
Another example, the string s = "001" can be split into ["0", "01"], ["00", "1"], or ["0", "0", "1"]. However all the ways are invalid because they have numerical values [0,1], [0,1], and [0,0,1] respectively, all of which are not in descending order.
Return true if it is possible to split s as described above, or false otherwise.
A substring is a contiguous sequence of characters in a string.
Example 1:
Input: s = "1234"
Output: false
Explanation: There is no valid way to split s.
Example 2:
Input: s = "050043"
Output: true
Explanation: s can be split into ["05", "004", "3"] with numerical values [5,4,3].
The values are in descending order with adjacent values differing by 1.
Example 3:
Input: s = "9080701"
Output: false
Explanation: There is no valid way to split s.
Constraints:
1 <= s.length <= 20
s only consists of digits. | Clear Python DFS with comments | 8 | splitting-a-string-into-descending-consecutive-values | 0.323 | changyou1009 | Medium | 26,341 | 1,849 |
minimum adjacent swaps to reach the kth smallest number | class Solution:
def getMinSwaps(self, num: str, k: int) -> int:
num = list(num)
orig = num.copy()
for _ in range(k):
for i in reversed(range(len(num)-1)):
if num[i] < num[i+1]:
ii = i+1
while ii < len(num) and num[i] < num[ii]: ii += 1
num[i], num[ii-1] = num[ii-1], num[i]
lo, hi = i+1, len(num)-1
while lo < hi:
num[lo], num[hi] = num[hi], num[lo]
lo += 1
hi -= 1
break
ans = 0
for i in range(len(num)):
ii = i
while orig[i] != num[i]:
ans += 1
ii += 1
num[i], num[ii] = num[ii], num[i]
return ans | https://leetcode.com/problems/minimum-adjacent-swaps-to-reach-the-kth-smallest-number/discuss/1186887/Python3-brute-force | 7 | You are given a string num, representing a large integer, and an integer k.
We call some integer wonderful if it is a permutation of the digits in num and is greater in value than num. There can be many wonderful integers. However, we only care about the smallest-valued ones.
For example, when num = "5489355142":
The 1st smallest wonderful integer is "5489355214".
The 2nd smallest wonderful integer is "5489355241".
The 3rd smallest wonderful integer is "5489355412".
The 4th smallest wonderful integer is "5489355421".
Return the minimum number of adjacent digit swaps that needs to be applied to num to reach the kth smallest wonderful integer.
The tests are generated in such a way that kth smallest wonderful integer exists.
Example 1:
Input: num = "5489355142", k = 4
Output: 2
Explanation: The 4th smallest wonderful number is "5489355421". To get this number:
- Swap index 7 with index 8: "5489355142" -> "5489355412"
- Swap index 8 with index 9: "5489355412" -> "5489355421"
Example 2:
Input: num = "11112", k = 4
Output: 4
Explanation: The 4th smallest wonderful number is "21111". To get this number:
- Swap index 3 with index 4: "11112" -> "11121"
- Swap index 2 with index 3: "11121" -> "11211"
- Swap index 1 with index 2: "11211" -> "12111"
- Swap index 0 with index 1: "12111" -> "21111"
Example 3:
Input: num = "00123", k = 1
Output: 1
Explanation: The 1st smallest wonderful number is "00132". To get this number:
- Swap index 3 with index 4: "00123" -> "00132"
Constraints:
2 <= num.length <= 1000
1 <= k <= 1000
num only consists of digits. | [Python3] brute-force | 803 | minimum-adjacent-swaps-to-reach-the-kth-smallest-number | 0.719 | ye15 | Medium | 26,347 | 1,850 |
minimum interval to include each query | class Solution:
def minInterval(self, intervals: List[List[int]], queries: List[int]) -> List[int]:
intervals.sort(key = lambda x:x[1]-x[0])
q = sorted([qu,i] for i,qu in enumerate(queries))
res=[-1]*len(queries)
for left,right in intervals:
ind = bisect.bisect(q,[left])
while ind<len(q) and q[ind][0]<=right:
res[q.pop(ind)[1]]=right-left+1
return res | https://leetcode.com/problems/minimum-interval-to-include-each-query/discuss/1422509/For-Beginners-oror-Easy-Approach-oror-Well-Explained-oror-Clean-and-Concise | 4 | You are given a 2D integer array intervals, where intervals[i] = [lefti, righti] describes the ith interval starting at lefti and ending at righti (inclusive). The size of an interval is defined as the number of integers it contains, or more formally righti - lefti + 1.
You are also given an integer array queries. The answer to the jth query is the size of the smallest interval i such that lefti <= queries[j] <= righti. If no such interval exists, the answer is -1.
Return an array containing the answers to the queries.
Example 1:
Input: intervals = [[1,4],[2,4],[3,6],[4,4]], queries = [2,3,4,5]
Output: [3,3,1,4]
Explanation: The queries are processed as follows:
- Query = 2: The interval [2,4] is the smallest interval containing 2. The answer is 4 - 2 + 1 = 3.
- Query = 3: The interval [2,4] is the smallest interval containing 3. The answer is 4 - 2 + 1 = 3.
- Query = 4: The interval [4,4] is the smallest interval containing 4. The answer is 4 - 4 + 1 = 1.
- Query = 5: The interval [3,6] is the smallest interval containing 5. The answer is 6 - 3 + 1 = 4.
Example 2:
Input: intervals = [[2,3],[2,5],[1,8],[20,25]], queries = [2,19,5,22]
Output: [2,-1,4,6]
Explanation: The queries are processed as follows:
- Query = 2: The interval [2,3] is the smallest interval containing 2. The answer is 3 - 2 + 1 = 2.
- Query = 19: None of the intervals contain 19. The answer is -1.
- Query = 5: The interval [2,5] is the smallest interval containing 5. The answer is 5 - 2 + 1 = 4.
- Query = 22: The interval [20,25] is the smallest interval containing 22. The answer is 25 - 20 + 1 = 6.
Constraints:
1 <= intervals.length <= 105
1 <= queries.length <= 105
intervals[i].length == 2
1 <= lefti <= righti <= 107
1 <= queries[j] <= 107 | ๐๐ For Beginners || Easy-Approach || Well-Explained || Clean & Concise ๐ | 274 | minimum-interval-to-include-each-query | 0.479 | abhi9Rai | Hard | 26,352 | 1,851 |
maximum population year | class Solution:
def maximumPopulation(self, logs: List[List[int]]) -> int:
# the timespan 1950-2050 covers 101 years
delta = [0] * 101
# to make explicit the conversion from the year (1950 + i) to the ith index
conversionDiff = 1950
for l in logs:
# the log's first entry, birth, increases the population by 1
delta[l[0] - conversionDiff] += 1
# the log's second entry, death, decreases the population by 1
delta[l[1] - conversionDiff] -= 1
runningSum = 0
maxPop = 0
year = 1950
# find the year with the greatest population
for i, d in enumerate(delta):
runningSum += d
# since we want the first year this population was reached, only update if strictly greater than the previous maximum population
if runningSum > maxPop:
maxPop = runningSum
year = conversionDiff + i
return year | https://leetcode.com/problems/maximum-population-year/discuss/1210686/Python3-O(N) | 21 | You are given a 2D integer array logs where each logs[i] = [birthi, deathi] indicates the birth and death years of the ith person.
The population of some year x is the number of people alive during that year. The ith person is counted in year x's population if x is in the inclusive range [birthi, deathi - 1]. Note that the person is not counted in the year that they die.
Return the earliest year with the maximum population.
Example 1:
Input: logs = [[1993,1999],[2000,2010]]
Output: 1993
Explanation: The maximum population is 1, and 1993 is the earliest year with this population.
Example 2:
Input: logs = [[1950,1961],[1960,1971],[1970,1981]]
Output: 1960
Explanation:
The maximum population is 2, and it had happened in years 1960 and 1970.
The earlier year between them is 1960.
Constraints:
1 <= logs.length <= 100
1950 <= birthi < deathi <= 2050 | Python3 O(N) | 2,000 | maximum-population-year | 0.599 | signifying | Easy | 26,358 | 1,854 |
maximum distance between a pair of values | class Solution:
def maxDistance(self, nums1: List[int], nums2: List[int]) -> int:
length1, length2 = len(nums1), len(nums2)
i,j = 0,0
result = 0
while i < length1 and j < length2:
if nums1[i] > nums2[j]:
i+=1
else:
result = max(result,j-i)
j+=1
return result | https://leetcode.com/problems/maximum-distance-between-a-pair-of-values/discuss/2209743/Python3-simple-solution-using-two-pointers | 6 | You are given two non-increasing 0-indexed integer arrays nums1 and nums2.
A pair of indices (i, j), where 0 <= i < nums1.length and 0 <= j < nums2.length, is valid if both i <= j and nums1[i] <= nums2[j]. The distance of the pair is j - i.
Return the maximum distance of any valid pair (i, j). If there are no valid pairs, return 0.
An array arr is non-increasing if arr[i-1] >= arr[i] for every 1 <= i < arr.length.
Example 1:
Input: nums1 = [55,30,5,4,2], nums2 = [100,20,10,10,5]
Output: 2
Explanation: The valid pairs are (0,0), (2,2), (2,3), (2,4), (3,3), (3,4), and (4,4).
The maximum distance is 2 with pair (2,4).
Example 2:
Input: nums1 = [2,2,2], nums2 = [10,10,1]
Output: 1
Explanation: The valid pairs are (0,0), (0,1), and (1,1).
The maximum distance is 1 with pair (0,1).
Example 3:
Input: nums1 = [30,29,19,5], nums2 = [25,25,25,25,25]
Output: 2
Explanation: The valid pairs are (2,2), (2,3), (2,4), (3,3), and (3,4).
The maximum distance is 2 with pair (2,4).
Constraints:
1 <= nums1.length, nums2.length <= 105
1 <= nums1[i], nums2[j] <= 105
Both nums1 and nums2 are non-increasing. | ๐ Python3 simple solution using two pointers | 69 | maximum-distance-between-a-pair-of-values | 0.527 | Dark_wolf_jss | Medium | 26,372 | 1,855 |
maximum subarray min product | class Solution:
def maxSumMinProduct(self, nums: List[int]) -> int:
prefix = [0]
for x in nums: prefix.append(prefix[-1] + x)
ans = 0
stack = []
for i, x in enumerate(nums + [-inf]): # append "-inf" to force flush all elements
while stack and stack[-1][1] >= x:
_, xx = stack.pop()
ii = stack[-1][0] if stack else -1
ans = max(ans, xx*(prefix[i] - prefix[ii+1]))
stack.append((i, x))
return ans % 1_000_000_007 | https://leetcode.com/problems/maximum-subarray-min-product/discuss/1198800/Python3-mono-stack | 10 | The min-product of an array is equal to the minimum value in the array multiplied by the array's sum.
For example, the array [3,2,5] (minimum value is 2) has a min-product of 2 * (3+2+5) = 2 * 10 = 20.
Given an array of integers nums, return the maximum min-product of any non-empty subarray of nums. Since the answer may be large, return it modulo 109 + 7.
Note that the min-product should be maximized before performing the modulo operation. Testcases are generated such that the maximum min-product without modulo will fit in a 64-bit signed integer.
A subarray is a contiguous part of an array.
Example 1:
Input: nums = [1,2,3,2]
Output: 14
Explanation: The maximum min-product is achieved with the subarray [2,3,2] (minimum value is 2).
2 * (2+3+2) = 2 * 7 = 14.
Example 2:
Input: nums = [2,3,3,1,2]
Output: 18
Explanation: The maximum min-product is achieved with the subarray [3,3] (minimum value is 3).
3 * (3+3) = 3 * 6 = 18.
Example 3:
Input: nums = [3,1,5,6,4,2]
Output: 60
Explanation: The maximum min-product is achieved with the subarray [5,6,4] (minimum value is 4).
4 * (5+6+4) = 4 * 15 = 60.
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 107 | [Python3] mono-stack | 345 | maximum-subarray-min-product | 0.378 | ye15 | Medium | 26,384 | 1,856 |
largest color value in a directed graph | class Solution(object):
def largestPathValue(self, colors, edges):
n=len(colors)
graph=defaultdict(list)
indegree=defaultdict(int)
for u,v in edges:
graph[u].append(v)
indegree[v]+=1
queue=[]
dp=[[0]*26 for _ in range(n)]
colorvalues=[ord(c)-ord("a") for c in colors]
for u in range(n):
if u not in indegree:
queue.append(u)
dp[u][colorvalues[u]]=1
visited=0
while queue:
u=queue.pop()
visited+=1
for v in graph[u]:
for c in range(26):
dp[v][c]=max(dp[v][c],dp[u][c] + (c==colorvalues[v]))
indegree[v]-=1
if indegree[v]==0:
queue.append(v)
del indegree[v]
if visited<n:
return -1
return max(max(x) for x in dp)
``` | https://leetcode.com/problems/largest-color-value-in-a-directed-graph/discuss/1200668/easy-python-sol-.. | 9 | There is a directed graph of n colored nodes and m edges. The nodes are numbered from 0 to n - 1.
You are given a string colors where colors[i] is a lowercase English letter representing the color of the ith node in this graph (0-indexed). You are also given a 2D array edges where edges[j] = [aj, bj] indicates that there is a directed edge from node aj to node bj.
A valid path in the graph is a sequence of nodes x1 -> x2 -> x3 -> ... -> xk such that there is a directed edge from xi to xi+1 for every 1 <= i < k. The color value of the path is the number of nodes that are colored the most frequently occurring color along that path.
Return the largest color value of any valid path in the given graph, or -1 if the graph contains a cycle.
Example 1:
Input: colors = "abaca", edges = [[0,1],[0,2],[2,3],[3,4]]
Output: 3
Explanation: The path 0 -> 2 -> 3 -> 4 contains 3 nodes that are colored "a" (red in the above image).
Example 2:
Input: colors = "a", edges = [[0,0]]
Output: -1
Explanation: There is a cycle from 0 to 0.
Constraints:
n == colors.length
m == edges.length
1 <= n <= 105
0 <= m <= 105
colors consists of lowercase English letters.
0 <= aj, bj < n | easy python sol .. | 299 | largest-color-value-in-a-directed-graph | 0.407 | aayush_chhabra | Hard | 26,391 | 1,857 |
sorting the sentence | class Solution:
def sortSentence(self, s: str) -> str:
arr = [i[-1] + i[:-1] for i in s.split()]
arr.sort()
ans = ""
for i in arr:
ans += i[1:] + ' '
return ans[:-1] | https://leetcode.com/problems/sorting-the-sentence/discuss/1219040/Python3-99.60-Fast-Solution | 23 | A sentence is a list of words that are separated by a single space with no leading or trailing spaces. Each word consists of lowercase and uppercase English letters.
A sentence can be shuffled by appending the 1-indexed word position to each word then rearranging the words in the sentence.
For example, the sentence "This is a sentence" can be shuffled as "sentence4 a3 is2 This1" or "is2 sentence4 This1 a3".
Given a shuffled sentence s containing no more than 9 words, reconstruct and return the original sentence.
Example 1:
Input: s = "is2 sentence4 This1 a3"
Output: "This is a sentence"
Explanation: Sort the words in s to their original positions "This1 is2 a3 sentence4", then remove the numbers.
Example 2:
Input: s = "Myself2 Me1 I4 and3"
Output: "Me Myself and I"
Explanation: Sort the words in s to their original positions "Me1 Myself2 and3 I4", then remove the numbers.
Constraints:
2 <= s.length <= 200
s consists of lowercase and uppercase English letters, spaces, and digits from 1 to 9.
The number of words in s is between 1 and 9.
The words in s are separated by a single space.
s contains no leading or trailing spaces. | [Python3] 99.60% Fast Solution | 2,000 | sorting-the-sentence | 0.844 | VoidCupboard | Easy | 26,394 | 1,859 |
incremental memory leak | class Solution:
def memLeak(self, memory1: int, memory2: int) -> List[int]:
i = 1
while max(memory1, memory2) >= i:
if memory1 >= memory2:
memory1 -= i
else:
memory2 -= i
i += 1
return [i, memory1, memory2] | https://leetcode.com/problems/incremental-memory-leak/discuss/1210088/JavaC%2B%2BPython-Solution | 27 | You are given two integers memory1 and memory2 representing the available memory in bits on two memory sticks. There is currently a faulty program running that consumes an increasing amount of memory every second.
At the ith second (starting from 1), i bits of memory are allocated to the stick with more available memory (or from the first memory stick if both have the same available memory). If neither stick has at least i bits of available memory, the program crashes.
Return an array containing [crashTime, memory1crash, memory2crash], where crashTime is the time (in seconds) when the program crashed and memory1crash and memory2crash are the available bits of memory in the first and second sticks respectively.
Example 1:
Input: memory1 = 2, memory2 = 2
Output: [3,1,0]
Explanation: The memory is allocated as follows:
- At the 1st second, 1 bit of memory is allocated to stick 1. The first stick now has 1 bit of available memory.
- At the 2nd second, 2 bits of memory are allocated to stick 2. The second stick now has 0 bits of available memory.
- At the 3rd second, the program crashes. The sticks have 1 and 0 bits available respectively.
Example 2:
Input: memory1 = 8, memory2 = 11
Output: [6,0,4]
Explanation: The memory is allocated as follows:
- At the 1st second, 1 bit of memory is allocated to stick 2. The second stick now has 10 bit of available memory.
- At the 2nd second, 2 bits of memory are allocated to stick 2. The second stick now has 8 bits of available memory.
- At the 3rd second, 3 bits of memory are allocated to stick 1. The first stick now has 5 bits of available memory.
- At the 4th second, 4 bits of memory are allocated to stick 2. The second stick now has 4 bits of available memory.
- At the 5th second, 5 bits of memory are allocated to stick 1. The first stick now has 0 bits of available memory.
- At the 6th second, the program crashes. The sticks have 0 and 4 bits available respectively.
Constraints:
0 <= memory1, memory2 <= 231 - 1 | [Java/C++/Python] Solution | 1,800 | incremental-memory-leak | 0.718 | lokeshsenthilkumar | Medium | 26,438 | 1,860 |
rotating the box | class Solution:
def rotateTheBox(self, box: List[List[str]]) -> List[List[str]]:
# move stones to right, row by row
for i in range(len(box)):
stone = 0
for j in range(len(box[0])):
if box[i][j] == '#': # if a stone
stone += 1
box[i][j] = '.'
elif box[i][j] == '*': # if a obstacle
for m in range(stone):
box[i][j-m-1] = '#'
stone = 0
# if reaches the end of j, but still have stone
if stone != 0:
for m in range(stone):
box[i][j-m] = '#'
# rotate box, same as leetcode #48
box[:] = zip(*box[::-1])
return box | https://leetcode.com/problems/rotating-the-box/discuss/1622675/Python-Easy-explanation | 10 | You are given an m x n matrix of characters box representing a side-view of a box. Each cell of the box is one of the following:
A stone '#'
A stationary obstacle '*'
Empty '.'
The box is rotated 90 degrees clockwise, causing some of the stones to fall due to gravity. Each stone falls down until it lands on an obstacle, another stone, or the bottom of the box. Gravity does not affect the obstacles' positions, and the inertia from the box's rotation does not affect the stones' horizontal positions.
It is guaranteed that each stone in box rests on an obstacle, another stone, or the bottom of the box.
Return an n x m matrix representing the box after the rotation described above.
Example 1:
Input: box = [["#",".","#"]]
Output: [["."],
["#"],
["#"]]
Example 2:
Input: box = [["#",".","*","."],
["#","#","*","."]]
Output: [["#","."],
["#","#"],
["*","*"],
[".","."]]
Example 3:
Input: box = [["#","#","*",".","*","."],
["#","#","#","*",".","."],
["#","#","#",".","#","."]]
Output: [[".","#","#"],
[".","#","#"],
["#","#","*"],
["#","*","."],
["#",".","*"],
["#",".","."]]
Constraints:
m == box.length
n == box[i].length
1 <= m, n <= 500
box[i][j] is either '#', '*', or '.'. | [Python] Easy explanation | 1,100 | rotating-the-box | 0.647 | sashaxx | Medium | 26,444 | 1,861 |
sum of floored pairs | class Solution:
def sumOfFlooredPairs(self, nums: List[int]) -> int:
sumP = 0 #To store the value of Sum of floor values
for i in nums: #Traverse every element in nums
for j in nums: #Traverse every element in nums
sumP += (j//i) #Simply do floor division and add the number to sumP
return sumP % (10**9 +7)#return the sumof the pairs | https://leetcode.com/problems/sum-of-floored-pairs/discuss/1218305/PythonPython3-solution-BruteForce-and-Optimized-solution-using-Dictionary | 7 | Given an integer array nums, return the sum of floor(nums[i] / nums[j]) for all pairs of indices 0 <= i, j < nums.length in the array. Since the answer may be too large, return it modulo 109 + 7.
The floor() function returns the integer part of the division.
Example 1:
Input: nums = [2,5,9]
Output: 10
Explanation:
floor(2 / 5) = floor(2 / 9) = floor(5 / 9) = 0
floor(2 / 2) = floor(5 / 5) = floor(9 / 9) = 1
floor(5 / 2) = 2
floor(9 / 2) = 4
floor(9 / 5) = 1
We calculate the floor of the division for every pair of indices in the array then sum them up.
Example 2:
Input: nums = [7,7,7,7,7,7,7]
Output: 49
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 105 | Python/Python3 solution BruteForce & Optimized solution using Dictionary | 279 | sum-of-floored-pairs | 0.282 | prasanthksp1009 | Hard | 26,463 | 1,862 |
sum of all subset xor totals | class Solution:
def subsetXORSum(self, nums: List[int]) -> int:
ans = 0
for mask in range(1 << len(nums)):
val = 0
for i in range(len(nums)):
if mask & 1 << i: val ^= nums[i]
ans += val
return ans | https://leetcode.com/problems/sum-of-all-subset-xor-totals/discuss/1211232/Python3-power-set | 8 | The XOR total of an array is defined as the bitwise XOR of all its elements, or 0 if the array is empty.
For example, the XOR total of the array [2,5,6] is 2 XOR 5 XOR 6 = 1.
Given an array nums, return the sum of all XOR totals for every subset of nums.
Note: Subsets with the same elements should be counted multiple times.
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.
Example 1:
Input: nums = [1,3]
Output: 6
Explanation: The 4 subsets of [1,3] are:
- The empty subset has an XOR total of 0.
- [1] has an XOR total of 1.
- [3] has an XOR total of 3.
- [1,3] has an XOR total of 1 XOR 3 = 2.
0 + 1 + 3 + 2 = 6
Example 2:
Input: nums = [5,1,6]
Output: 28
Explanation: The 8 subsets of [5,1,6] are:
- The empty subset has an XOR total of 0.
- [5] has an XOR total of 5.
- [1] has an XOR total of 1.
- [6] has an XOR total of 6.
- [5,1] has an XOR total of 5 XOR 1 = 4.
- [5,6] has an XOR total of 5 XOR 6 = 3.
- [1,6] has an XOR total of 1 XOR 6 = 7.
- [5,1,6] has an XOR total of 5 XOR 1 XOR 6 = 2.
0 + 5 + 1 + 6 + 4 + 3 + 7 + 2 = 28
Example 3:
Input: nums = [3,4,5,6,7,8]
Output: 480
Explanation: The sum of all XOR totals for every subset is 480.
Constraints:
1 <= nums.length <= 12
1 <= nums[i] <= 20 | [Python3] power set | 1,100 | sum-of-all-subset-xor-totals | 0.79 | ye15 | Easy | 26,466 | 1,863 |
minimum number of swaps to make the binary string alternating | class Solution:
def minSwaps(self, s: str) -> int:
ones = s.count("1")
zeros = len(s) - ones
if abs(ones - zeros) > 1: return -1 # impossible
def fn(x):
"""Return number of swaps if string starts with x."""
ans = 0
for c in s:
if c != x: ans += 1
x = "1" if x == "0" else "0"
return ans//2
if ones > zeros: return fn("1")
elif ones < zeros: return fn("0")
else: return min(fn("0"), fn("1")) | https://leetcode.com/problems/minimum-number-of-swaps-to-make-the-binary-string-alternating/discuss/1211146/Python3-greedy | 23 | Given a binary string s, return the minimum number of character swaps to make it alternating, or -1 if it is impossible.
The string is called alternating if no two adjacent characters are equal. For example, the strings "010" and "1010" are alternating, while the string "0100" is not.
Any two characters may be swapped, even if they are not adjacent.
Example 1:
Input: s = "111000"
Output: 1
Explanation: Swap positions 1 and 4: "111000" -> "101010"
The string is now alternating.
Example 2:
Input: s = "010"
Output: 0
Explanation: The string is already alternating, no swaps are needed.
Example 3:
Input: s = "1110"
Output: -1
Constraints:
1 <= s.length <= 1000
s[i] is either '0' or '1'. | [Python3] greedy | 963 | minimum-number-of-swaps-to-make-the-binary-string-alternating | 0.425 | ye15 | Medium | 26,489 | 1,864 |
number of ways to rearrange sticks with k sticks visible | class Solution:
def rearrangeSticks(self, n: int, k: int) -> int:
@cache
def fn(n, k):
"""Return number of ways to rearrange n sticks to that k are visible."""
if n == k: return 1
if k == 0: return 0
return ((n-1)*fn(n-1, k) + fn(n-1, k-1)) % 1_000_000_007
return fn(n, k) | https://leetcode.com/problems/number-of-ways-to-rearrange-sticks-with-k-sticks-visible/discuss/1211157/Python3-top-down-dp | 4 | There are n uniquely-sized sticks whose lengths are integers from 1 to n. You want to arrange the sticks such that exactly k sticks are visible from the left. A stick is visible from the left if there are no longer sticks to the left of it.
For example, if the sticks are arranged [1,3,2,5,4], then the sticks with lengths 1, 3, and 5 are visible from the left.
Given n and k, return the number of such arrangements. Since the answer may be large, return it modulo 109 + 7.
Example 1:
Input: n = 3, k = 2
Output: 3
Explanation: [1,3,2], [2,3,1], and [2,1,3] are the only arrangements such that exactly 2 sticks are visible.
The visible sticks are underlined.
Example 2:
Input: n = 5, k = 5
Output: 1
Explanation: [1,2,3,4,5] is the only arrangement such that all 5 sticks are visible.
The visible sticks are underlined.
Example 3:
Input: n = 20, k = 11
Output: 647427950
Explanation: There are 647427950 (mod 109 + 7) ways to rearrange the sticks such that exactly 11 sticks are visible.
Constraints:
1 <= n <= 1000
1 <= k <= n | [Python3] top-down dp | 253 | number-of-ways-to-rearrange-sticks-with-k-sticks-visible | 0.558 | ye15 | Hard | 26,498 | 1,866 |
longer contiguous segments of ones than zeros | class Solution:
def checkZeroOnes(self, s: str) -> bool:
zero_in=temp=0
for i in s:
if i=="0":
temp+=1
if temp>zero_in:
zero_in=temp
else:
temp=0
# Longest contiguous 0 in s is zero_in
return "1"*(zero_in+1) in s #return boolean value | https://leetcode.com/problems/longer-contiguous-segments-of-ones-than-zeros/discuss/1261757/Short-O(n)-Solution(python). | 3 | Given a binary string s, return true if the longest contiguous segment of 1's is strictly longer than the longest contiguous segment of 0's in s, or return false otherwise.
For example, in s = "110100010" the longest continuous segment of 1s has length 2, and the longest continuous segment of 0s has length 3.
Note that if there are no 0's, then the longest continuous segment of 0's is considered to have a length 0. The same applies if there is no 1's.
Example 1:
Input: s = "1101"
Output: true
Explanation:
The longest contiguous segment of 1s has length 2: "1101"
The longest contiguous segment of 0s has length 1: "1101"
The segment of 1s is longer, so return true.
Example 2:
Input: s = "111000"
Output: false
Explanation:
The longest contiguous segment of 1s has length 3: "111000"
The longest contiguous segment of 0s has length 3: "111000"
The segment of 1s is not longer, so return false.
Example 3:
Input: s = "110100010"
Output: false
Explanation:
The longest contiguous segment of 1s has length 2: "110100010"
The longest contiguous segment of 0s has length 3: "110100010"
The segment of 1s is not longer, so return false.
Constraints:
1 <= s.length <= 100
s[i] is either '0' or '1'. | Short O(n) Solution(python). | 183 | longer-contiguous-segments-of-ones-than-zeros | 0.603 | _jorjis | Easy | 26,499 | 1,869 |
minimum speed to arrive on time | class Solution:
def minSpeedOnTime(self, dist: List[int], hour: float) -> int:
# the speed upper is either the longest train ride: max(dist),
# or the last train ride divide by 0.01: ceil(dist[-1] / 0.01).
# notice: "hour will have at most two digits after the decimal point"
upper = max(max(dist), ceil(dist[-1] / 0.01))
#
# the function to calcute total time consumed
total = lambda speed: sum(map(lambda x: ceil(x / speed), dist[:-1])) + (dist[-1] / speed)
# the case of impossible to arrive office on time
if total(upper) > hour:
return -1
#
# binary search: find the mimimal among "all" feasible answers
left, right = 1, upper
while left < right:
mid = left + (right - left) // 2
if total(mid) > hour:
left = mid + 1 # should be larger
else:
right = mid # should explore a smaller one
return right | https://leetcode.com/problems/minimum-speed-to-arrive-on-time/discuss/1225585/Python3-Concise-binary-search-code-with-comments | 4 | You are given a floating-point number hour, representing the amount of time you have to reach the office. To commute to the office, you must take n trains in sequential order. You are also given an integer array dist of length n, where dist[i] describes the distance (in kilometers) of the ith train ride.
Each train can only depart at an integer hour, so you may need to wait in between each train ride.
For example, if the 1st train ride takes 1.5 hours, you must wait for an additional 0.5 hours before you can depart on the 2nd train ride at the 2 hour mark.
Return the minimum positive integer speed (in kilometers per hour) that all the trains must travel at for you to reach the office on time, or -1 if it is impossible to be on time.
Tests are generated such that the answer will not exceed 107 and hour will have at most two digits after the decimal point.
Example 1:
Input: dist = [1,3,2], hour = 6
Output: 1
Explanation: At speed 1:
- The first train ride takes 1/1 = 1 hour.
- Since we are already at an integer hour, we depart immediately at the 1 hour mark. The second train takes 3/1 = 3 hours.
- Since we are already at an integer hour, we depart immediately at the 4 hour mark. The third train takes 2/1 = 2 hours.
- You will arrive at exactly the 6 hour mark.
Example 2:
Input: dist = [1,3,2], hour = 2.7
Output: 3
Explanation: At speed 3:
- The first train ride takes 1/3 = 0.33333 hours.
- Since we are not at an integer hour, we wait until the 1 hour mark to depart. The second train ride takes 3/3 = 1 hour.
- Since we are already at an integer hour, we depart immediately at the 2 hour mark. The third train takes 2/3 = 0.66667 hours.
- You will arrive at the 2.66667 hour mark.
Example 3:
Input: dist = [1,3,2], hour = 1.9
Output: -1
Explanation: It is impossible because the earliest the third train can depart is at the 2 hour mark.
Constraints:
n == dist.length
1 <= n <= 105
1 <= dist[i] <= 105
1 <= hour <= 109
There will be at most two digits after the decimal point in hour. | [Python3] Concise binary search code with comments | 322 | minimum-speed-to-arrive-on-time | 0.374 | macroway | Medium | 26,528 | 1,870 |
jump game vii | class Solution:
def canReach(self, s: str, minJump: int, maxJump: int) -> bool:
prefix = [0, 1]
for i in range(1, len(s)):
prefix.append(prefix[-1])
lo = max(0, i-maxJump)
hi = max(0, i-minJump+1)
if s[i] == "0" and prefix[hi] - prefix[lo] > 0: prefix[-1] += 1
return prefix[-1] > prefix[-2] | https://leetcode.com/problems/jump-game-vii/discuss/1224907/Python3-prefix-sum | 3 | You are given a 0-indexed binary string s and two integers minJump and maxJump. In the beginning, you are standing at index 0, which is equal to '0'. You can move from index i to index j if the following conditions are fulfilled:
i + minJump <= j <= min(i + maxJump, s.length - 1), and
s[j] == '0'.
Return true if you can reach index s.length - 1 in s, or false otherwise.
Example 1:
Input: s = "011010", minJump = 2, maxJump = 3
Output: true
Explanation:
In the first step, move from index 0 to index 3.
In the second step, move from index 3 to index 5.
Example 2:
Input: s = "01101110", minJump = 2, maxJump = 3
Output: false
Constraints:
2 <= s.length <= 105
s[i] is either '0' or '1'.
s[0] == '0'
1 <= minJump <= maxJump < s.length | [Python3] prefix sum | 123 | jump-game-vii | 0.251 | ye15 | Medium | 26,539 | 1,871 |
stone game viii | class Solution:
def stoneGameVIII(self, s: List[int]) -> int:
s, res = list(accumulate(s)), 0
for i in range(len(s) - 1, 0, -1):
res = s[i] if i == len(s) - 1 else max(res, s[i] - res)
return res | https://leetcode.com/problems/stone-game-viii/discuss/1224872/Top-Down-and-Bottom-Up | 49 | Alice and Bob take turns playing a game, with Alice starting first.
There are n stones arranged in a row. On each player's turn, while the number of stones is more than one, they will do the following:
Choose an integer x > 1, and remove the leftmost x stones from the row.
Add the sum of the removed stones' values to the player's score.
Place a new stone, whose value is equal to that sum, on the left side of the row.
The game stops when only one stone is left in the row.
The score difference between Alice and Bob is (Alice's score - Bob's score). Alice's goal is to maximize the score difference, and Bob's goal is the minimize the score difference.
Given an integer array stones of length n where stones[i] represents the value of the ith stone from the left, return the score difference between Alice and Bob if they both play optimally.
Example 1:
Input: stones = [-1,2,-3,4,-5]
Output: 5
Explanation:
- Alice removes the first 4 stones, adds (-1) + 2 + (-3) + 4 = 2 to her score, and places a stone of
value 2 on the left. stones = [2,-5].
- Bob removes the first 2 stones, adds 2 + (-5) = -3 to his score, and places a stone of value -3 on
the left. stones = [-3].
The difference between their scores is 2 - (-3) = 5.
Example 2:
Input: stones = [7,-6,5,10,5,-2,-6]
Output: 13
Explanation:
- Alice removes all stones, adds 7 + (-6) + 5 + 10 + 5 + (-2) + (-6) = 13 to her score, and places a
stone of value 13 on the left. stones = [13].
The difference between their scores is 13 - 0 = 13.
Example 3:
Input: stones = [-10,-12]
Output: -22
Explanation:
- Alice can only make one move, which is to remove both stones. She adds (-10) + (-12) = -22 to her
score and places a stone of value -22 on the left. stones = [-22].
The difference between their scores is (-22) - 0 = -22.
Constraints:
n == stones.length
2 <= n <= 105
-104 <= stones[i] <= 104 | Top-Down and Bottom-Up | 2,700 | stone-game-viii | 0.524 | votrubac | Hard | 26,552 | 1,872 |
substrings of size three with distinct characters | class Solution:
def countGoodSubstrings(self, s: str) -> int:
count=0
for i in range(len(s)-2):
if(s[i]!=s[i+1] and s[i]!=s[i+2] and s[i+1]!=s[i+2]):
count+=1
return count | https://leetcode.com/problems/substrings-of-size-three-with-distinct-characters/discuss/1356591/Easy-Python-Solution(98.80) | 13 | A string is good if there are no repeated characters.
Given a string s, return the number of good substrings of length three in s.
Note that if there are multiple occurrences of the same substring, every occurrence should be counted.
A substring is a contiguous sequence of characters in a string.
Example 1:
Input: s = "xyzzaz"
Output: 1
Explanation: There are 4 substrings of size 3: "xyz", "yzz", "zza", and "zaz".
The only good substring of length 3 is "xyz".
Example 2:
Input: s = "aababcabc"
Output: 4
Explanation: There are 7 substrings of size 3: "aab", "aba", "bab", "abc", "bca", "cab", and "abc".
The good substrings are "abc", "bca", "cab", and "abc".
Constraints:
1 <= s.length <= 100
s consists of lowercase English letters. | Easy Python Solution(98.80%) | 878 | substrings-of-size-three-with-distinct-characters | 0.703 | Sneh17029 | Easy | 26,556 | 1,876 |
minimize maximum pair sum in array | class Solution:
def minPairSum(self, nums: List[int]) -> int:
pair_sum = []
nums.sort()
for i in range(len(nums)//2):
pair_sum.append(nums[i]+nums[len(nums)-i-1])
return max(pair_sum) | https://leetcode.com/problems/minimize-maximum-pair-sum-in-array/discuss/2087728/Python-Easy-To-Understand-Code-oror-Beginner-Friendly-oror-Brute-Force | 5 | The pair sum of a pair (a,b) is equal to a + b. The maximum pair sum is the largest pair sum in a list of pairs.
For example, if we have pairs (1,5), (2,3), and (4,4), the maximum pair sum would be max(1+5, 2+3, 4+4) = max(6, 5, 8) = 8.
Given an array nums of even length n, pair up the elements of nums into n / 2 pairs such that:
Each element of nums is in exactly one pair, and
The maximum pair sum is minimized.
Return the minimized maximum pair sum after optimally pairing up the elements.
Example 1:
Input: nums = [3,5,2,3]
Output: 7
Explanation: The elements can be paired up into pairs (3,3) and (5,2).
The maximum pair sum is max(3+3, 5+2) = max(6, 7) = 7.
Example 2:
Input: nums = [3,5,4,2,4,6]
Output: 8
Explanation: The elements can be paired up into pairs (3,5), (4,4), and (6,2).
The maximum pair sum is max(3+5, 4+4, 6+2) = max(8, 8, 8) = 8.
Constraints:
n == nums.length
2 <= n <= 105
n is even.
1 <= nums[i] <= 105 | Python Easy To Understand Code || Beginner Friendly || Brute Force | 207 | minimize-maximum-pair-sum-in-array | 0.803 | Shivam_Raj_Sharma | Medium | 26,606 | 1,877 |
get biggest three rhombus sums in a grid | class Solution:
def getBiggestThree(self, grid: List[List[int]]) -> List[int]:
def calc(l,r,u,d):
sc=0
c1=c2=(l+r)//2
expand=True
for row in range(u,d+1):
if c1==c2:
sc+=grid[row][c1]
else:
sc+=grid[row][c1]+grid[row][c2]
if c1==l:
expand=False
if expand:
c1-=1
c2+=1
else:
c1+=1
c2-=1
return sc
m=len(grid)
n=len(grid[0])
heap=[]
for i in range(m):
for j in range(n):
l=r=j
d=i
while l>=0 and r<=n-1 and d<=m-1:
sc=calc(l,r,i,d)
l-=1
r+=1
d+=2
if len(heap)<3:
if sc not in heap:
heapq.heappush(heap,sc)
else:
if sc not in heap and sc>heap[0]:
heapq.heappop(heap)
heapq.heappush(heap,sc)
heap.sort(reverse=True)
return heap | https://leetcode.com/problems/get-biggest-three-rhombus-sums-in-a-grid/discuss/1239929/python-oror-100-faster-oror-well-explained-oror-Simple-approach | 6 | You are given an m x n integer matrix grid.
A rhombus sum is the sum of the elements that form the border of a regular rhombus shape in grid. The rhombus must have the shape of a square rotated 45 degrees with each of the corners centered in a grid cell. Below is an image of four valid rhombus shapes with the corresponding colored cells that should be included in each rhombus sum:
Note that the rhombus can have an area of 0, which is depicted by the purple rhombus in the bottom right corner.
Return the biggest three distinct rhombus sums in the grid in descending order. If there are less than three distinct values, return all of them.
Example 1:
Input: grid = [[3,4,5,1,3],[3,3,4,2,3],[20,30,200,40,10],[1,5,5,4,1],[4,3,2,2,5]]
Output: [228,216,211]
Explanation: The rhombus shapes for the three biggest distinct rhombus sums are depicted above.
- Blue: 20 + 3 + 200 + 5 = 228
- Red: 200 + 2 + 10 + 4 = 216
- Green: 5 + 200 + 4 + 2 = 211
Example 2:
Input: grid = [[1,2,3],[4,5,6],[7,8,9]]
Output: [20,9,8]
Explanation: The rhombus shapes for the three biggest distinct rhombus sums are depicted above.
- Blue: 4 + 2 + 6 + 8 = 20
- Red: 9 (area 0 rhombus in the bottom right corner)
- Green: 8 (area 0 rhombus in the bottom middle)
Example 3:
Input: grid = [[7,7,7]]
Output: [7]
Explanation: All three possible rhombus sums are the same, so return [7].
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 50
1 <= grid[i][j] <= 105 | ๐ {python} || 100% faster || well-explained || Simple approach | 721 | get-biggest-three-rhombus-sums-in-a-grid | 0.464 | abhi9Rai | Medium | 26,645 | 1,878 |
minimum xor sum of two arrays | class Solution:
def minimumXORSum(self, a: List[int], b: List[int]) -> int:
@cache
def dp(mask: int) -> int:
i = bin(mask).count("1")
if i >= len(a):
return 0
return min((a[i] ^ b[j]) + dp(mask + (1 << j))
for j in range(len(b)) if mask & (1 << j) == 0)
return dp(0) | https://leetcode.com/problems/minimum-xor-sum-of-two-arrays/discuss/1238641/Bit-Mask | 103 | You are given two integer arrays nums1 and nums2 of length n.
The XOR sum of the two integer arrays is (nums1[0] XOR nums2[0]) + (nums1[1] XOR nums2[1]) + ... + (nums1[n - 1] XOR nums2[n - 1]) (0-indexed).
For example, the XOR sum of [1,2,3] and [3,2,1] is equal to (1 XOR 3) + (2 XOR 2) + (3 XOR 1) = 2 + 0 + 2 = 4.
Rearrange the elements of nums2 such that the resulting XOR sum is minimized.
Return the XOR sum after the rearrangement.
Example 1:
Input: nums1 = [1,2], nums2 = [2,3]
Output: 2
Explanation: Rearrange nums2 so that it becomes [3,2].
The XOR sum is (1 XOR 3) + (2 XOR 2) = 2 + 0 = 2.
Example 2:
Input: nums1 = [1,0,3], nums2 = [5,3,4]
Output: 8
Explanation: Rearrange nums2 so that it becomes [5,4,3].
The XOR sum is (1 XOR 5) + (0 XOR 4) + (3 XOR 3) = 4 + 4 + 0 = 8.
Constraints:
n == nums1.length
n == nums2.length
1 <= n <= 14
0 <= nums1[i], nums2[i] <= 107 | Bit Mask | 6,400 | minimum-xor-sum-of-two-arrays | 0.448 | votrubac | Hard | 26,651 | 1,879 |
check if word equals summation of two words | class Solution:
def isSumEqual(self, first: str, second: str, target: str) -> bool:
def op(s: str): return "".join(chr(ord(ch) - 49) for ch in s)
return int(op(first)) + int(op(second)) == int(op(target)) | https://leetcode.com/problems/check-if-word-equals-summation-of-two-words/discuss/1241968/Minus-49 | 18 | The letter value of a letter is its position in the alphabet starting from 0 (i.e. 'a' -> 0, 'b' -> 1, 'c' -> 2, etc.).
The numerical value of some string of lowercase English letters s is the concatenation of the letter values of each letter in s, which is then converted into an integer.
For example, if s = "acb", we concatenate each letter's letter value, resulting in "021". After converting it, we get 21.
You are given three strings firstWord, secondWord, and targetWord, each consisting of lowercase English letters 'a' through 'j' inclusive.
Return true if the summation of the numerical values of firstWord and secondWord equals the numerical value of targetWord, or false otherwise.
Example 1:
Input: firstWord = "acb", secondWord = "cba", targetWord = "cdb"
Output: true
Explanation:
The numerical value of firstWord is "acb" -> "021" -> 21.
The numerical value of secondWord is "cba" -> "210" -> 210.
The numerical value of targetWord is "cdb" -> "231" -> 231.
We return true because 21 + 210 == 231.
Example 2:
Input: firstWord = "aaa", secondWord = "a", targetWord = "aab"
Output: false
Explanation:
The numerical value of firstWord is "aaa" -> "000" -> 0.
The numerical value of secondWord is "a" -> "0" -> 0.
The numerical value of targetWord is "aab" -> "001" -> 1.
We return false because 0 + 0 != 1.
Example 3:
Input: firstWord = "aaa", secondWord = "a", targetWord = "aaaa"
Output: true
Explanation:
The numerical value of firstWord is "aaa" -> "000" -> 0.
The numerical value of secondWord is "a" -> "0" -> 0.
The numerical value of targetWord is "aaaa" -> "0000" -> 0.
We return true because 0 + 0 == 0.
Constraints:
1 <= firstWord.length, secondWord.length, targetWord.length <= 8
firstWord, secondWord, and targetWord consist of lowercase English letters from 'a' to 'j' inclusive. | Minus 49 | 1,200 | check-if-word-equals-summation-of-two-words | 0.738 | votrubac | Easy | 26,653 | 1,880 |
maximum value after insertion | class Solution:
def maxValue(self, n: str, x: int) -> str:
if int(n)>0:
ans = ""
flag = False
for i in range(len(n)):
if int(n[i])>=x:
ans += n[i]
else:
a = n[:i]
b = n[i:]
ans = a+str(x)+b
flag = True
break
if not flag:
ans += str(x)
else:
n = n[1:]
ans = ""
flag = False
for i in range(len(n)):
if int(n[i])<=x:
ans += n[i]
else:
a = n[:i]
b = n[i:]
ans = a+str(x)+b
flag = True
break
if not flag:
ans += str(x)
ans = "-"+ans
return ans | https://leetcode.com/problems/maximum-value-after-insertion/discuss/1240010/Python-oror-simple-O(N)-iteration | 5 | You are given a very large integer n, represented as a string, and an integer digit x. The digits in n and the digit x are in the inclusive range [1, 9], and n may represent a negative number.
You want to maximize n's numerical value by inserting x anywhere in the decimal representation of n. You cannot insert x to the left of the negative sign.
For example, if n = 73 and x = 6, it would be best to insert it between 7 and 3, making n = 763.
If n = -55 and x = 2, it would be best to insert it before the first 5, making n = -255.
Return a string representing the maximum value of n after the insertion.
Example 1:
Input: n = "99", x = 9
Output: "999"
Explanation: The result is the same regardless of where you insert 9.
Example 2:
Input: n = "-13", x = 2
Output: "-123"
Explanation: You can make n one of {-213, -123, -132}, and the largest of those three is -123.
Constraints:
1 <= n.length <= 105
1 <= x <= 9
The digits in n are in the range [1, 9].
n is a valid representation of an integer.
In the case of a negative n, it will begin with '-'. | Python || simple O(N) iteration | 536 | maximum-value-after-insertion | 0.366 | harshhx | Medium | 26,701 | 1,881 |
process tasks using servers | class Solution:
def assignTasks(self, servers: List[int], tasks: List[int]) -> List[int]:
# sort the servers in order of weight, keeping index
server_avail = [(w,i) for i,w in enumerate(servers)]
heapify(server_avail)
tasks_in_progress = []
res = []
st=0
for j,task in enumerate(tasks):
#starting time of task
st = max(st,j)
# if any server is not free then we can take start-time equal to end-time of task
if not server_avail:
st = tasks_in_progress[0][0]
# pop the completed task's server and push inside the server avail
while tasks_in_progress and tasks_in_progress[0][0]<=st:
heapq.heappush(server_avail,heappop(tasks_in_progress)[1])
# append index of used server in res
res.append(server_avail[0][1])
# push the first available server in "server_avail" heap to "tasks_in_progress" heap
heapq.heappush(tasks_in_progress,(st+task,heappop(server_avail)))
return res | https://leetcode.com/problems/process-tasks-using-servers/discuss/1240147/Python-oror-Heap-oror-O(n%2Bmlogn)-oror-easy-and-well-explained | 5 | You are given two 0-indexed integer arrays servers and tasks of lengths n and m respectively. servers[i] is the weight of the ith server, and tasks[j] is the time needed to process the jth task in seconds.
Tasks are assigned to the servers using a task queue. Initially, all servers are free, and the queue is empty.
At second j, the jth task is inserted into the queue (starting with the 0th task being inserted at second 0). As long as there are free servers and the queue is not empty, the task in the front of the queue will be assigned to a free server with the smallest weight, and in case of a tie, it is assigned to a free server with the smallest index.
If there are no free servers and the queue is not empty, we wait until a server becomes free and immediately assign the next task. If multiple servers become free at the same time, then multiple tasks from the queue will be assigned in order of insertion following the weight and index priorities above.
A server that is assigned task j at second t will be free again at second t + tasks[j].
Build an array ans of length m, where ans[j] is the index of the server the jth task will be assigned to.
Return the array ans.
Example 1:
Input: servers = [3,3,2], tasks = [1,2,3,2,1,2]
Output: [2,2,0,2,1,2]
Explanation: Events in chronological order go as follows:
- At second 0, task 0 is added and processed using server 2 until second 1.
- At second 1, server 2 becomes free. Task 1 is added and processed using server 2 until second 3.
- At second 2, task 2 is added and processed using server 0 until second 5.
- At second 3, server 2 becomes free. Task 3 is added and processed using server 2 until second 5.
- At second 4, task 4 is added and processed using server 1 until second 5.
- At second 5, all servers become free. Task 5 is added and processed using server 2 until second 7.
Example 2:
Input: servers = [5,1,4,3,2], tasks = [2,1,2,4,5,2,1]
Output: [1,4,1,4,1,3,2]
Explanation: Events in chronological order go as follows:
- At second 0, task 0 is added and processed using server 1 until second 2.
- At second 1, task 1 is added and processed using server 4 until second 2.
- At second 2, servers 1 and 4 become free. Task 2 is added and processed using server 1 until second 4.
- At second 3, task 3 is added and processed using server 4 until second 7.
- At second 4, server 1 becomes free. Task 4 is added and processed using server 1 until second 9.
- At second 5, task 5 is added and processed using server 3 until second 7.
- At second 6, task 6 is added and processed using server 2 until second 7.
Constraints:
servers.length == n
tasks.length == m
1 <= n, m <= 2 * 105
1 <= servers[i], tasks[j] <= 2 * 105 | ๐ {Python} || Heap || O(n+mlogn) || easy and well-explained | 227 | process-tasks-using-servers | 0.396 | abhi9Rai | Medium | 26,712 | 1,882 |
minimum skips to arrive at meeting on time | class Solution:
def minSkips(self, dist: List[int], speed: int, hoursBefore: int) -> int:
if sum(dist)/speed > hoursBefore: return -1 # impossible
@cache
def fn(i, k):
"""Return min time (in distance) of traveling first i roads with k skips."""
if k < 0: return inf # impossible
if i == 0: return 0
return min(ceil((fn(i-1, k) + dist[i-1])/speed) * speed, dist[i-1] + fn(i-1, k-1))
for k in range(len(dist)):
if fn(len(dist)-1, k) + dist[-1] <= hoursBefore*speed: return k | https://leetcode.com/problems/minimum-skips-to-arrive-at-meeting-on-time/discuss/1242138/Python3-top-down-dp | 1 | You are given an integer hoursBefore, the number of hours you have to travel to your meeting. To arrive at your meeting, you have to travel through n roads. The road lengths are given as an integer array dist of length n, where dist[i] describes the length of the ith road in kilometers. In addition, you are given an integer speed, which is the speed (in km/h) you will travel at.
After you travel road i, you must rest and wait for the next integer hour before you can begin traveling on the next road. Note that you do not have to rest after traveling the last road because you are already at the meeting.
For example, if traveling a road takes 1.4 hours, you must wait until the 2 hour mark before traveling the next road. If traveling a road takes exactly 2 hours, you do not need to wait.
However, you are allowed to skip some rests to be able to arrive on time, meaning you do not need to wait for the next integer hour. Note that this means you may finish traveling future roads at different hour marks.
For example, suppose traveling the first road takes 1.4 hours and traveling the second road takes 0.6 hours. Skipping the rest after the first road will mean you finish traveling the second road right at the 2 hour mark, letting you start traveling the third road immediately.
Return the minimum number of skips required to arrive at the meeting on time, or -1 if it is impossible.
Example 1:
Input: dist = [1,3,2], speed = 4, hoursBefore = 2
Output: 1
Explanation:
Without skipping any rests, you will arrive in (1/4 + 3/4) + (3/4 + 1/4) + (2/4) = 2.5 hours.
You can skip the first rest to arrive in ((1/4 + 0) + (3/4 + 0)) + (2/4) = 1.5 hours.
Note that the second rest is shortened because you finish traveling the second road at an integer hour due to skipping the first rest.
Example 2:
Input: dist = [7,3,5,5], speed = 2, hoursBefore = 10
Output: 2
Explanation:
Without skipping any rests, you will arrive in (7/2 + 1/2) + (3/2 + 1/2) + (5/2 + 1/2) + (5/2) = 11.5 hours.
You can skip the first and third rest to arrive in ((7/2 + 0) + (3/2 + 0)) + ((5/2 + 0) + (5/2)) = 10 hours.
Example 3:
Input: dist = [7,3,5,5], speed = 1, hoursBefore = 10
Output: -1
Explanation: It is impossible to arrive at the meeting on time even if you skip all the rests.
Constraints:
n == dist.length
1 <= n <= 1000
1 <= dist[i] <= 105
1 <= speed <= 106
1 <= hoursBefore <= 107 | [Python3] top-down dp | 59 | minimum-skips-to-arrive-at-meeting-on-time | 0.385 | ye15 | Hard | 26,719 | 1,883 |
egg drop with 2 eggs and n floors | class Solution:
@cache
def twoEggDrop(self, n: int) -> int:
return min((1 + max(i - 1, self.twoEggDrop(n - i)) for i in range (1, n)), default = 1) | https://leetcode.com/problems/egg-drop-with-2-eggs-and-n-floors/discuss/1248069/Recursive-Iterative-Generic | 194 | You are given two identical eggs and you have access to a building with n floors labeled from 1 to n.
You know that there exists a floor f where 0 <= f <= n such that any egg dropped at a floor higher than f will break, and any egg dropped at or below floor f will not break.
In each move, you may take an unbroken egg and drop it from any floor x (where 1 <= x <= n). If the egg breaks, you can no longer use it. However, if the egg does not break, you may reuse it in future moves.
Return the minimum number of moves that you need to determine with certainty what the value of f is.
Example 1:
Input: n = 2
Output: 2
Explanation: We can drop the first egg from floor 1 and the second egg from floor 2.
If the first egg breaks, we know that f = 0.
If the second egg breaks but the first egg didn't, we know that f = 1.
Otherwise, if both eggs survive, we know that f = 2.
Example 2:
Input: n = 100
Output: 14
Explanation: One optimal strategy is:
- Drop the 1st egg at floor 9. If it breaks, we know f is between 0 and 8. Drop the 2nd egg starting from floor 1 and going up one at a time to find f within 8 more drops. Total drops is 1 + 8 = 9.
- If the 1st egg does not break, drop the 1st egg again at floor 22. If it breaks, we know f is between 9 and 21. Drop the 2nd egg starting from floor 10 and going up one at a time to find f within 12 more drops. Total drops is 2 + 12 = 14.
- If the 1st egg does not break again, follow a similar process dropping the 1st egg from floors 34, 45, 55, 64, 72, 79, 85, 90, 94, 97, 99, and 100.
Regardless of the outcome, it takes at most 14 drops to determine f.
Constraints:
1 <= n <= 1000 | Recursive, Iterative, Generic | 11,600 | egg-drop-with-2-eggs-and-n-floors | 0.703 | votrubac | Medium | 26,720 | 1,884 |
determine whether matrix can be obtained by rotation | class Solution:
def findRotation(self, mat: List[List[int]], target: List[List[int]]) -> bool:
for _ in range(4):
if mat == target: return True
mat = [list(x) for x in zip(*mat[::-1])]
return False | https://leetcode.com/problems/determine-whether-matrix-can-be-obtained-by-rotation/discuss/1253880/Python3-rotate-matrix | 86 | Given two n x n binary matrices mat and target, return true if it is possible to make mat equal to target by rotating mat in 90-degree increments, or false otherwise.
Example 1:
Input: mat = [[0,1],[1,0]], target = [[1,0],[0,1]]
Output: true
Explanation: We can rotate mat 90 degrees clockwise to make mat equal target.
Example 2:
Input: mat = [[0,1],[1,1]], target = [[1,0],[0,1]]
Output: false
Explanation: It is impossible to make mat equal to target by rotating mat.
Example 3:
Input: mat = [[0,0,0],[0,1,0],[1,1,1]], target = [[1,1,1],[0,1,0],[0,0,0]]
Output: true
Explanation: We can rotate mat 90 degrees clockwise two times to make mat equal target.
Constraints:
n == mat.length == target.length
n == mat[i].length == target[i].length
1 <= n <= 10
mat[i][j] and target[i][j] are either 0 or 1. | [Python3] rotate matrix | 4,800 | determine-whether-matrix-can-be-obtained-by-rotation | 0.554 | ye15 | Easy | 26,734 | 1,886 |
reduction operations to make the array elements equal | class Solution:
def reductionOperations(self, nums: List[int]) -> int:
ans = val = 0
nums.sort()
for i in range(1, len(nums)):
if nums[i-1] < nums[i]: val += 1
ans += val
return ans | https://leetcode.com/problems/reduction-operations-to-make-the-array-elements-equal/discuss/1253889/Python3-greedy | 20 | Given an integer array nums, your goal is to make all elements in nums equal. To complete one operation, follow these steps:
Find the largest value in nums. Let its index be i (0-indexed) and its value be largest. If there are multiple elements with the largest value, pick the smallest i.
Find the next largest value in nums strictly smaller than largest. Let its value be nextLargest.
Reduce nums[i] to nextLargest.
Return the number of operations to make all elements in nums equal.
Example 1:
Input: nums = [5,1,3]
Output: 3
Explanation: It takes 3 operations to make all elements in nums equal:
1. largest = 5 at index 0. nextLargest = 3. Reduce nums[0] to 3. nums = [3,1,3].
2. largest = 3 at index 0. nextLargest = 1. Reduce nums[0] to 1. nums = [1,1,3].
3. largest = 3 at index 2. nextLargest = 1. Reduce nums[2] to 1. nums = [1,1,1].
Example 2:
Input: nums = [1,1,1]
Output: 0
Explanation: All elements in nums are already equal.
Example 3:
Input: nums = [1,1,2,2,3]
Output: 4
Explanation: It takes 4 operations to make all elements in nums equal:
1. largest = 3 at index 4. nextLargest = 2. Reduce nums[4] to 2. nums = [1,1,2,2,2].
2. largest = 2 at index 2. nextLargest = 1. Reduce nums[2] to 1. nums = [1,1,1,2,2].
3. largest = 2 at index 3. nextLargest = 1. Reduce nums[3] to 1. nums = [1,1,1,1,2].
4. largest = 2 at index 4. nextLargest = 1. Reduce nums[4] to 1. nums = [1,1,1,1,1].
Constraints:
1 <= nums.length <= 5 * 104
1 <= nums[i] <= 5 * 104 | [Python3] greedy | 963 | reduction-operations-to-make-the-array-elements-equal | 0.624 | ye15 | Medium | 26,759 | 1,887 |
minimum number of flips to make the binary string alternating | class Solution:
def minFlips(self, s: str) -> int:
prev = 0
start_1, start_0, start_1_odd, start_0_odd = 0,0,sys.maxsize,sys.maxsize
odd = len(s)%2
for val in s:
val = int(val)
if val == prev:
if odd:
start_0_odd = min(start_0_odd, start_1)
start_1_odd += 1
start_1 += 1
else:
if odd:
start_1_odd = min(start_1_odd, start_0)
start_0_odd += 1
start_0 += 1
prev = 1 - prev
return min([start_1, start_0, start_1_odd, start_0_odd]) | https://leetcode.com/problems/minimum-number-of-flips-to-make-the-binary-string-alternating/discuss/1259837/Python-Simple-DP-(beats-99.52) | 6 | You are given a binary string s. You are allowed to perform two types of operations on the string in any sequence:
Type-1: Remove the character at the start of the string s and append it to the end of the string.
Type-2: Pick any character in s and flip its value, i.e., if its value is '0' it becomes '1' and vice-versa.
Return the minimum number of type-2 operations you need to perform such that s becomes alternating.
The string is called alternating if no two adjacent characters are equal.
For example, the strings "010" and "1010" are alternating, while the string "0100" is not.
Example 1:
Input: s = "111000"
Output: 2
Explanation: Use the first operation two times to make s = "100011".
Then, use the second operation on the third and sixth elements to make s = "101010".
Example 2:
Input: s = "010"
Output: 0
Explanation: The string is already alternating.
Example 3:
Input: s = "1110"
Output: 1
Explanation: Use the second operation on the second element to make s = "1010".
Constraints:
1 <= s.length <= 105
s[i] is either '0' or '1'. | [Python] Simple DP (beats 99.52%) | 640 | minimum-number-of-flips-to-make-the-binary-string-alternating | 0.381 | cloverpku | Medium | 26,771 | 1,888 |
minimum space wasted from packaging | class Solution:
def minWastedSpace(self, packages: List[int], boxes: List[List[int]]) -> int:
packages.sort()
prefix = [0]
for x in packages: prefix.append(prefix[-1] + x)
ans = inf
for box in boxes:
box.sort()
if packages[-1] <= box[-1]:
kk = val = 0
for x in box:
k = bisect_right(packages, x)
val += (k - kk) * x - (prefix[k] - prefix[kk])
kk = k
ans = min(ans, val)
return ans % 1_000_000_007 if ans < inf else -1 | https://leetcode.com/problems/minimum-space-wasted-from-packaging/discuss/1253918/Python3-prefix-sum-and-binary-search | 5 | You have n packages that you are trying to place in boxes, one package in each box. There are m suppliers that each produce boxes of different sizes (with infinite supply). A package can be placed in a box if the size of the package is less than or equal to the size of the box.
The package sizes are given as an integer array packages, where packages[i] is the size of the ith package. The suppliers are given as a 2D integer array boxes, where boxes[j] is an array of box sizes that the jth supplier produces.
You want to choose a single supplier and use boxes from them such that the total wasted space is minimized. For each package in a box, we define the space wasted to be size of the box - size of the package. The total wasted space is the sum of the space wasted in all the boxes.
For example, if you have to fit packages with sizes [2,3,5] and the supplier offers boxes of sizes [4,8], you can fit the packages of size-2 and size-3 into two boxes of size-4 and the package with size-5 into a box of size-8. This would result in a waste of (4-2) + (4-3) + (8-5) = 6.
Return the minimum total wasted space by choosing the box supplier optimally, or -1 if it is impossible to fit all the packages inside boxes. Since the answer may be large, return it modulo 109 + 7.
Example 1:
Input: packages = [2,3,5], boxes = [[4,8],[2,8]]
Output: 6
Explanation: It is optimal to choose the first supplier, using two size-4 boxes and one size-8 box.
The total waste is (4-2) + (4-3) + (8-5) = 6.
Example 2:
Input: packages = [2,3,5], boxes = [[1,4],[2,3],[3,4]]
Output: -1
Explanation: There is no box that the package of size 5 can fit in.
Example 3:
Input: packages = [3,5,8,10,11,12], boxes = [[12],[11,9],[10,5,14]]
Output: 9
Explanation: It is optimal to choose the third supplier, using two size-5 boxes, two size-10 boxes, and two size-14 boxes.
The total waste is (5-3) + (5-5) + (10-8) + (10-10) + (14-11) + (14-12) = 9.
Constraints:
n == packages.length
m == boxes.length
1 <= n <= 105
1 <= m <= 105
1 <= packages[i] <= 105
1 <= boxes[j].length <= 105
1 <= boxes[j][k] <= 105
sum(boxes[j].length) <= 105
The elements in boxes[j] are distinct. | [Python3] prefix sum & binary search | 330 | minimum-space-wasted-from-packaging | 0.307 | ye15 | Hard | 26,780 | 1,889 |
check if all the integers in a range are covered | class Solution:
def isCovered(self, ranges: List[List[int]], left: int, right: int) -> bool:
ranges = sorted(ranges)
for s,e in ranges:
if s<=left<=e:
if s<=right<=e:
return True
else:
left=e+1
return False | https://leetcode.com/problems/check-if-all-the-integers-in-a-range-are-covered/discuss/1444310/PYTHON3-Noob-Friendly-Easy-inuitive-naturally-occuring-solution | 2 | You are given a 2D integer array ranges and two integers left and right. Each ranges[i] = [starti, endi] represents an inclusive interval between starti and endi.
Return true if each integer in the inclusive range [left, right] is covered by at least one interval in ranges. Return false otherwise.
An integer x is covered by an interval ranges[i] = [starti, endi] if starti <= x <= endi.
Example 1:
Input: ranges = [[1,2],[3,4],[5,6]], left = 2, right = 5
Output: true
Explanation: Every integer between 2 and 5 is covered:
- 2 is covered by the first range.
- 3 and 4 are covered by the second range.
- 5 is covered by the third range.
Example 2:
Input: ranges = [[1,10],[10,20]], left = 21, right = 21
Output: false
Explanation: 21 is not covered by any range.
Constraints:
1 <= ranges.length <= 50
1 <= starti <= endi <= 50
1 <= left <= right <= 50 | PYTHON3- Noob Friendly Easy inuitive naturally occuring solution | 138 | check-if-all-the-integers-in-a-range-are-covered | 0.508 | mathur17021play | Easy | 26,783 | 1,893 |
find the student that will replace the chalk | class Solution:
def chalkReplacer(self, chalk: List[int], k: int) -> int:
prefix_sum = [0 for i in range(len(chalk))]
prefix_sum[0] = chalk[0]
for i in range(1,len(chalk)):
prefix_sum[i] = prefix_sum[i-1] + chalk[i]
remainder = k % prefix_sum[-1]
#apply binary search on prefix_sum array, target = remainder
start = 0
end = len(prefix_sum) - 1
while start <= end:
mid = start + (end - start) // 2
if remainder == prefix_sum[mid]:
return mid + 1
elif remainder < prefix_sum[mid]:
end = mid - 1
else:
start = mid + 1
return start | https://leetcode.com/problems/find-the-student-that-will-replace-the-chalk/discuss/1612394/Python-oror-Prefix-Sum-and-Binary-Search-oror-O(n)-time-O(n)-space | 4 | There are n students in a class numbered from 0 to n - 1. The teacher will give each student a problem starting with the student number 0, then the student number 1, and so on until the teacher reaches the student number n - 1. After that, the teacher will restart the process, starting with the student number 0 again.
You are given a 0-indexed integer array chalk and an integer k. There are initially k pieces of chalk. When the student number i is given a problem to solve, they will use chalk[i] pieces of chalk to solve that problem. However, if the current number of chalk pieces is strictly less than chalk[i], then the student number i will be asked to replace the chalk.
Return the index of the student that will replace the chalk pieces.
Example 1:
Input: chalk = [5,1,5], k = 22
Output: 0
Explanation: The students go in turns as follows:
- Student number 0 uses 5 chalk, so k = 17.
- Student number 1 uses 1 chalk, so k = 16.
- Student number 2 uses 5 chalk, so k = 11.
- Student number 0 uses 5 chalk, so k = 6.
- Student number 1 uses 1 chalk, so k = 5.
- Student number 2 uses 5 chalk, so k = 0.
Student number 0 does not have enough chalk, so they will have to replace it.
Example 2:
Input: chalk = [3,4,1,2], k = 25
Output: 1
Explanation: The students go in turns as follows:
- Student number 0 uses 3 chalk so k = 22.
- Student number 1 uses 4 chalk so k = 18.
- Student number 2 uses 1 chalk so k = 17.
- Student number 3 uses 2 chalk so k = 15.
- Student number 0 uses 3 chalk so k = 12.
- Student number 1 uses 4 chalk so k = 8.
- Student number 2 uses 1 chalk so k = 7.
- Student number 3 uses 2 chalk so k = 5.
- Student number 0 uses 3 chalk so k = 2.
Student number 1 does not have enough chalk, so they will have to replace it.
Constraints:
chalk.length == n
1 <= n <= 105
1 <= chalk[i] <= 105
1 <= k <= 109 | Python || Prefix Sum and Binary Search || O(n) time O(n) space | 244 | find-the-student-that-will-replace-the-chalk | 0.438 | s_m_d_29 | Medium | 26,806 | 1,894 |
largest magic square | class Solution:
def largestMagicSquare(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0]) # dimensions
rows = [[0]*(n+1) for _ in range(m)] # prefix sum along row
cols = [[0]*n for _ in range(m+1)] # prefix sum along column
for i in range(m):
for j in range(n):
rows[i][j+1] = grid[i][j] + rows[i][j]
cols[i+1][j] = grid[i][j] + cols[i][j]
ans = 1
for i in range(m):
for j in range(n):
diag = grid[i][j]
for k in range(min(i, j)):
ii, jj = i-k-1, j-k-1
diag += grid[ii][jj]
ss = {diag}
for r in range(ii, i+1): ss.add(rows[r][j+1] - rows[r][jj])
for c in range(jj, j+1): ss.add(cols[i+1][c] - cols[ii][c])
ss.add(sum(grid[ii+kk][j-kk] for kk in range(k+2))) # anti-diagonal
if len(ss) == 1: ans = max(ans, k+2)
return ans | https://leetcode.com/problems/largest-magic-square/discuss/1267452/Python3-prefix-sums | 6 | A k x k magic square is a k x k grid filled with integers such that every row sum, every column sum, and both diagonal sums are all equal. The integers in the magic square do not have to be distinct. Every 1 x 1 grid is trivially a magic square.
Given an m x n integer grid, return the size (i.e., the side length k) of the largest magic square that can be found within this grid.
Example 1:
Input: grid = [[7,1,4,5,6],[2,5,1,6,4],[1,5,4,3,2],[1,2,7,3,4]]
Output: 3
Explanation: The largest magic square has a size of 3.
Every row sum, column sum, and diagonal sum of this magic square is equal to 12.
- Row sums: 5+1+6 = 5+4+3 = 2+7+3 = 12
- Column sums: 5+5+2 = 1+4+7 = 6+3+3 = 12
- Diagonal sums: 5+4+3 = 6+4+2 = 12
Example 2:
Input: grid = [[5,1,3,1],[9,3,3,1],[1,3,3,8]]
Output: 2
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 50
1 <= grid[i][j] <= 106 | [Python3] prefix sums | 449 | largest-magic-square | 0.519 | ye15 | Medium | 26,821 | 1,895 |
minimum cost to change the final value of expression | class Solution:
def minOperationsToFlip(self, expression: str) -> int:
loc = {}
stack = []
for i in reversed(range(len(expression))):
if expression[i] == ")": stack.append(i)
elif expression[i] == "(": loc[stack.pop()] = i
def fn(lo, hi):
"""Return value and min op to change value."""
if lo == hi: return int(expression[lo]), 1
if expression[hi] == ")" and loc[hi] == lo: return fn(lo+1, hi-1) # strip parenthesis
mid = loc.get(hi, hi) - 1
v, c = fn(mid+1, hi)
vv, cc = fn(lo, mid-1)
if expression[mid] == "|":
val = v | vv
if v == vv == 0: chg = min(c, cc)
elif v == vv == 1: chg = 1 + min(c, cc)
else: chg = 1
else: # expression[k] == "&"
val = v & vv
if v == vv == 0: chg = 1 + min(c, cc)
elif v == vv == 1: chg = min(c, cc)
else: chg = 1
return val, chg
return fn(0, len(expression)-1)[1] | https://leetcode.com/problems/minimum-cost-to-change-the-final-value-of-expression/discuss/1272620/Python3-divide-and-conquer | 0 | You are given a valid boolean expression as a string expression consisting of the characters '1','0','&' (bitwise AND operator),'|' (bitwise OR operator),'(', and ')'.
For example, "()1|1" and "(1)&()" are not valid while "1", "(((1))|(0))", and "1|(0&(1))" are valid expressions.
Return the minimum cost to change the final value of the expression.
For example, if expression = "1|1|(0&0)&1", its value is 1|1|(0&0)&1 = 1|1|0&1 = 1|0&1 = 1&1 = 1. We want to apply operations so that the new expression evaluates to 0.
The cost of changing the final value of an expression is the number of operations performed on the expression. The types of operations are described as follows:
Turn a '1' into a '0'.
Turn a '0' into a '1'.
Turn a '&' into a '|'.
Turn a '|' into a '&'.
Note: '&' does not take precedence over '|' in the order of calculation. Evaluate parentheses first, then in left-to-right order.
Example 1:
Input: expression = "1&(0|1)"
Output: 1
Explanation: We can turn "1&(0|1)" into "1&(0&1)" by changing the '|' to a '&' using 1 operation.
The new expression evaluates to 0.
Example 2:
Input: expression = "(0&0)&(0&0&0)"
Output: 3
Explanation: We can turn "(0&0)&(0&0&0)" into "(0|1)|(0&0&0)" using 3 operations.
The new expression evaluates to 1.
Example 3:
Input: expression = "(0|(1|0&1))"
Output: 1
Explanation: We can turn "(0|(1|0&1))" into "(0|(0|0&1))" using 1 operation.
The new expression evaluates to 0.
Constraints:
1 <= expression.length <= 105
expression only contains '1','0','&','|','(', and ')'
All parentheses are properly matched.
There will be no empty parentheses (i.e: "()" is not a substring of expression). | [Python3] divide & conquer | 57 | minimum-cost-to-change-the-final-value-of-expression | 0.548 | ye15 | Hard | 26,827 | 1,896 |
redistribute characters to make all strings equal | class Solution:
def makeEqual(self, words: List[str]) -> bool:
map_ = {}
for word in words:
for i in word:
if i not in map_:
map_[i] = 1
else:
map_[i] += 1
n = len(words)
for k,v in map_.items():
if (v%n) != 0:
return False
return True | https://leetcode.com/problems/redistribute-characters-to-make-all-strings-equal/discuss/1268522/Python-or-dictionary | 14 | You are given an array of strings words (0-indexed).
In one operation, pick two distinct indices i and j, where words[i] is a non-empty string, and move any character from words[i] to any position in words[j].
Return true if you can make every string in words equal using any number of operations, and false otherwise.
Example 1:
Input: words = ["abc","aabc","bc"]
Output: true
Explanation: Move the first 'a' in words[1] to the front of words[2],
to make words[1] = "abc" and words[2] = "abc".
All the strings are now equal to "abc", so return true.
Example 2:
Input: words = ["ab","a"]
Output: false
Explanation: It is impossible to make all the strings equal using the operation.
Constraints:
1 <= words.length <= 100
1 <= words[i].length <= 100
words[i] consists of lowercase English letters. | Python | dictionary | 1,200 | redistribute-characters-to-make-all-strings-equal | 0.599 | harshhx | Easy | 26,828 | 1,897 |
maximum number of removable characters | class Solution:
def maximumRemovals(self, s: str, p: str, removable: List[int]) -> int:
mp = {x: i for i, x in enumerate(removable)}
def fn(x):
"""Return True if p is a subseq of s after x removals."""
k = 0
for i, ch in enumerate(s):
if mp.get(i, inf) < x: continue
if k < len(p) and ch == p[k]: k += 1
return k == len(p)
lo, hi = -1, len(removable)
while lo < hi:
mid = lo + hi + 1 >> 1
if fn(mid): lo = mid
else: hi = mid - 1
return lo | https://leetcode.com/problems/maximum-number-of-removable-characters/discuss/1268727/Python3-binary-search | 10 | You are given two strings s and p where p is a subsequence of s. You are also given a distinct 0-indexed integer array removable containing a subset of indices of s (s is also 0-indexed).
You want to choose an integer k (0 <= k <= removable.length) such that, after removing k characters from s using the first k indices in removable, p is still a subsequence of s. More formally, you will mark the character at s[removable[i]] for each 0 <= i < k, then remove all marked characters and check if p is still a subsequence.
Return the maximum k you can choose such that p is still a subsequence of s after the removals.
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.
Example 1:
Input: s = "abcacb", p = "ab", removable = [3,1,0]
Output: 2
Explanation: After removing the characters at indices 3 and 1, "abcacb" becomes "accb".
"ab" is a subsequence of "accb".
If we remove the characters at indices 3, 1, and 0, "abcacb" becomes "ccb", and "ab" is no longer a subsequence.
Hence, the maximum k is 2.
Example 2:
Input: s = "abcbddddd", p = "abcd", removable = [3,2,1,4,5,6]
Output: 1
Explanation: After removing the character at index 3, "abcbddddd" becomes "abcddddd".
"abcd" is a subsequence of "abcddddd".
Example 3:
Input: s = "abcab", p = "abc", removable = [0,1,2,3,4]
Output: 0
Explanation: If you remove the first index in the array removable, "abc" is no longer a subsequence.
Constraints:
1 <= p.length <= s.length <= 105
0 <= removable.length < s.length
0 <= removable[i] < s.length
p is a subsequence of s.
s and p both consist of lowercase English letters.
The elements in removable are distinct. | [Python3] binary search | 467 | maximum-number-of-removable-characters | 0.393 | ye15 | Medium | 26,852 | 1,898 |
merge triplets to form target triplet | class Solution:
def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:
i = 1
cur = []
for a,b,c in triplets:
if a<=target[0] and b<=target[1] and c<= target[2]:
cur = [a,b,c]
break
if not cur:
return False
while i<len(triplets):
if cur == target:
return True
a,b,c = triplets[i]
x,y,z = cur
if max(a,x)<=target[0] and max(b,y)<=target[1] and max(c,z)<=target[2]:
cur = [max(a,x), max(b,y), max(c,z)]
i+= 1
if cur == target:
return True
return False | https://leetcode.com/problems/merge-triplets-to-form-target-triplet/discuss/1268491/python-or-implementation-O(N) | 4 | A triplet is an array of three integers. You are given a 2D integer array triplets, where triplets[i] = [ai, bi, ci] describes the ith triplet. You are also given an integer array target = [x, y, z] that describes the triplet you want to obtain.
To obtain target, you may apply the following operation on triplets any number of times (possibly zero):
Choose two indices (0-indexed) i and j (i != j) and update triplets[j] to become [max(ai, aj), max(bi, bj), max(ci, cj)].
For example, if triplets[i] = [2, 5, 3] and triplets[j] = [1, 7, 5], triplets[j] will be updated to [max(2, 1), max(5, 7), max(3, 5)] = [2, 7, 5].
Return true if it is possible to obtain the target triplet [x, y, z] as an element of triplets, or false otherwise.
Example 1:
Input: triplets = [[2,5,3],[1,8,4],[1,7,5]], target = [2,7,5]
Output: true
Explanation: Perform the following operations:
- Choose the first and last triplets [[2,5,3],[1,8,4],[1,7,5]]. Update the last triplet to be [max(2,1), max(5,7), max(3,5)] = [2,7,5]. triplets = [[2,5,3],[1,8,4],[2,7,5]]
The target triplet [2,7,5] is now an element of triplets.
Example 2:
Input: triplets = [[3,4,5],[4,5,6]], target = [3,2,5]
Output: false
Explanation: It is impossible to have [3,2,5] as an element because there is no 2 in any of the triplets.
Example 3:
Input: triplets = [[2,5,3],[2,3,4],[1,2,5],[5,2,3]], target = [5,5,5]
Output: true
Explanation: Perform the following operations:
- Choose the first and third triplets [[2,5,3],[2,3,4],[1,2,5],[5,2,3]]. Update the third triplet to be [max(2,1), max(5,2), max(3,5)] = [2,5,5]. triplets = [[2,5,3],[2,3,4],[2,5,5],[5,2,3]].
- Choose the third and fourth triplets [[2,5,3],[2,3,4],[2,5,5],[5,2,3]]. Update the fourth triplet to be [max(2,5), max(5,2), max(5,3)] = [5,5,5]. triplets = [[2,5,3],[2,3,4],[2,5,5],[5,5,5]].
The target triplet [5,5,5] is now an element of triplets.
Constraints:
1 <= triplets.length <= 105
triplets[i].length == target.length == 3
1 <= ai, bi, ci, x, y, z <= 1000 | python | implementation O(N) | 234 | merge-triplets-to-form-target-triplet | 0.644 | harshhx | Medium | 26,862 | 1,899 |
the earliest and latest rounds where players compete | class Solution:
def earliestAndLatest(self, n: int, firstPlayer: int, secondPlayer: int) -> List[int]:
firstPlayer, secondPlayer = firstPlayer-1, secondPlayer-1 # 0-indexed
@cache
def fn(k, mask):
"""Return earliest and latest rounds."""
can = deque()
for i in range(n):
if mask & (1 << i): can.append(i)
cand = [] # eliminated player
while len(can) > 1:
p1, p2 = can.popleft(), can.pop()
if p1 == firstPlayer and p2 == secondPlayer or p1 == secondPlayer and p2 == firstPlayer: return [k, k] # game of interest
if p1 in (firstPlayer, secondPlayer): cand.append([p2]) # p2 eliminated
elif p2 in (firstPlayer, secondPlayer): cand.append([p1]) # p1 eliminated
else: cand.append([p1, p2]) # both could be elimited
minn, maxx = inf, -inf
for x in product(*cand):
mask0 = mask
for i in x: mask0 ^= 1 << i
mn, mx = fn(k+1, mask0)
minn = min(minn, mn)
maxx = max(maxx, mx)
return minn, maxx
return fn(1, (1<<n)-1) | https://leetcode.com/problems/the-earliest-and-latest-rounds-where-players-compete/discuss/1268788/Python3-bit-mask-dp | 7 | There is a tournament where n players are participating. The players are standing in a single row and are numbered from 1 to n based on their initial standing position (player 1 is the first player in the row, player 2 is the second player in the row, etc.).
The tournament consists of multiple rounds (starting from round number 1). In each round, the ith player from the front of the row competes against the ith player from the end of the row, and the winner advances to the next round. When the number of players is odd for the current round, the player in the middle automatically advances to the next round.
For example, if the row consists of players 1, 2, 4, 6, 7
Player 1 competes against player 7.
Player 2 competes against player 6.
Player 4 automatically advances to the next round.
After each round is over, the winners are lined back up in the row based on the original ordering assigned to them initially (ascending order).
The players numbered firstPlayer and secondPlayer are the best in the tournament. They can win against any other player before they compete against each other. If any two other players compete against each other, either of them might win, and thus you may choose the outcome of this round.
Given the integers n, firstPlayer, and secondPlayer, return an integer array containing two values, the earliest possible round number and the latest possible round number in which these two players will compete against each other, respectively.
Example 1:
Input: n = 11, firstPlayer = 2, secondPlayer = 4
Output: [3,4]
Explanation:
One possible scenario which leads to the earliest round number:
First round: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
Second round: 2, 3, 4, 5, 6, 11
Third round: 2, 3, 4
One possible scenario which leads to the latest round number:
First round: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
Second round: 1, 2, 3, 4, 5, 6
Third round: 1, 2, 4
Fourth round: 2, 4
Example 2:
Input: n = 5, firstPlayer = 1, secondPlayer = 5
Output: [1,1]
Explanation: The players numbered 1 and 5 compete in the first round.
There is no way to make them compete in any other round.
Constraints:
2 <= n <= 28
1 <= firstPlayer < secondPlayer <= n | [Python3] bit-mask dp | 265 | the-earliest-and-latest-rounds-where-players-compete | 0.518 | ye15 | Hard | 26,879 | 1,900 |
find a peak element ii | class Solution:
def findPeakGrid(self, mat: List[List[int]]) -> List[int]:
m, n = len(mat), len(mat[0])
l, r = 0, n
while l <= r:
mid = (l + r) // 2
cur_max, left = 0, False
for i in range(m):
if i > 0 and mat[i-1][mid] >= mat[i][mid]:
continue
if i+1 < m and mat[i+1][mid] >= mat[i][mid]:
continue
if mid+1 < n and mat[i][mid+1] >= mat[i][mid]:
cur_max, left = mat[i][mid], not mat[i][mid] > cur_max
continue
if mid > 0 and mat[i][mid-1] >= mat[i][mid]:
cur_max, left = mat[i][mid], mat[i][mid] > cur_max
continue
return [i, mid]
if left:
r = mid-1
else:
l = mid+1
return [] | https://leetcode.com/problems/find-a-peak-element-ii/discuss/1446385/Python-3-or-Binary-Search-or-Explanation | 17 | A peak element in a 2D grid is an element that is strictly greater than all of its adjacent neighbors to the left, right, top, and bottom.
Given a 0-indexed m x n matrix mat where no two adjacent cells are equal, find any peak element mat[i][j] and return the length 2 array [i,j].
You may assume that the entire matrix is surrounded by an outer perimeter with the value -1 in each cell.
You must write an algorithm that runs in O(m log(n)) or O(n log(m)) time.
Example 1:
Input: mat = [[1,4],[3,2]]
Output: [0,1]
Explanation: Both 3 and 4 are peak elements so [1,0] and [0,1] are both acceptable answers.
Example 2:
Input: mat = [[10,20,15],[21,30,14],[7,16,32]]
Output: [1,1]
Explanation: Both 30 and 32 are peak elements so [1,1] and [2,2] are both acceptable answers.
Constraints:
m == mat.length
n == mat[i].length
1 <= m, n <= 500
1 <= mat[i][j] <= 105
No two adjacent cells are equal. | Python 3 | Binary Search | Explanation | 2,100 | find-a-peak-element-ii | 0.532 | idontknoooo | Medium | 26,880 | 1,901 |
largest odd number in string | class Solution:
def largestOddNumber(self, num: str) -> str:
for i in range(len(num) - 1, -1, -1) :
if num[i] in {'1','3','5','7','9'} :
return num[:i+1]
return '' | https://leetcode.com/problems/largest-odd-number-in-string/discuss/1338138/PYTHON-3%3A-99.34-FASTER-EASY-EXPLANATION | 30 | You are given a string num, representing a large integer. Return the largest-valued odd integer (as a string) that is a non-empty substring of num, or an empty string "" if no odd integer exists.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: num = "52"
Output: "5"
Explanation: The only non-empty substrings are "5", "2", and "52". "5" is the only odd number.
Example 2:
Input: num = "4206"
Output: ""
Explanation: There are no odd numbers in "4206".
Example 3:
Input: num = "35427"
Output: "35427"
Explanation: "35427" is already an odd number.
Constraints:
1 <= num.length <= 105
num only consists of digits and does not contain any leading zeros. | PYTHON 3: 99.34% FASTER, EASY EXPLANATION | 1,400 | largest-odd-number-in-string | 0.557 | rohitkhairnar | Easy | 26,893 | 1,903 |
the number of full rounds you have played | class Solution:
def numberOfRounds(self, startTime: str, finishTime: str) -> int:
hs, ms = (int(x) for x in startTime.split(":"))
ts = 60 * hs + ms
hf, mf = (int(x) for x in finishTime.split(":"))
tf = 60 * hf + mf
if 0 <= tf - ts < 15: return 0 # edge case
return tf//15 - (ts+14)//15 + (ts>tf)*96 | https://leetcode.com/problems/the-number-of-full-rounds-you-have-played/discuss/1284279/Python3-math-ish | 18 | You are participating in an online chess tournament. There is a chess round that starts every 15 minutes. The first round of the day starts at 00:00, and after every 15 minutes, a new round starts.
For example, the second round starts at 00:15, the fourth round starts at 00:45, and the seventh round starts at 01:30.
You are given two strings loginTime and logoutTime where:
loginTime is the time you will login to the game, and
logoutTime is the time you will logout from the game.
If logoutTime is earlier than loginTime, this means you have played from loginTime to midnight and from midnight to logoutTime.
Return the number of full chess rounds you have played in the tournament.
Note: All the given times follow the 24-hour clock. That means the first round of the day starts at 00:00 and the last round of the day starts at 23:45.
Example 1:
Input: loginTime = "09:31", logoutTime = "10:14"
Output: 1
Explanation: You played one full round from 09:45 to 10:00.
You did not play the full round from 09:30 to 09:45 because you logged in at 09:31 after it began.
You did not play the full round from 10:00 to 10:15 because you logged out at 10:14 before it ended.
Example 2:
Input: loginTime = "21:30", logoutTime = "03:00"
Output: 22
Explanation: You played 10 full rounds from 21:30 to 00:00 and 12 full rounds from 00:00 to 03:00.
10 + 12 = 22.
Constraints:
loginTime and logoutTime are in the format hh:mm.
00 <= hh <= 23
00 <= mm <= 59
loginTime and logoutTime are not equal. | [Python3] math-ish | 1,300 | the-number-of-full-rounds-you-have-played | 0.456 | ye15 | Medium | 26,928 | 1,904 |
count sub islands | class Solution:
def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int:
m=len(grid1)
n=len(grid1[0])
def dfs(i,j):
if i<0 or i>=m or j<0 or j>=n or grid2[i][j]==0:
return
grid2[i][j]=0
dfs(i+1,j)
dfs(i,j+1)
dfs(i,j-1)
dfs(i-1,j)
# removing all the non-common sub-islands
for i in range(m):
for j in range(n):
if grid2[i][j]==1 and grid1[i][j]==0:
dfs(i,j)
c=0
# counting sub-islands
for i in range(m):
for j in range(n):
if grid2[i][j]==1:
dfs(i,j)
c+=1
return c | https://leetcode.com/problems/count-sub-islands/discuss/1284306/98-faster-oror-Simple-approach-oror-well-explained | 148 | You are given two m x n binary matrices grid1 and grid2 containing only 0's (representing water) and 1's (representing land). An island is a group of 1's connected 4-directionally (horizontal or vertical). Any cells outside of the grid are considered water cells.
An island in grid2 is considered a sub-island if there is an island in grid1 that contains all the cells that make up this island in grid2.
Return the number of islands in grid2 that are considered sub-islands.
Example 1:
Input: grid1 = [[1,1,1,0,0],[0,1,1,1,1],[0,0,0,0,0],[1,0,0,0,0],[1,1,0,1,1]], grid2 = [[1,1,1,0,0],[0,0,1,1,1],[0,1,0,0,0],[1,0,1,1,0],[0,1,0,1,0]]
Output: 3
Explanation: In the picture above, the grid on the left is grid1 and the grid on the right is grid2.
The 1s colored red in grid2 are those considered to be part of a sub-island. There are three sub-islands.
Example 2:
Input: grid1 = [[1,0,1,0,1],[1,1,1,1,1],[0,0,0,0,0],[1,1,1,1,1],[1,0,1,0,1]], grid2 = [[0,0,0,0,0],[1,1,1,1,1],[0,1,0,1,0],[0,1,0,1,0],[1,0,0,0,1]]
Output: 2
Explanation: In the picture above, the grid on the left is grid1 and the grid on the right is grid2.
The 1s colored red in grid2 are those considered to be part of a sub-island. There are two sub-islands.
Constraints:
m == grid1.length == grid2.length
n == grid1[i].length == grid2[i].length
1 <= m, n <= 500
grid1[i][j] and grid2[i][j] are either 0 or 1. | ๐ 98% faster || Simple approach || well-explained ๐ | 4,900 | count-sub-islands | 0.677 | abhi9Rai | Medium | 26,937 | 1,905 |