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"
Exp... | 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, th... | 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 ba... | 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] = ma... | 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... | [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)
ret... | 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 th... | [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.
r... | 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
... | 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 ar... | [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 =... | 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 su... | [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... | 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.
speed... | [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 manDis... | 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... | [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
Expla... | 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 beau... | [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
val... | 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 ... | [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]... | [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) ... | 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}... | 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 ... | [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)
... | 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 s... | [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. ... | [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):
... | 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 th... | 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]... | 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... | [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])
els... | 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
O... | [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 seco... | ✔ 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 coin... | 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... | 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 ... | [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... | [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
... | 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 ... | [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:
... | 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 max... | 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... | 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 t... | [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.ge... | 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 wh... | 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... | 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 ... | [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 fi... | [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... | 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 i... | 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. ... | 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... | [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(sta... | 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 wil... | [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 inte... | 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
... | 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 multip... | [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])
... | 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 dif... | [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)
... | 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 element... | [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... | [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 g... | [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
... | 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 obs... | 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 s... | 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 t... | 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... | 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 (... | 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, ... | [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 c... | 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 le... | 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... | 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.po... | 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 tas... | 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))
\ | /
\ | /
... | 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 cons... | 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... | [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 -... | 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.
Exa... | [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:
... | 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" a... | [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] + restrictio... | 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 betw... | [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 ... | 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]:
... | 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 f... | [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]... | 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... | [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, sta... | [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]
... | 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" ... | 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 n... | 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 1... | [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... | 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 ... | 📌📌 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, ... | 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... | 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:
resu... | 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 pai... | 📌 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... | 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 ma... | [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)]
... | 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 the... | 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 "Th... | [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 memor... | [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
... | 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... | [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 numb... | 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:
fl... | 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 ... | [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:
... | 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,... | [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)) ... | 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 lengt... | [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
ret... | 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... | 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), cei... | 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... | [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... | 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 ca... | [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 t... | 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 ... | 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... | 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]
... | 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 correspon... | 🐍 {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... | 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.
Rea... | 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 ... | 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:]
... | 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... | 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):... | 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 ... | 🐍 {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: re... | 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 in... | [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 a... | 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... | [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... | [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... | 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... | [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]:
... | 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... | [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 cover... | 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 b... | 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.
... | 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):
fo... | 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 ... | [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):
... | 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 f... | [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():
... | 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.
... | 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... | 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... | [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 Fals... | 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 nu... | 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()
... | 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 rou... | [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]:
... | 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 ... | 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: ... | 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... | 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.
Yo... | [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(... | 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 i... | 🐍 98% faster || Simple approach || well-explained 📌 | 4,900 | count-sub-islands | 0.677 | abhi9Rai | Medium | 26,937 | 1,905 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.