post_href stringlengths 57 213 | python_solutions stringlengths 71 22.3k | slug stringlengths 3 77 | post_title stringlengths 1 100 | user stringlengths 3 29 | upvotes int64 -20 1.2k | views int64 0 60.9k | problem_title stringlengths 3 77 | number int64 1 2.48k | acceptance float64 0.14 0.91 | difficulty stringclasses 3 values | __index_level_0__ int64 0 34k |
|---|---|---|---|---|---|---|---|---|---|---|---|
https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/discuss/1135132/Python-O(n)-time-O(1)-space | class Solution:
def check(self, nums: List[int]) -> bool:
decreased = False
prior_num = nums[-1]
for num in nums:
if num < prior_num:
if decreased:
return False
decreased = True
prior_num = num
return True | check-if-array-is-sorted-and-rotated | Python O(n) time O(1) space | alexanco | 0 | 143 | check if array is sorted and rotated | 1,752 | 0.493 | Easy | 25,200 |
https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/discuss/1066092/Python-one-pass-Time-O(N)-Space-O(1). | class Solution:
def check(self, nums: List[int]) -> bool:
found = False
for idx in range(1, len(nums)):
if nums[idx] < nums[idx - 1]:
if found or nums[-1] > nums[0]:
return False
found = True
return True | check-if-array-is-sorted-and-rotated | Python, one pass Time O(N), Space O(1). | blue_sky5 | 0 | 64 | check if array is sorted and rotated | 1,752 | 0.493 | Easy | 25,201 |
https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/discuss/1062171/Python-1-Liner-just-for-fun | class Solution:
def check(self, nums: List[int]) -> bool:
return max(1 if nums[i:]+nums[:i] == sorted(nums) else 0 for i in range(len(nums))) | check-if-array-is-sorted-and-rotated | Python 1 Liner just for fun | Onlycst | 0 | 121 | check if array is sorted and rotated | 1,752 | 0.493 | Easy | 25,202 |
https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/discuss/1060162/Intuitive-approach-by-checking-the-number-of-break-point-(bp) | class Solution:
def check(self, nums: List[int]) -> bool:
min_val_pos, min_val, bp = 0, nums[0], 0
pv = min_val
for i in range(1, len(nums)):
cv = nums[i]
if cv < pv:
bp += 1
min_val_pos = i
min_val = cv
if bp > 1:
return False
pv = cv
return True if bp == 0 or nums[-1] <= nums[0] else False | check-if-array-is-sorted-and-rotated | Intuitive approach by checking the number of break point (bp) | puremonkey2001 | 0 | 62 | check if array is sorted and rotated | 1,752 | 0.493 | Easy | 25,203 |
https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/discuss/1055876/Python-3-Faster-than-100-and-space-less-than-100 | class Solution:
def check(self, nums) -> bool:
if len(set(nums))==1:
return True
count=0
temp =nums[-1]
for i in range(len(nums)-1):
if temp > nums[i]:
count+=1
temp = nums[i]
if count>=2:
return False
else:
return True | check-if-array-is-sorted-and-rotated | [Python 3] Faster than 100% and space less than 100% | WiseLin | 0 | 101 | check if array is sorted and rotated | 1,752 | 0.493 | Easy | 25,204 |
https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/discuss/1054031/Python-100-100-clear-and-easy-explanation | class Solution:
def check(self, nums: List[int]) -> bool:
count = 0
for i in range(0, len(nums)):
if nums[i] > nums[(i + 1) % len(nums)]:
count += 1
if count > 1:
return False
return True | check-if-array-is-sorted-and-rotated | Python 100% 100% clear and easy explanation | intouch_key | 0 | 36 | check if array is sorted and rotated | 1,752 | 0.493 | Easy | 25,205 |
https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/discuss/1053677/Python-3-Simple-brute-force-solution | class Solution:
def check(self, nums: List[int]) -> bool:
nums_sorted = sorted(nums)
if nums == nums_sorted:
return True
else:
for _ in range(len(nums)):
num_first = nums[0]
nums = nums[1:] + [num_first]
if nums == nums_sorted:
return True
return False | check-if-array-is-sorted-and-rotated | Python 3 - Simple brute force solution | TuanBC | 0 | 48 | check if array is sorted and rotated | 1,752 | 0.493 | Easy | 25,206 |
https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/discuss/1053647/Python-w-explanation | class Solution:
def check(self, nums: List[int]) -> bool:
rotations = 0
# zip returns tuple of two elements
for prev, cur in zip(nums, nums[1:]):
# sorted order is just fine
if prev <= cur:
continue
# If it is the second non-sorted place or if it is the first but the last character
# in the string greater than the first one (we can't have such rotation)
elif rotations or nums[-1] > nums[0]:
return False
rotations += 1
# reached here - everything is fine
return True | check-if-array-is-sorted-and-rotated | [Python] w/ explanation | MariaMozgunova | 0 | 53 | check if array is sorted and rotated | 1,752 | 0.493 | Easy | 25,207 |
https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/discuss/1053506/Python3-O(n)-or-easy-to-understand | class Solution:
def check(self, nums: List[int]) -> bool:
res = 0
n = len(nums)
for i in range(n):
if nums[i] > nums[(i+1) % n]:
res += 1
return res <= 1 | check-if-array-is-sorted-and-rotated | [Python3] O(n) | easy to understand | SonicM | 0 | 131 | check if array is sorted and rotated | 1,752 | 0.493 | Easy | 25,208 |
https://leetcode.com/problems/maximum-score-from-removing-stones/discuss/1053645/Python3-math | class Solution:
def maximumScore(self, a: int, b: int, c: int) -> int:
a, b, c = sorted((a, b, c))
if a + b < c: return a + b
return (a + b + c)//2 | maximum-score-from-removing-stones | [Python3] math | ye15 | 15 | 745 | maximum score from removing stones | 1,753 | 0.662 | Medium | 25,209 |
https://leetcode.com/problems/maximum-score-from-removing-stones/discuss/1053896/Python-Slicing-%2B-Sorting-(with-comments) | class Solution:
def maximumScore(self, a: int, b: int, c: int) -> int:
d = sorted([a,b,c])
r = 0
while len(d)>1: # continue removing stones when we have more than one piles
d[0], d[-1] = d[0] - 1, d[-1] - 1 # removing stones from first and last piles
if len(d) > 0 and d[-1]==0: # check if the last pile is empty
d = d[:-1]
if len(d) > 0 and d[0]==0: # check if the first pile is empty
d = d[1:]
r += 1 # increasing score after each step
d = sorted(d) # sort piles by stones
return r | maximum-score-from-removing-stones | Python - Slicing + Sorting (with comments) | qwe9 | 6 | 141 | maximum score from removing stones | 1,753 | 0.662 | Medium | 25,210 |
https://leetcode.com/problems/maximum-score-from-removing-stones/discuss/1446457/Python-3-or-O(1)-Greedy-O(N)-Sort-or-Explanation | class Solution:
def maximumScore(self, a: int, b: int, c: int) -> int:
a, b, c = sorted([a, b, c], reverse=True)
ans = 0
while a > 0 and b > 0:
a -= 1
b -= 1
ans += 1
a, b, c = sorted([a, b, c], reverse=True)
return ans | maximum-score-from-removing-stones | Python 3 | O(1) Greedy, O(N) Sort | Explanation | idontknoooo | 4 | 177 | maximum score from removing stones | 1,753 | 0.662 | Medium | 25,211 |
https://leetcode.com/problems/maximum-score-from-removing-stones/discuss/1446457/Python-3-or-O(1)-Greedy-O(N)-Sort-or-Explanation | class Solution:
def maximumScore(self, a: int, b: int, c: int) -> int:
a, b, c = sorted([a, b, c], reverse=True)
sub = math.ceil((a + b - c) / 2)
return b + min(a-b, c) if sub > b else sub + (a-sub) + (b-sub) | maximum-score-from-removing-stones | Python 3 | O(1) Greedy, O(N) Sort | Explanation | idontknoooo | 4 | 177 | maximum score from removing stones | 1,753 | 0.662 | Medium | 25,212 |
https://leetcode.com/problems/maximum-score-from-removing-stones/discuss/1433446/Python-3-93-T.C-O(1)-S.C-O(1)-Two-Solution | # Solution - I
class Solution:
def maximumScore(self, a, b, c):
if (a >= b) and (a >= c):
largest = a
elif (b >= a) and (b >= c):
largest = b
else:
largest = c
s = a+b+c
if s-largest<=largest:
return s - largest
return s//2
```
# Solution - II
class Solution:
def maximumScore(self, num1, num2, num3):
def largest(num1, num2, num3):
if (num1 > num2) and (num1 > num3):
largest_num = num1
elif (num2 > num1) and (num2 > num3):
largest_num = num2
else:
largest_num = num3
return largest_num
l = largest(num1,num2,num3)
s = num1+num2+num3
if s-l<=l:
return s-l
return s//2 | maximum-score-from-removing-stones | Python 3 93% T.C - O(1) S.C-O(1) Two Solution | rstudy211 | 1 | 64 | maximum score from removing stones | 1,753 | 0.662 | Medium | 25,213 |
https://leetcode.com/problems/maximum-score-from-removing-stones/discuss/2804981/Python-O-(1)-time-and-O-(1)-space | class Solution:
def maximumScore(self, a: int, b: int, c: int) -> int:
vals = sorted([a,b,c])
first = vals[0]
second = vals[1]
third = vals[2]
mini = min(first + second, third)
if first + second > third:
return mini + (first+second - third)//2
else:
return mini
# if tot >= third:
# return third + (tot - third)//2
# else:
# return tot | maximum-score-from-removing-stones | Python O (1) time and O (1) space | vijay_2022 | 0 | 2 | maximum score from removing stones | 1,753 | 0.662 | Medium | 25,214 |
https://leetcode.com/problems/maximum-score-from-removing-stones/discuss/2749870/Python-simple-O(1)-eassy-to-understand | class Solution:
def maximumScore(self, a: int, b: int, c: int) -> int:
l = [a,b,c]
l.sort()
x = l[0]+l[1]-l[2]
if x<0:
return l[0]+l[1]
return (x)//2 +l[2] | maximum-score-from-removing-stones | Python simple O(1) eassy to understand | manishx112 | 0 | 4 | maximum score from removing stones | 1,753 | 0.662 | Medium | 25,215 |
https://leetcode.com/problems/maximum-score-from-removing-stones/discuss/2684684/python-greedy-and-maxHeap | class Solution:
def maximumScore(self, a: int, b: int, c: int) -> int:
res, maxHeap = 0, [-a, -b, -c]
heapify(maxHeap)
while maxHeap:
first, second, third = -heappop(maxHeap), -heappop(maxHeap), heappop(maxHeap)
if second == 0 and third == 0:
break
res += 1
first -= 1
second -= 1
heappush(maxHeap, -first)
heappush(maxHeap, -second)
heappush(maxHeap, third)
return res | maximum-score-from-removing-stones | python greedy and maxHeap | JasonDecode | 0 | 5 | maximum score from removing stones | 1,753 | 0.662 | Medium | 25,216 |
https://leetcode.com/problems/maximum-score-from-removing-stones/discuss/2366482/Python-heap-readable-solution | class Solution:
def maximumScore(self, a: int, b: int, c: int) -> int:
q = [-a,-b,-c]
points=0
while len(q)>1:
x1=heappop(q)
x2=heappop(q)
x1+=1
x2+=1
if x1:
heappush(q,x1)
if x2:
heappush(q,x2)
points+=1
return points | maximum-score-from-removing-stones | Python heap readable solution | sunakshi132 | 0 | 24 | maximum score from removing stones | 1,753 | 0.662 | Medium | 25,217 |
https://leetcode.com/problems/maximum-score-from-removing-stones/discuss/1528603/100-faster-oror-Math-and-Logic-oror-Easy-to-Understand | class Solution:
def maximumScore(self, a: int, b: int, c: int) -> int:
a,b,c = sorted([a,b,c])
s = a+b
d = abs(s-c)
if s>=c:
return c + d//2
else:
return s | maximum-score-from-removing-stones | 📌📌 100% faster || Math & Logic || Easy to Understand 🐍 | abhi9Rai | 0 | 92 | maximum score from removing stones | 1,753 | 0.662 | Medium | 25,218 |
https://leetcode.com/problems/maximum-score-from-removing-stones/discuss/1061363/Steal-Maximum-MTG-cards-from-kids-on-the-playground-(TLE-Backtracking) | class Solution(object):
def maximumScore(self, a, b, c):
memo = {}
def dfs(a, b, c):
if (a,b,c) in memo:
return memo[a,b,c]
if (a==0 and b==0) or\
(b==0 and c==0) or\
(a==0 and c==0):
return 0
ra = dfs(a-1, b-1, c) if a>0 and b>0 else 0
rb = dfs(a, b-1, c-1) if b>0 and c>0 else 0
rc = dfs(a-1, b, c-1) if a>0 and c>0 else 0
memo[a,b,c] = max(ra, rb, rc) + 1
return memo[a,b,c]
return dfs(a,b,c) | maximum-score-from-removing-stones | Steal Maximum MTG cards from kids on the playground (TLE Backtracking) | Yusef28 | 0 | 55 | maximum score from removing stones | 1,753 | 0.662 | Medium | 25,219 |
https://leetcode.com/problems/maximum-score-from-removing-stones/discuss/1053797/Python-Easy-To-Understand-and-detailed-explanation | class Solution:
def maximumScore(self, a: int, b: int, c: int) -> int:
ans = 0
ar = sorted([a, b, c])
while ar[0]!=0:
ar.sort()
ar[0]-=1
ar[-1]-=1
ans+=1
return ans+min(ar[1], ar[-1]) | maximum-score-from-removing-stones | Python Easy To Understand and detailed explanation | rudranshsharma123 | 0 | 62 | maximum score from removing stones | 1,753 | 0.662 | Medium | 25,220 |
https://leetcode.com/problems/maximum-score-from-removing-stones/discuss/1053674/Python3-Easy-solution | class Solution:
def maximumScore(self, a: int, b: int, c: int) -> int:
l1 = [a,b,c]
l1.sort()
a, b, c = l1[0],l1[1],l1[2]
ans = 0
for j in range(a+1):
ans = max(ans, a + min((b - j), (c - (a - j))))
return ans | maximum-score-from-removing-stones | [Python3] Easy solution | mihirrane | 0 | 52 | maximum score from removing stones | 1,753 | 0.662 | Medium | 25,221 |
https://leetcode.com/problems/maximum-score-from-removing-stones/discuss/1053670/Python-w-explanation | class Solution:
def maximumScore(self, a: int, b: int, c: int) -> int:
a, b, c = sorted((a, b, c))
if a + b <= c:
return a + b
return a + (b + c - a) // 2 | maximum-score-from-removing-stones | [Python] w/ explanation | MariaMozgunova | 0 | 52 | maximum score from removing stones | 1,753 | 0.662 | Medium | 25,222 |
https://leetcode.com/problems/largest-merge-of-two-strings/discuss/1053605/Python3-greedy | class Solution:
def largestMerge(self, word1: str, word2: str) -> str:
ans = []
i1 = i2 = 0
while i1 < len(word1) and i2 < len(word2):
if word1[i1:] > word2[i2:]:
ans.append(word1[i1])
i1 += 1
else:
ans.append(word2[i2])
i2 += 1
return "".join(ans) + word1[i1:] + word2[i2:] | largest-merge-of-two-strings | [Python3] greedy | ye15 | 6 | 251 | largest merge of two strings | 1,754 | 0.451 | Medium | 25,223 |
https://leetcode.com/problems/largest-merge-of-two-strings/discuss/1053560/Python-Simple-Solution | class Solution:
def largestMerge(self, w1: str, w2: str) -> str:
ans=[]
m,n=len(w1),len(w2)
i=j=0
while i<m or j<n:
if w1[i:]>w2[j:]:
ans.append(w1[i])
i+=1
else:
ans.append(w2[j])
j+=1
return ''.join(ans) | largest-merge-of-two-strings | Python Simple Solution | lokeshsenthilkumar | 3 | 133 | largest merge of two strings | 1,754 | 0.451 | Medium | 25,224 |
https://leetcode.com/problems/largest-merge-of-two-strings/discuss/1429031/python-3-merge-sort-method-oror-easy-oror-clean | class Solution(object):
def largestMerge(self, w1, w2):
i=j=0
s=""
while i<len(w1) and j<len(w2):
if w1[i] > w2[j]:
s+=w1[i]
i=i+1
elif w1[i] < w2[j]:
s+=w2[j]
j=j+1
elif w1[i:] > w2[j:]:
s+=w1[i]
i+=1
else:
s+=w2[j]
j+=1
while i<len(w1):
s=s+w1[i]
i=i+1
while j<len(w2):
s=s+w2[j]
j=j+1
return s | largest-merge-of-two-strings | python 3 merge sort method || easy || clean | minato_namikaze | 2 | 125 | largest merge of two strings | 1,754 | 0.451 | Medium | 25,225 |
https://leetcode.com/problems/largest-merge-of-two-strings/discuss/2545148/Python-Greedy-with-comments | class Solution:
def largestMerge(self, word1: str, word2: str) -> str:
# init values
result = ""
p1 = 0
p2 = 0
l1 = len(word1)
l2 = len(word2)
# iteration over both pointers, while both words
# have letters
while p1 < l1 and p2 < l2:
# easy case where current word1 letter is bigger
if word1[p1] > word2[p2]:
result += word1[p1]
p1 += 1
# easy case where current word2 letter is bigger
elif word1[p1] < word2[p2]:
result += word2[p2]
p2 += 1
# as soon as words are equal we need to figure out
# how to go on. We do that by looking where we can
# get the next most highest letter
else:
if word1[p1:] > word2[p2:]:
result += word1[p1]
p1 += 1
else:
result += word2[p2]
p2 += 1
# add the rest of the words (one of them will be empty!)
result += word1[p1:] + word2[p2:]
return result | largest-merge-of-two-strings | [Python] - Greedy with comments | Lucew | 0 | 31 | largest merge of two strings | 1,754 | 0.451 | Medium | 25,226 |
https://leetcode.com/problems/largest-merge-of-two-strings/discuss/1130087/Python-Long-solution-(AC-without-using-slice)-%2B-DP-(TLE)-solution | class Solution:
def largestMerge(self, word1: str, word2: str) -> str:
M = len(word1)
N = len(word2)
#pointers for word1 and word2
p1 = 0
p2 = 0
mergeList = []
while p1 < M and p2 < N:
#print("mergeList: {}".format(mergeList))
if word1[p1] > word2[p2]:
mergeList.append(word1[p1])
p1 += 1
elif word1[p1] < word2[p2]:
mergeList.append(word2[p2])
p2 += 1
else: #equal, so check ahead to see which one eventually has higher lex
temp1,temp2 = p1,p2
while word1[temp1] == word2[temp2]:
temp1 += 1
temp2 += 1
if temp2 == N:
#word2 reached the end without seeing different char from word1, so take word1's chars up till (and excluding) this point
#first make sure the next char in word1 is greater than word2's p2 char, otherwise we will take all of word2 first
if temp1 == M:
#both the same, take word1 char
mergeList.append(word1[p1])
p1 += 1
break
else:
if word1[temp1] < word2[p2]:
#take word2 char first
mergeList.append(word2[p2])
p2 += 1
else:
#take word1 first
mergeList.append(word1[p1])
p1 += 1
break
elif temp1 == M:
#similarly as the previous if
if temp2 == N:
#both the same - take word1 char first
mergeList.append(word1[p1])
p1 += 1
else:
if word2[temp2] < word1[p1]:
#take word1 char first
mergeList.append(word1[p1])
p1 += 1
else:
#take word2 char first
mergeList.append(word2[p2])
p2 += 1
break
elif word1[temp1] != word2[temp2]:
if word1[temp1] > word2[temp2]:
#char of word1 is bigger so take p1 char from word1
mergeList.append(word1[p1])
p1 += 1
else:
#char of word2 is bigger so take p2 char from word2
mergeList.append(word2[p2])
p2 += 1
break
#done with at least one string, add the rest of the other
if p1 == M and p2 != N:
mergeList.append(word2[p2:])
elif p1 != M and p2 == N:
mergeList.append(word1[p1:])
return "".join(mergeList) | largest-merge-of-two-strings | [Python] Long solution (AC without using slice) + DP (TLE) solution | Vikktour | 0 | 107 | largest merge of two strings | 1,754 | 0.451 | Medium | 25,227 |
https://leetcode.com/problems/largest-merge-of-two-strings/discuss/1130087/Python-Long-solution-(AC-without-using-slice)-%2B-DP-(TLE)-solution | class Solution:
def largestMerge(self, word1: str, word2: str) -> str:
index1 = 0
index2 = 0
N1 = len(word1)
N2 = len(word2)
dpPrevRow = [""]*(N2+1)
for j in range(0,N2):
dpPrevRow[j+1] = dpPrevRow[j] + word2[j]
#print("dpPrevRow: {}".format(dpPrevRow))
dpCurRow = [""]*(N2+1)
for i in range(1,N1+1):
for j in range(0,N2+1):
if j==0:
dpCurRow[0] = dpPrevRow[0] + word1[i-1]
else:
#dpCurRow[j] = max(dpCurRow[j-1],dpPrevRow[j]) +
if dpCurRow[j-1] > dpPrevRow[j]:
dpCurRow[j] = dpCurRow[j-1] + word2[j-1]
else:
dpCurRow[j] = dpPrevRow[j] + word1[i-1]
dpPrevRow = dpCurRow
#print("dpCurRow = {}".format(dpCurRow))
return dpCurRow[N2] | largest-merge-of-two-strings | [Python] Long solution (AC without using slice) + DP (TLE) solution | Vikktour | 0 | 107 | largest merge of two strings | 1,754 | 0.451 | Medium | 25,228 |
https://leetcode.com/problems/largest-merge-of-two-strings/discuss/1062939/Trying-to-Save-My-Dead-End-Job-(Greedy-Solution-from-Lee215) | class Solution:
def largestMerge(self, w1: str, w2: str) -> str:
def dfs(m, w1, w2):
if not w1 or not w2:
return m + (w1 if w1 else w2)
if w1 >= w2:
return dfs(m+w1[0], w1[1:], w2)
elif w1 < w2:
return dfs(m+w2[0], w1, w2[1:])
#else:
#return max(dfs(m+w1[0], w1[1:], w2), dfs(m+w2[0], w1, w2[1:]))
return dfs("", w1, w2) | largest-merge-of-two-strings | Trying to Save My Dead End Job (Greedy Solution from Lee215) | Yusef28 | 0 | 137 | largest merge of two strings | 1,754 | 0.451 | Medium | 25,229 |
https://leetcode.com/problems/closest-subsequence-sum/discuss/1053790/Python3-divide-in-half | class Solution:
def minAbsDifference(self, nums: List[int], goal: int) -> int:
def fn(nums):
ans = {0}
for x in nums:
ans |= {x + y for y in ans}
return ans
nums0 = sorted(fn(nums[:len(nums)//2]))
ans = inf
for x in fn(nums[len(nums)//2:]):
k = bisect_left(nums0, goal - x)
if k < len(nums0): ans = min(ans, nums0[k] + x - goal)
if 0 < k: ans = min(ans, goal - x - nums0[k-1])
return ans | closest-subsequence-sum | [Python3] divide in half | ye15 | 28 | 1,400 | closest subsequence sum | 1,755 | 0.364 | Hard | 25,230 |
https://leetcode.com/problems/closest-subsequence-sum/discuss/2818506/Python-easy-to-read-and-understand-or-binary-search | class Solution:
# @lru_cache
def solve(self, nums, i, sums, path, goal):
if i == len(nums):
# print(path, sums)
self.res = min(self.res, abs(sums - goal))
return
self.solve(nums, i + 1, sums + nums[i], path + [nums[i]], goal)
self.solve(nums, i + 1, sums, path, goal)
def minAbsDifference(self, nums: List[int], goal: int) -> int:
self.res = float("inf")
self.solve(nums, 0, 0, [], goal)
return self.res | closest-subsequence-sum | Python easy to read and understand | binary-search | sanial2001 | 0 | 4 | closest subsequence sum | 1,755 | 0.364 | Hard | 25,231 |
https://leetcode.com/problems/closest-subsequence-sum/discuss/2818506/Python-easy-to-read-and-understand-or-binary-search | class Solution:
def solve(self, nums, i, val, sums):
if i == len(nums):
sums.append(val)
return
self.solve(nums, i+1, val+nums[i], sums)
self.solve(nums, i+1, val, sums)
def minAbsDifference(self, nums: List[int], goal: int) -> int:
n = len(nums)
sum1, sum2 = [], []
self.solve(nums[:n//2], 0, 0, sum1)
self.solve(nums[n//2:], 0, 0, sum2)
sum2 = sorted(sum2)
#print(sum1, sum2)
n2 = len(sum2)
ans = float("inf")
for s in sum1:
rem = goal-s
i = bisect_left(sum2, rem)
if i < n2:
ans = min(ans, abs(rem-sum2[i]))
if i > 0:
ans = min(ans, abs(rem-sum2[i-1]))
return ans | closest-subsequence-sum | Python easy to read and understand | binary-search | sanial2001 | 0 | 4 | closest subsequence sum | 1,755 | 0.364 | Hard | 25,232 |
https://leetcode.com/problems/minimum-changes-to-make-alternating-binary-string/discuss/1437401/Python3-solution-or-O(n)-or-Explained | class Solution:
def minOperations(self, s: str) -> int:
count = 0
count1 = 0
for i in range(len(s)):
if i % 2 == 0:
if s[i] == '1':
count += 1
if s[i] == '0':
count1 += 1
else:
if s[i] == '0':
count += 1
if s[i] == '1':
count1 += 1
return min(count, count1) | minimum-changes-to-make-alternating-binary-string | Python3 solution | O(n) | Explained | FlorinnC1 | 10 | 425 | minimum changes to make alternating binary string | 1,758 | 0.583 | Easy | 25,233 |
https://leetcode.com/problems/minimum-changes-to-make-alternating-binary-string/discuss/1064546/Python3-counting | class Solution:
def minOperations(self, s: str) -> int:
cnt = 0 # "010101..."
for i, c in enumerate(s):
if i&1 == int(c): cnt += 1
return min(cnt, len(s) - cnt) | minimum-changes-to-make-alternating-binary-string | [Python3] counting | ye15 | 4 | 277 | minimum changes to make alternating binary string | 1,758 | 0.583 | Easy | 25,234 |
https://leetcode.com/problems/minimum-changes-to-make-alternating-binary-string/discuss/1138511/Python-solution-(83-faster) | class Solution:
def minOperations(self, s: str) -> int:
odd=[]
even=[]
for i in range(len(s)):
if i%2==0:
even.append(s[i])
else:
odd.append(s[i])
return min(even.count('1')+odd.count('0'),even.count('0')+odd.count('1')) | minimum-changes-to-make-alternating-binary-string | Python solution (83% faster) | samarthnehe | 2 | 236 | minimum changes to make alternating binary string | 1,758 | 0.583 | Easy | 25,235 |
https://leetcode.com/problems/minimum-changes-to-make-alternating-binary-string/discuss/1098059/Python3-simple-solution | class Solution:
def minOperations(self, s: str) -> int:
n = len(s)
print(n)
x1 = ''
x2 = ''
l = []
if n % 2 == 0:
x1 = '10'*(n//2)
x2 = '01'*(n//2)
else:
x1 = '10'*(n//2)+'1'
x2 = '01'*(n//2)+'0'
l = [x1,x2]
count1, count2 = 0,0
for i in range(len(s)):
if l[0][i] != s[i]:
count1 += 1
if l[1][i] != s[i]:
count2 += 1
return min(count1, count2) | minimum-changes-to-make-alternating-binary-string | Python3 simple solution | EklavyaJoshi | 2 | 176 | minimum changes to make alternating binary string | 1,758 | 0.583 | Easy | 25,236 |
https://leetcode.com/problems/minimum-changes-to-make-alternating-binary-string/discuss/1930933/python-3-oror-simple-one-pass-solution | class Solution:
def minOperations(self, s: str) -> int:
a = b = 0
for i, c in enumerate(s):
if i % 2 == 0:
if c == '0':
a += 1
else:
b += 1
else:
if c == '0':
b += 1
else:
a += 1
return min(a, b) | minimum-changes-to-make-alternating-binary-string | python 3 || simple one pass solution | dereky4 | 1 | 74 | minimum changes to make alternating binary string | 1,758 | 0.583 | Easy | 25,237 |
https://leetcode.com/problems/minimum-changes-to-make-alternating-binary-string/discuss/1622022/Python.-Easy-and-Fast. | class Solution:
def minOperations(self, s: str) -> int:
return min(self.alt("0",s),self.alt("1",s))
def alt(self,num,string):
count = 0
for s in string:
if s != num:
count +=1
num = "0" if num == "1" else "1"
return count | minimum-changes-to-make-alternating-binary-string | Python. Easy and Fast. | manassehkola | 1 | 149 | minimum changes to make alternating binary string | 1,758 | 0.583 | Easy | 25,238 |
https://leetcode.com/problems/minimum-changes-to-make-alternating-binary-string/discuss/1064504/PythonPython3-Minimum-Changes-To-Make-Alternating-Binary-String | class Solution:
def minOperations(self, s: str) -> int:
start = 0
zero_cnt = 0
for idx in range(len(s)):
if int(s[idx]) != start:
zero_cnt += 1
start = start ^ 1
start = 1
one_cnt = 0
for idx in range(len(s)):
if int(s[idx]) != start:
one_cnt += 1
start = start ^ 1
return min(zero_cnt, one_cnt) | minimum-changes-to-make-alternating-binary-string | [Python/Python3] Minimum Changes To Make Alternating Binary String | newborncoder | 1 | 88 | minimum changes to make alternating binary string | 1,758 | 0.583 | Easy | 25,239 |
https://leetcode.com/problems/minimum-changes-to-make-alternating-binary-string/discuss/2805011/Simple-Easy-Python | class Solution:
def minOperations(self, s: str) -> int:
# pointer
even = 0
odd = 0
for idx, chr in enumerate(s):
# case 1:
if idx % 2 == 0:
if chr == '0':
even += 1
else:
odd += 1
elif idx % 2 == 1:
if chr == '1':
even += 1
else:
odd += 1
return min(even, odd) | minimum-changes-to-make-alternating-binary-string | Simple Easy Python | moon1006 | 0 | 7 | minimum changes to make alternating binary string | 1,758 | 0.583 | Easy | 25,240 |
https://leetcode.com/problems/minimum-changes-to-make-alternating-binary-string/discuss/2780789/python-3-xor-operations | class Solution:
def minOperations(self, s: str) -> int:
ov, zv = 0, 0
for i in range(len(s)):
if (i%2) ^ int(s[i]) != 0:
ov += 1
if (i+1)%2 ^ int(s[i]) != 0:
zv += 1
return min(ov, zv) | minimum-changes-to-make-alternating-binary-string | python 3 xor operations | WJTTW | 0 | 3 | minimum changes to make alternating binary string | 1,758 | 0.583 | Easy | 25,241 |
https://leetcode.com/problems/minimum-changes-to-make-alternating-binary-string/discuss/2351978/Python3-East-to-understand-O(N)-Solution-English-Explanation | class Solution:
def minOperations(self, s: str) -> int:
# 1010 etc.
count1 = 0
# 0101 etc.
count2 = 0
for i in range(len(s)):
if int(s[i]) != i % 2:
count1 += 1
else:
count2 += 1
return min(count1, count2) | minimum-changes-to-make-alternating-binary-string | [Python3] ✔️ East to understand O(N) Solution ✔️English Explanation | shrined | 0 | 87 | minimum changes to make alternating binary string | 1,758 | 0.583 | Easy | 25,242 |
https://leetcode.com/problems/minimum-changes-to-make-alternating-binary-string/discuss/1989106/Python-easy-single-pass-solution-faster-than-89-memory-less-than-96 | class Solution:
def minOperations(self, s: str) -> int:
check1, check2 = 0, 0
for i in range(len(s)):
if i % 2 == 0:
if s[i] == "0":
check2 += 1
else:
check1 += 1
else:
if s[i] == "1":
check2 += 1
else:
check1 += 1
return min(check1, check2) | minimum-changes-to-make-alternating-binary-string | Python easy single pass solution faster than 89%, memory less than 96% | alishak1999 | 0 | 99 | minimum changes to make alternating binary string | 1,758 | 0.583 | Easy | 25,243 |
https://leetcode.com/problems/minimum-changes-to-make-alternating-binary-string/discuss/1949173/Python-(Simple-Approach-and-Beginner-Friendly) | class Solution:
def minOperations(self, s: str) -> int:
s = list(s)
poss1 = ['']*len(s)
poss2 = ['']*len(s)
for i in range(0,len(s),2):
poss1[i] = '0'
poss2[i] = '1'
for i in range(1,len(s),2):
poss1[i] = '1'
poss2[i] = '0'
print(poss1, poss2)
a, b = 0,0
for i in range(len(s)):
if s[i] != poss1[i]:
a+=1
if s[i] != poss2[i]:
b+=1
return min(a,b) | minimum-changes-to-make-alternating-binary-string | Python (Simple Approach and Beginner-Friendly) | vishvavariya | 0 | 60 | minimum changes to make alternating binary string | 1,758 | 0.583 | Easy | 25,244 |
https://leetcode.com/problems/minimum-changes-to-make-alternating-binary-string/discuss/1570062/Python-solution-O(n) | class Solution:
def minOperations(self, s: str) -> int:
a,b = '0', '1'
count1, count2 = 0, 0
for i in s:
if i!=a:
count1+=1
if i!=b:
count2+=1
a, b = b, a
return min(count1, count2) | minimum-changes-to-make-alternating-binary-string | Python solution O(n) | ShaangriLa | 0 | 136 | minimum changes to make alternating binary string | 1,758 | 0.583 | Easy | 25,245 |
https://leetcode.com/problems/minimum-changes-to-make-alternating-binary-string/discuss/1543284/One-pass-96-speed | class Solution:
def minOperations(self, s: str) -> int:
start0 = start1 = 0
for i, c in enumerate(s):
if i % 2:
if c == "0":
start0 += 1
else:
start1 += 1
else:
if c == "0":
start1 += 1
else:
start0 += 1
return min(start0, start1) | minimum-changes-to-make-alternating-binary-string | One pass, 96% speed | EvgenySH | 0 | 91 | minimum changes to make alternating binary string | 1,758 | 0.583 | Easy | 25,246 |
https://leetcode.com/problems/minimum-changes-to-make-alternating-binary-string/discuss/1454552/Python-Linear | class Solution:
def minOperations(self, s: str) -> int:
n = len(s)
one = ""
while True:
if len(one) >= n:
break
else:
one += "1"
one += "0"
one = one[:len(s)]
two = ""
while True:
if len(two) >= n:
break
else:
two += "0"
two += "1"
two = two[:len(s)]
count_one = 0
for i, j in zip(s, one):
if i != j:
count_one += 1
count_two = 0
for i, j in zip(s, two):
if i != j:
count_two += 1
return min(count_one, count_two) | minimum-changes-to-make-alternating-binary-string | [Python] Linear | Sai-Adarsh | 0 | 119 | minimum changes to make alternating binary string | 1,758 | 0.583 | Easy | 25,247 |
https://leetcode.com/problems/minimum-changes-to-make-alternating-binary-string/discuss/1089439/Faster-then-92-of-Python-Submissions | class Solution:
def minOperations(self, s: str) -> int:
#s = "101101111"
if len(s)% 2 == 0 :
number = int(len(s)/2)
v2 = self.counting(s,"".join(["10"]*number))
v3 = self.counting(s,"".join(["01"]*number))
return min([v2,v3])
else :
number = int(len(s)/2)+1
v2 = self.counting(s,"".join(["10"]*number)[0:-1])
v3 = self.counting(s,"".join(["01"]*number)[0:-1])
return min([v2,v3])
def counting(self,init,final):
count = 0
for i in range(0,len(init)):
if init[i] != final[i]:
count +=1
else :
pass
return count | minimum-changes-to-make-alternating-binary-string | Faster then 92 % of Python Submissions | xevb | 0 | 171 | minimum changes to make alternating binary string | 1,758 | 0.583 | Easy | 25,248 |
https://leetcode.com/problems/minimum-changes-to-make-alternating-binary-string/discuss/1074038/python-My-approach-with-detailed-explanation | class Solution:
def minOperations(self, s: str) -> int:
pattern1_changes = 0
pattern2_changes = 0
for i, c in enumerate(s):
if i%2 != int(c): pattern1_changes += 1
if (i+1) % 2 != int(c) : pattern2_changes += 1
return min(pattern1_changes, pattern2_changes) | minimum-changes-to-make-alternating-binary-string | [python] My approach with detailed explanation | Jay1984 | 0 | 138 | minimum changes to make alternating binary string | 1,758 | 0.583 | Easy | 25,249 |
https://leetcode.com/problems/minimum-changes-to-make-alternating-binary-string/discuss/1074038/python-My-approach-with-detailed-explanation | class Solution:
def minOperations(self, s: str) -> int:
pattern1_changes = 0
pattern2_changes = 0
for i, c in enumerate(s):
if i%2 != int(c): pattern1_changes += 1
else: pattern2_changes += 1
return min(pattern1_changes, pattern2_changes) | minimum-changes-to-make-alternating-binary-string | [python] My approach with detailed explanation | Jay1984 | 0 | 138 | minimum changes to make alternating binary string | 1,758 | 0.583 | Easy | 25,250 |
https://leetcode.com/problems/minimum-changes-to-make-alternating-binary-string/discuss/1067685/Leonardo-Di-Caprio-Finds-Time-Alone-(Brute-Force-100) | class Solution:
def minOperations(self, s: str) -> int:
L = 0
R = 0
tmp = s
for i in range(1, len(s)):
if s[i] == s[i-1]:
L += 1
s = s[:i] + str(abs(int(s[i]) - 1)) + s[i+1:]
s = tmp[::-1]
for i in range(1, len(s)):
if s[i] == s[i-1]:
R += 1
s = s[:i] + str(abs(int(s[i]) - 1)) + s[i+1:]
return min(L,R,len(s)-L,len(s)-R) | minimum-changes-to-make-alternating-binary-string | Leonardo Di Caprio Finds Time Alone (Brute Force 100%) | Yusef28 | 0 | 68 | minimum changes to make alternating binary string | 1,758 | 0.583 | Easy | 25,251 |
https://leetcode.com/problems/minimum-changes-to-make-alternating-binary-string/discuss/1066085/Python-two-pass-O(N)O(1) | class Solution:
def minOperations(self, s: str) -> int:
def count_mismatches(n):
count = 0
for c in s:
if n != c:
count += 1
n = '1' if n == '0' else '0'
return count
return min(count_mismatches('1'), count_mismatches('0')) | minimum-changes-to-make-alternating-binary-string | Python, two pass O(N)/O(1) | blue_sky5 | 0 | 63 | minimum changes to make alternating binary string | 1,758 | 0.583 | Easy | 25,252 |
https://leetcode.com/problems/minimum-changes-to-make-alternating-binary-string/discuss/1064849/python3-solution-oror-using-of-four-variable | class Solution:
def minOperations(self, s: str) -> int:
even_0 =0
even_1 =0
odd_0 = 0
odd_1 =0
for i , ch in enumerate(s):
if i%2 ==0:
if ch =='1':
even_1+=1
else:
even_0+=1
else:
if ch =='1':
odd_1+=1
else:
odd_0+=1
return min(even_0+odd_1 , odd_0+even_1)//convert to those which r minimum | minimum-changes-to-make-alternating-binary-string | python3 solution || using of four variable | Yash_pal2907 | 0 | 46 | minimum changes to make alternating binary string | 1,758 | 0.583 | Easy | 25,253 |
https://leetcode.com/problems/minimum-changes-to-make-alternating-binary-string/discuss/1064668/Python-You-only-have-two-ways-to-transform-string | class Solution:
def minOperations(self, s: str) -> int:
def compare(s, start=0):
res = 0
# enumerate yields tuples of index and element in s
# the second argument in enumerate is the starting point for index
for i, el in enumerate(s, start):
# i % 2 will be either 0 or 1
# str(i % 2) and el are not the same this is the place where s and
# 1010101... or 010101... with the same length differs
if str(i % 2) != el:
res += 1
return res
return min(compare(s), compare(s, 1)) | minimum-changes-to-make-alternating-binary-string | [Python] You only have two ways to transform string | MariaMozgunova | 0 | 73 | minimum changes to make alternating binary string | 1,758 | 0.583 | Easy | 25,254 |
https://leetcode.com/problems/minimum-changes-to-make-alternating-binary-string/discuss/1065377/Python-3-24ms-beats-100.00 | class Solution:
def minOperations(self, s: str) -> int:
return min((cnt := s[::2].count('1') + s[1::2].count('0')), len(s) - cnt) | minimum-changes-to-make-alternating-binary-string | Python 3, 24ms, beats 100.00 % | jmj1 | -2 | 80 | minimum changes to make alternating binary string | 1,758 | 0.583 | Easy | 25,255 |
https://leetcode.com/problems/count-number-of-homogenous-substrings/discuss/1064598/Python-one-pass-with-explanation | class Solution:
def countHomogenous(self, s: str) -> int:
res, count, n = 0, 1, len(s)
for i in range(1,n):
if s[i]==s[i-1]:
count+=1
else:
if count>1:
res+=(count*(count-1)//2)
count=1
if count>1:
res+=(count*(count-1)//2)
return (res+n)%(10**9+7) | count-number-of-homogenous-substrings | Python - one pass - with explanation | ajith6198 | 6 | 353 | count number of homogenous substrings | 1,759 | 0.48 | Medium | 25,256 |
https://leetcode.com/problems/count-number-of-homogenous-substrings/discuss/1627143/Python-oror-Easy-Solution-oror-Beat~100-oror-Using-groupby | class Solution:
def countHomogenous(self, s: str) -> int:
count = 0
for i, j in itertools.groupby(s):
temp = len(list(j))
count += (temp * (temp + 1)) // 2
return count % (10 ** 9 + 7) | count-number-of-homogenous-substrings | Python || Easy Solution || Beat~100% || Using groupby | naveenrathore | 1 | 102 | count number of homogenous substrings | 1,759 | 0.48 | Medium | 25,257 |
https://leetcode.com/problems/count-number-of-homogenous-substrings/discuss/1064716/Python-with-illustration-It-is-just-an-arithmetic-progression | class Solution:
def countHomogenous(self, s: str) -> int:
i = j = 0
n = len(s)
res = 0
while i < n:
while j < n and s[j] == s[i]:
j += 1
# l is the length of the homogenous substrings
l = j - i
# our formula goes here
res += l * (l + 1) // 2
# keep on iterating
i = j
# it is said in the problem to return answer modulo 10 ** 9 + 7
return res % (10 ** 9 + 7) | count-number-of-homogenous-substrings | [Python with illustration] It is just an arithmetic progression | MariaMozgunova | 1 | 66 | count number of homogenous substrings | 1,759 | 0.48 | Medium | 25,258 |
https://leetcode.com/problems/count-number-of-homogenous-substrings/discuss/1064693/Python-O(n)-Solution-with-Explanation | class Solution:
def countHomogenous(self, s: str) -> int:
# Function to calculate total possible substring
# from a contiguous subarray having the same character
def sum_n(n):
return (n * (n + 1)) // 2
i = sumn = 0
n = 1 # The starting value for any character
while i < len(s) - 1:
# Keep incrementing n until different characters are encountered
if s[i] == s[i + 1]:
n += 1
else:
# Add all the cases for that substring and initialize n = 1
sumn += sum_n(n)
n = 1
i += 1
# For the last index of the array (Since, the loop will only run till n - 1)
sumn += sum_n(n)
return sumn % (pow(10, 9) + 7) | count-number-of-homogenous-substrings | Python O(n) Solution with Explanation | Anjani10 | 1 | 89 | count number of homogenous substrings | 1,759 | 0.48 | Medium | 25,259 |
https://leetcode.com/problems/count-number-of-homogenous-substrings/discuss/1064596/Python-Groupby-Method-and-One-Liner | class Solution:
def countHomogenous(self, s: str) -> int:
MOD = 10**9 + 7
groups = [list(g) for k, g in itertools.groupby(s)]
res = 0
for g in groups:
n = len(g)
res += (n + 1) * n // 2
return res % MOD | count-number-of-homogenous-substrings | [Python] Groupby Method and One Liner | rowe1227 | 1 | 64 | count number of homogenous substrings | 1,759 | 0.48 | Medium | 25,260 |
https://leetcode.com/problems/count-number-of-homogenous-substrings/discuss/1064554/Python3-counting-with-anchor | class Solution:
def countHomogenous(self, s: str) -> int:
ans = ii = 0
for i in range(len(s)):
if s[ii] != s[i]: ii = i
ans += i - ii + 1
return ans % 1_000_000_007 | count-number-of-homogenous-substrings | [Python3] counting with anchor | ye15 | 1 | 75 | count number of homogenous substrings | 1,759 | 0.48 | Medium | 25,261 |
https://leetcode.com/problems/count-number-of-homogenous-substrings/discuss/2367181/Python-Super-easy-understand-one-pass | class Solution:
def countHomogenous(self, s: str) -> int:
res = 0
subCount = 0 # count the length of the same character as substring
tmpSum = 0 # count the number of the substrings of each partition(same character)
for i in range(len(s)):
if i > 0 and s[i] != s[i-1]: # if character != prev_character, clear the subCount and tmpSum
res += tmpSum
subCount = 0
tmpSum = 0
subCount += 1
tmpSum += subCount
return (res + tmpSum) % 1000000007 #dont forget to add any tmpSum left | count-number-of-homogenous-substrings | Python Super easy understand one pass | scr112 | 0 | 32 | count number of homogenous substrings | 1,759 | 0.48 | Medium | 25,262 |
https://leetcode.com/problems/count-number-of-homogenous-substrings/discuss/2216949/Python-oror-Easy | class Solution:
def countHomogenous(self, s: str) -> int:
ans = count = 0
x = ' '
for c in s:
if c != x:
count = 1
x = c
else:
count += 1
ans += count
return ans % ((10**9)+7) | count-number-of-homogenous-substrings | Python || Easy | htarab_b | 0 | 37 | count number of homogenous substrings | 1,759 | 0.48 | Medium | 25,263 |
https://leetcode.com/problems/count-number-of-homogenous-substrings/discuss/1694834/Python-easy-two-pointers-solution | class Solution:
def countHomogenous(self, s: str) -> int:
NUM = 10**9 + 7
n = len(s)
i = 0
res = 0
while i < n:
if i< n-1 and s[i] == s[i+1]:
start = i
while i < n-1 and s[i] == s[i+1]:
i += 1
r = i - start + 1
res += r*(r+1)//2
i += 1
else:
i += 1
res += 1
return res % NUM | count-number-of-homogenous-substrings | Python easy two-pointers solution | byuns9334 | 0 | 70 | count number of homogenous substrings | 1,759 | 0.48 | Medium | 25,264 |
https://leetcode.com/problems/count-number-of-homogenous-substrings/discuss/1265221/python3-easy-as-much-possible | class Solution:
def countHomogenous(self, s: str) -> int:
intial=s[0]
index=0
ans=0
calc=lambda x: int((x)*(x+1)/2)
for i in s:
if i!=intial:
intial=i
ans=ans+calc(index)
index=0
index+=1
ans=ans+calc(index)
return ans%1000000007 | count-number-of-homogenous-substrings | python3 easy as much possible | Dr_Negative | 0 | 56 | count number of homogenous substrings | 1,759 | 0.48 | Medium | 25,265 |
https://leetcode.com/problems/count-number-of-homogenous-substrings/discuss/1116348/Python-one-for-loop.-Time%3A-O(N)-Space%3A-O(1) | class Solution:
def countHomogenous(self, s: str) -> int:
result = 0
count = 0
for i in range(len(s) + 1):
if i == 0 or i == len(s) or s[i] != s[i-1]:
result += count * (count + 1) // 2
count = 1
else:
count += 1
return result % (10**9 + 7) | count-number-of-homogenous-substrings | Python, one for-loop. Time: O(N), Space: O(1) | blue_sky5 | 0 | 89 | count number of homogenous substrings | 1,759 | 0.48 | Medium | 25,266 |
https://leetcode.com/problems/count-number-of-homogenous-substrings/discuss/1064712/Python-Quite-short-and-easy-to-understand-answer-(I-think) | class Solution:
def countHomogenous(self, s: str) -> int:
count = 0
start = len(s)
for i in reversed(range(len(s))):
if s[i] != s[i-1] or i==0:
diff = start-i
count += diff*(diff+1)//2
start = i*1
return count % (10**9 + 7) | count-number-of-homogenous-substrings | Python - Quite short and easy to understand answer (I think) | TuanBC | 0 | 29 | count number of homogenous substrings | 1,759 | 0.48 | Medium | 25,267 |
https://leetcode.com/problems/count-number-of-homogenous-substrings/discuss/1064680/Python3-Two-Pointers | class Solution:
def countHomogenous(self, s: str) -> int:
mod = 10 ** 9 + 7
cur, n = 0, 1
for i in range(1, len(s)):
if s[i] == s[cur]:
n += i - cur + 1
else:
cur = i
n += 1
return n % mod | count-number-of-homogenous-substrings | [Python3] Two Pointers | hwsbjts | 0 | 31 | count number of homogenous substrings | 1,759 | 0.48 | Medium | 25,268 |
https://leetcode.com/problems/count-number-of-homogenous-substrings/discuss/1064632/Python3-Intuitive-Solution-Counting-sums-to-the-lengths-of-substrings | class Solution:
def countHomogenous(self, s: str) -> int:
length = len(s)
count = start = 0
for end in range(1, length):
if s[start] != s[end]:
n = end - start
# NUMBER OF COMBINATIONS POSSIBLE IS EQUAL TO SUM TO THAT LENGTH
count += (n * (n + 1)) // 2
start = end
# PERFORMING THE SAME ON THE REST OF THE SUBSTRING
n = end + 1 - start
count += (n * (n + 1)) // 2
return count % 1000000007 | count-number-of-homogenous-substrings | Python3 - Intuitive Solution; Counting sums to the lengths of substrings | AB07 | 0 | 33 | count number of homogenous substrings | 1,759 | 0.48 | Medium | 25,269 |
https://leetcode.com/problems/count-number-of-homogenous-substrings/discuss/1064533/PythonPython3-Count-Number-of-Homogenous-Substrings | class Solution:
def countHomogenous(self, s: str) -> int:
cnt = 0
i = 0
j = 1
while j < len(s):
if s[i] != s[j]:
diff = j-i
cnt += ((diff) * (diff+1)) // 2
i = j
j += 1
else:
j += 1
diff = j-i
cnt += ((diff) * (diff+1)) // 2
return cnt % ((10**9) + 7) | count-number-of-homogenous-substrings | [Python/Python3] Count Number of Homogenous Substrings | newborncoder | 0 | 50 | count number of homogenous substrings | 1,759 | 0.48 | Medium | 25,270 |
https://leetcode.com/problems/minimum-limit-of-balls-in-a-bag/discuss/1064572/Python3-binary-search | class Solution:
def minimumSize(self, nums: List[int], maxOperations: int) -> int:
lo, hi = 1, 1_000_000_000
while lo < hi:
mid = lo + hi >> 1
if sum((x-1)//mid for x in nums) <= maxOperations: hi = mid
else: lo = mid + 1
return lo | minimum-limit-of-balls-in-a-bag | [Python3] binary search | ye15 | 2 | 238 | minimum limit of balls in a bag | 1,760 | 0.603 | Medium | 25,271 |
https://leetcode.com/problems/minimum-limit-of-balls-in-a-bag/discuss/1992180/Python-3-solution-Binary-search | class Solution:
def minimumSize(self, nums: List[int], maxOperations: int) -> int:
n=len(nums);
#a function that will check if the following ans is valid.
def check(x,op):
for i in range(n):
op-=(nums[i]//x);
if(nums[i]%x==0):
op+=1
return True if op>=0 else False;
#binary search the value of ans
#since the min value in the bag can be one
start=1;
end=max(nums);#max value can be taken as upper bound.
ans=-1;
while start<=end:
mid=(start+end)//2
if(check(mid,maxOperations)):
ans=mid;
end=mid-1
else:
start=mid+1;
return ans; | minimum-limit-of-balls-in-a-bag | Python 3 solution Binary search | cubz01 | 1 | 65 | minimum limit of balls in a bag | 1,760 | 0.603 | Medium | 25,272 |
https://leetcode.com/problems/minimum-limit-of-balls-in-a-bag/discuss/1910722/Python-or-Binary-Search-or-Comments | class Solution:
def minimumSize(self, nums: List[int], maxOperations: int) -> int:
# the maximum size increases the minimum number of bags decreases so we can binary search the maximum size
def helper(penalty):
split = 0
for i in nums:
split+=(i-1)//penalty
if split<=maxOperations:
return True
else:
return False
# if we know the maximum size of a bag what is the minimum number of bags you can make
low = 1
heigh = max(nums)
while low<heigh:
mid = (low+heigh)//2
if helper(mid):
heigh = mid
else:
low = mid+1
return low | minimum-limit-of-balls-in-a-bag | 🐍Python | Binary Search | Comments | Brillianttyagi | 1 | 81 | minimum limit of balls in a bag | 1,760 | 0.603 | Medium | 25,273 |
https://leetcode.com/problems/minimum-limit-of-balls-in-a-bag/discuss/1928852/Binary-Search-Solution-oror-90-Faster-oror-Memory-less-than-80 | class Solution:
def isValid(self, nums, maxSize, maxOp):
requiredOp=0
for num in nums:
op=(num-1)//maxSize
requiredOp+=op
return requiredOp<=maxOp
def minimumSize(self, nums, maxOp):
lo=1 ; hi=max(nums)
while lo<hi:
mid=(lo+hi)//2
if self.isValid(nums,mid,maxOp): hi=mid
else: lo=mid+1
return hi | minimum-limit-of-balls-in-a-bag | Binary Search Solution || 90% Faster || Memory less than 80% | Taha-C | 0 | 120 | minimum limit of balls in a bag | 1,760 | 0.603 | Medium | 25,274 |
https://leetcode.com/problems/minimum-limit-of-balls-in-a-bag/discuss/1478573/Python-binary-search-solution | class Solution:
def minimumSize(self, nums: List[int], maxOperations: int) -> int:
l = 1
r = max(nums)
while l < r:
mid = l + (r-l) // 2
count = self.count(mid,nums)
if count <= maxOperations:
r = mid
else:
l = mid+1
return r # or l
def count(self,n,arr):
return sum((a-1) // n for a in arr) | minimum-limit-of-balls-in-a-bag | Python binary search solution | Saura_v | 0 | 163 | minimum limit of balls in a bag | 1,760 | 0.603 | Medium | 25,275 |
https://leetcode.com/problems/minimum-degree-of-a-connected-trio-in-a-graph/discuss/1065724/Python3-brute-force | class Solution:
def minTrioDegree(self, n: int, edges: List[List[int]]) -> int:
graph = [[False]*n for _ in range(n)]
degree = [0]*n
for u, v in edges:
graph[u-1][v-1] = graph[v-1][u-1] = True
degree[u-1] += 1
degree[v-1] += 1
ans = inf
for i in range(n):
for j in range(i+1, n):
if graph[i][j]:
for k in range(j+1, n):
if graph[j][k] and graph[k][i]:
ans = min(ans, degree[i] + degree[j] + degree[k] - 6)
return ans if ans < inf else -1 | minimum-degree-of-a-connected-trio-in-a-graph | [Python3] brute-force | ye15 | 6 | 389 | minimum degree of a connected trio in a graph | 1,761 | 0.417 | Hard | 25,276 |
https://leetcode.com/problems/minimum-degree-of-a-connected-trio-in-a-graph/discuss/1064570/Python-I-kept-getting-TLE-any-advice-on-how-to-optimize-this-further | class Solution:
def minTrioDegree(self, n: int, edges: List[List[int]]) -> int:
for l in edges:
l.sort()
trios = self.findTrios(n, edges)
# Go through each trio
degrees = []
for t in trios:
degree = 0
for e in edges:
otherEdge = any(_ in t for _ in e)
if otherEdge:
degree += 1
# Will find three edges that are part of the trio
degree -= 3
degrees.append(degree)
minDegree = -1 if not degrees else min(degrees)
return minDegree
# Find all trios and return them in a list
def findTrios (self, n, edges) -> List[List[int]]:
trios = []
# For every edge
for edge in edges:
# Check every node
for node in range(1, n+1):
# If the node has an edge to each node in the edge
if sorted([edge[0], node]) in edges and sorted([edge[1], node]) in edges:
# It must be a trio then
trio = sorted([node, edge[0], edge[1]])
if trio not in trios:
trios.append(trio)
return trios | minimum-degree-of-a-connected-trio-in-a-graph | [Python] I kept getting TLE, any advice on how to optimize this further? | scornz | 2 | 383 | minimum degree of a connected trio in a graph | 1,761 | 0.417 | Hard | 25,277 |
https://leetcode.com/problems/minimum-degree-of-a-connected-trio-in-a-graph/discuss/1318010/O(EN)-TLE-and-O(N3)-AC-with-adjacency-list-adjacency-set | class Solution:
def getAdjLists(self, edges):
adj = defaultdict(list)
for u,v in edges:
adj[u].append(v)
adj[v].append(u)
return adj
def getAdjSets(self, edges):
adj = defaultdict(set)
for u,v in edges:
adj[u].add(v)
adj[v].add(u)
return adj
def minTrioDegree1TLE(self, n: int, edges: List[List[int]]) -> int:
# somehow compress the trio so it is considered a single node?
# O(N^3) keep picking random three points, check if trio and
res = math.inf
adj = self.getAdjLists(edges)
adjSet = self.getAdjSets(edges)
for u in range(1,n+1):
for v in adj[u]:
for choice in adj[v]:
if choice in adjSet[u] or u in adjSet[choice]:
# it is a common point!
res = min(res, len(adj[u]) + len(adj[v]) + len(adj[choice]) - 3)
return res if res < math.inf else -1
def minTrioDegree2TLE(self, n: int, edges: List[List[int]]) -> int:
# O(EN) pick any random two connected points(edge), search for
# possible third points e.g. [1,2] is an edge so adj[1] intersect adj[2]
res = math.inf
# after getting this how to get the degree?
# len(adj[1]) + len(adj[2]) + len(adj[3]) - 6 (the trio edges)
adj = self.getAdjSets(edges)
for u,v in edges:
# search for all the 'trio' points
for trio_point in adj[u] & adj[v]:
res = min(res, len(adj[u]) + len(adj[v]) + len(adj[trio_point]) - 3 - 3)
return res if res < math.inf else -1
def minTrioDegree(self, n: int, edges: List[List[int]]) -> int:
# O(N^3) pick any random two connected points(edge), search for
res = math.inf
adj = self.getAdjSets(edges)
for u in range(1,n+1):
for v in range(u+1, n+1):
for trio_point in range(v+1, n+1):
if v in adj[u] and trio_point in adj[u] and trio_point in adj[v]:
res = min(res, len(adj[u]) + len(adj[v]) + len(adj[trio_point]) - 3 - 3)
return res if res < math.inf else -1 | minimum-degree-of-a-connected-trio-in-a-graph | O(EN) TLE and O(N^3) AC with adjacency list / adjacency set | yozaam | 1 | 203 | minimum degree of a connected trio in a graph | 1,761 | 0.417 | Hard | 25,278 |
https://leetcode.com/problems/longest-nice-substring/discuss/1074546/Python3-brute-force-and-divide-and-conquer | class Solution:
def longestNiceSubstring(self, s: str) -> str:
ans = ""
for i in range(len(s)):
for ii in range(i+1, len(s)+1):
if all(s[k].swapcase() in s[i:ii] for k in range(i, ii)):
ans = max(ans, s[i:ii], key=len)
return ans | longest-nice-substring | [Python3] brute-force & divide and conquer | ye15 | 65 | 4,800 | longest nice substring | 1,763 | 0.616 | Easy | 25,279 |
https://leetcode.com/problems/longest-nice-substring/discuss/1074546/Python3-brute-force-and-divide-and-conquer | class Solution:
def longestNiceSubstring(self, s: str) -> str:
if not s: return "" # boundary condition
ss = set(s)
for i, c in enumerate(s):
if c.swapcase() not in ss:
s0 = self.longestNiceSubstring(s[:i])
s1 = self.longestNiceSubstring(s[i+1:])
return max(s0, s1, key=len)
return s | longest-nice-substring | [Python3] brute-force & divide and conquer | ye15 | 65 | 4,800 | longest nice substring | 1,763 | 0.616 | Easy | 25,280 |
https://leetcode.com/problems/longest-nice-substring/discuss/1693408/Python3-From-O(N2)-to-O(N) | class Solution:
def longestNiceSubstring(self, s: str) -> str:
N = len(s)
maxlen = 0
start = 0
for i in range(N):
seen = set()
missing = 0
for j in range(i, N):
# if we haven't seen this "type", add it into the seen set
if s[j] not in seen:
seen.add(s[j])
# since this is the first time we see this "type" of character
# we check if the other half has already been seen before
if (s[j].lower() not in seen) or (s[j].upper() not in seen):
missing += 1 # we haven't seen the other half yet, so adding 1 to the missing type
else: # otherwise we know this character will compensate the other half which we pushed earlier into the set, so we subtract missing "type" by 1
missing -= 1
if missing == 0 and (j - i + 1) > maxlen:
maxlen = j - i + 1
start = i
return s[start:(start + maxlen)] | longest-nice-substring | Python3 - From O(N^2) to O(N) | kiritokun-zys | 30 | 1,400 | longest nice substring | 1,763 | 0.616 | Easy | 25,281 |
https://leetcode.com/problems/longest-nice-substring/discuss/1693408/Python3-From-O(N2)-to-O(N) | class Solution:
def longestNiceSubstring(self, s: str) -> str:
def helper(i: int, j: int):
# string length is less than 2 return empty string
# we return a tuple to indicate the start and end index of the string to avoid unncessary string copy operation
if j - i + 1 < 2: return (0, -1)
hashset = set()
# scan the string once and save all char into a set
for k in range(i, j + 1):
hashset.add(s[k])
for k in range(i, j + 1):
# if this char pairs with its other half, we are good
if s[k].upper() in hashset and s[k].lower() in hashset:
continue
# we found `E` !
slt = helper(i, k - 1)
srt = helper(k + 1, j)
return slt if (slt[1] - slt[0] + 1) >= (srt[1] - srt[0] + 1) else srt
return (i, j)
lt, rt = helper(0, len(s) - 1)
return s[lt:(rt + 1)] | longest-nice-substring | Python3 - From O(N^2) to O(N) | kiritokun-zys | 30 | 1,400 | longest nice substring | 1,763 | 0.616 | Easy | 25,282 |
https://leetcode.com/problems/longest-nice-substring/discuss/1693408/Python3-From-O(N2)-to-O(N) | class Solution:
def longestNiceSubstring(self, s: str) -> str:
def helper(i: int, j: int):
if (j - i + 1) < 2: return (0,-1)
hashset = set()
for k in range(i, j + 1):
hashset.add(s[k])
# use parts array to store position (index) of delimeter in sorted order
parts = [i - 1]
for k in range(i, j + 1):
up = s[k].upper()
lower = s[k].lower()
if (up not in hashset) or (lower not in hashset): # un-paired character
parts.append(k)
parts.append(j+1)
# why do we have i - 1 and j + 1 in the array?
# go through this example aAbbcCEdDEfF
# the subproblems are:
# [0, 5], [7, 8], [10, 11]
max_len_pair = (0, -1)
# if we don't find any delimeter, then the original string is a nice string
if len(parts) == 2:
return (i, j)
# call recursively to solve each subproblem
for i in range(len(parts) - 1):
ni, nj = helper(parts[i] + 1, parts[i+1] - 1)
if (nj - ni + 1) > (max_len_pair[1] - max_len_pair[0] + 1):
max_len_pair = (ni, nj)
return max_len_pair
lt, rt = helper(0, len(s) - 1)
return s[lt:(rt+1)] | longest-nice-substring | Python3 - From O(N^2) to O(N) | kiritokun-zys | 30 | 1,400 | longest nice substring | 1,763 | 0.616 | Easy | 25,283 |
https://leetcode.com/problems/longest-nice-substring/discuss/1074844/Python3-Recursive-Divide-and-Conquer-Solution-(O(n)) | class Solution:
def longestNiceSubstring(self, s: str) -> str:
def divcon(s):
# string with length 1 or less arent considered nice
if len(s) < 2:
return ""
pivot = []
# get every character that is not nice
for i, ch in enumerate(s):
if ch.isupper() and ch.lower() not in s:
pivot.append(i)
if ch.islower() and ch.upper() not in s:
pivot.append(i)
# if no such character return the string
if not pivot:
return s
# divide the string in half excluding the char that makes the string not nice
else:
mid = (len(pivot)) // 2
return max(divcon(s[:pivot[mid]]),divcon(s[pivot[mid]+1:]),key=len)
return divcon(s) | longest-nice-substring | [Python3] Recursive Divide and Conquer Solution (O(n)) | skele | 12 | 1,600 | longest nice substring | 1,763 | 0.616 | Easy | 25,284 |
https://leetcode.com/problems/longest-nice-substring/discuss/1885876/Python-Simple-and-Elegant!-Multiple-Solutions! | class Solution:
def longestNiceSubstring(self, s):
subs = [s[i:j] for i in range(len(s)) for j in range(i+1, len(s)+1)]
nice = [sub for sub in subs if set(sub)==set(sub.swapcase())]
return max(nice, key=len, default="") | longest-nice-substring | Python - Simple and Elegant! Multiple Solutions! | domthedeveloper | 8 | 891 | longest nice substring | 1,763 | 0.616 | Easy | 25,285 |
https://leetcode.com/problems/longest-nice-substring/discuss/1885876/Python-Simple-and-Elegant!-Multiple-Solutions! | class Solution:
def longestNiceSubstring(self, s):
chars = set(s)
for i, c in enumerate(s):
if c.swapcase() not in chars:
return max(map(self.longestNiceSubstring, [s[:i], s[i+1:]]), key=len)
return s | longest-nice-substring | Python - Simple and Elegant! Multiple Solutions! | domthedeveloper | 8 | 891 | longest nice substring | 1,763 | 0.616 | Easy | 25,286 |
https://leetcode.com/problems/longest-nice-substring/discuss/1790784/Python-3-Using-a-decreasing-sliding-window. | class Solution:
def get_nice(self, s: str) -> bool:
return len(set(s.lower())) == (len(set(s)) // 2)
def longestNiceSubstring(self, s: str) -> str:
window_size = len(s)
while window_size:
for i in range(len(s) - window_size + 1):
substring = s[i:i + window_size]
if self.get_nice(substring):
return substring
window_size -= 1
return '' | longest-nice-substring | [Python 3] Using a decreasing sliding window. | seankala | 7 | 1,300 | longest nice substring | 1,763 | 0.616 | Easy | 25,287 |
https://leetcode.com/problems/longest-nice-substring/discuss/1614794/easy-to-understand-python3-solution | class Solution:
def longestNiceSubstring(self, s: str) -> str:
res=""
n=len(s)
for i in range(n):
for j in range(i,n):
if all(ch.swapcase() in s[i:j+1] for ch in s[i:j+1]):
if len(s[i:j+1])>len(res):
res=s[i:j+1]
return res | longest-nice-substring | easy to understand python3 solution | Karna61814 | 3 | 327 | longest nice substring | 1,763 | 0.616 | Easy | 25,288 |
https://leetcode.com/problems/longest-nice-substring/discuss/1515779/Checking-substrings-with-sets-80-speed | class Solution:
def longestNiceSubstring(self, s: str) -> str:
max_len, ans = 0, ""
len_s = len(s)
for start in range(len_s - 1):
if len_s - start < max_len:
break
lower_set = set()
upper_set = set()
for end in range(start, len_s):
if s[end].islower():
lower_set.add(s[end])
else:
upper_set.add(s[end].lower())
if lower_set == upper_set:
if end - start + 1 > max_len:
ans = s[start: end + 1]
max_len = end - start + 1
return ans | longest-nice-substring | Checking substrings with sets, 80% speed | EvgenySH | 3 | 598 | longest nice substring | 1,763 | 0.616 | Easy | 25,289 |
https://leetcode.com/problems/longest-nice-substring/discuss/1371668/Python-3-Recursive-24-ms | class Solution:
def longestNiceSubstring(self, s: str) -> str:
if len(s) < 2:
return ''
hs = set(s)
badchars = {ch for ch in hs if ch.swapcase() not in hs}
if len(badchars) == 0:
return s
if len(hs) == len(badchars):
return ''
substrs = []
lp = 0
for i in range(len(s)):
if s[i] in badchars:
if lp != i:
substrs.append(s[lp: i])
lp = i+1
substrs.append(s[lp:])
return sorted([self.longestNiceSubstring(x) for x in substrs], key=len, reverse=True)[0] | longest-nice-substring | Python 3, Recursive 24 ms | MihailP | 3 | 602 | longest nice substring | 1,763 | 0.616 | Easy | 25,290 |
https://leetcode.com/problems/longest-nice-substring/discuss/2745748/Python-Divide-and-Conquer%3A-30-ms-faster-than-99.10-of-Python3 | class Solution:
def longestNiceSubstring(self, s: str) -> str:
if len(s)<2:
return ""
uVal = set(s)
for i,val in enumerate(s):
if val.swapcase() not in uVal:
r1 = self.longestNiceSubstring(s[0:i])
r2 = self.longestNiceSubstring(s[i+1:])
if len(r2)>len(r1):
return r2
else:
return r1
return s | longest-nice-substring | Python Divide & Conquer: 30 ms, faster than 99.10% of Python3 | rajukancharla | 0 | 10 | longest nice substring | 1,763 | 0.616 | Easy | 25,291 |
https://leetcode.com/problems/longest-nice-substring/discuss/2393271/Python-Solution-or-Recursive-or-100-Faster-or-Divide-and-Conquer | class Solution:
def longestNiceSubstring(self, s: str) -> str:
# base case
if len(s) < 2:
return ""
store = set(list(s))
for i in range(len(s)):
# check if reciprocal value is present or not
# if not, split the string from this point
if s[i].swapcase() not in store:
left = self.longestNiceSubstring(s[:i])
right = self.longestNiceSubstring(s[i+1:])
# we need the largest string
return max(left,right,key=len)
# in case string is nice from initial
return s | longest-nice-substring | Python Solution | Recursive | 100% Faster | Divide and Conquer | Gautam_ProMax | 0 | 123 | longest nice substring | 1,763 | 0.616 | Easy | 25,292 |
https://leetcode.com/problems/longest-nice-substring/discuss/2184563/python-set-solution | class Solution(object):
def longestNiceSubstring(self, s):
"""
:type s: str
:rtype: str
"""
if len(s)==1 or len(s)==0:
return ""
nice=""
for window in range(2,len(s)+1):
for i in range(len(s)-window+1):
string=s[i:window+i]
#print(string)
s1=set(string)
s2=set(string.swapcase())
s1=s1-s2
if len(s1)==0:
if len(nice)<len(string):
nice=string
return nice | longest-nice-substring | python set solution | sayandeep2900 | 0 | 132 | longest nice substring | 1,763 | 0.616 | Easy | 25,293 |
https://leetcode.com/problems/longest-nice-substring/discuss/1266572/Python3-or-Divide-and-Conquer | class Solution:
def longestNiceSubstring(self, s: str) -> str:
if len(s) <= 1:
return ""
upper, lower = [False]*26, [False]*26
for index, letter in enumerate(s):
if letter.isupper():
upper[ord(letter) - ord('A')] = True
else:
lower[ord(letter) - ord('a')] = True
if upper == lower: #self.isequal(upper, lower):
return s
start = 0
ans = ""
for index, x in enumerate(s):
i = ord(x) - ord('a') if x.islower() else ord(x) - ord('A')
if upper[i] != lower[i]:
curr = self.longestNiceSubstring(s[start:index])
start = index+1
if len(curr) > len(ans):
ans = curr
curr = self.longestNiceSubstring(s[start:])
if len(curr) > len(ans):
ans = curr
return ans | longest-nice-substring | Python3 | Divide and Conquer | Sanjaychandak95 | 0 | 238 | longest nice substring | 1,763 | 0.616 | Easy | 25,294 |
https://leetcode.com/problems/longest-nice-substring/discuss/2698175/Python3-Sliding-Window | class Solution:
def longestNiceSubstring(self, s: str) -> str:
niceSubstring = ""
for windowEnd in range(len(s)):
for windowStart in range(windowEnd+1):
substring = s[windowStart:windowEnd+1]
if len(set(substring.lower())) == (len(set(substring)) // 2):
niceSubstring = max(niceSubstring, substring, key=len)
return niceSubstring | longest-nice-substring | Python3 Sliding Window | shor123 | -1 | 86 | longest nice substring | 1,763 | 0.616 | Easy | 25,295 |
https://leetcode.com/problems/longest-nice-substring/discuss/1480107/Divide-and-Conquer-Python | class Solution:
def longestNiceSubstring(self, s: str) -> str:
def isNice(s):
pivot = -1
if len(s) < 2:
return ["", 0]
unorderedSet = set([x for x in s])
for i in range(len(s)):
if ord(s[i])<96:
if s[i].lower() not in unorderedSet:
pivot = i
else:
if s[i].upper() not in unorderedSet:
pivot = i
if pivot>=0:
if pivot == len(s)-1:
return isNice(s[:pivot])
a = isNice(s[:pivot])
b = isNice(s[pivot+1:])
return a if a[1]>=b[1] else b
else:
print(s, len(s))
return [s, len(s)]
[x1, x2] = isNice(s)
return x1 | longest-nice-substring | Divide and Conquer Python | Raniyer | -1 | 395 | longest nice substring | 1,763 | 0.616 | Easy | 25,296 |
https://leetcode.com/problems/form-array-by-concatenating-subarrays-of-another-array/discuss/1074555/Python3-check-group-one-by-one | class Solution:
def canChoose(self, groups: List[List[int]], nums: List[int]) -> bool:
i = 0
for grp in groups:
for ii in range(i, len(nums)):
if nums[ii:ii+len(grp)] == grp:
i = ii + len(grp)
break
else: return False
return True | form-array-by-concatenating-subarrays-of-another-array | [Python3] check group one-by-one | ye15 | 28 | 1,300 | form array by concatenating subarrays of another array | 1,764 | 0.527 | Medium | 25,297 |
https://leetcode.com/problems/form-array-by-concatenating-subarrays-of-another-array/discuss/1074629/Python-3-or-String-built-in-find()-or-Explanation | class Solution:
def canChoose(self, groups: List[List[int]], nums: List[int]) -> bool:
groups = ['-'.join(str(s) for s in group) for group in groups]
nums = '-'.join(str(s) for s in nums)
j = k = 0
while k < len(groups):
group = groups[k]
i = nums.find(group, j)
if i == -1: return False
if i == 0 or i > 0 and nums[i-1] == '-':
j = i + len(group)
k += 1
else: j += 1
return True | form-array-by-concatenating-subarrays-of-another-array | Python 3 | String built-in find() | Explanation | idontknoooo | 2 | 124 | form array by concatenating subarrays of another array | 1,764 | 0.527 | Medium | 25,298 |
https://leetcode.com/problems/form-array-by-concatenating-subarrays-of-another-array/discuss/1197186/Python3-Simple-Approach-with-Comments-beats-94-and-97 | class Solution:
def canChoose(self, groups: List[List[int]], nums: List[int]) -> bool:
k=0
found = 0
j = 0
# traverse the whole nums list,
## if nums[k] is same as the value of 0'th index of a group
## check whether the subarray of nums starting at index k upto index k+len(group)-1 is same as group
## if so, increase k and found variables accordingly
## otherwise increment k
while k<len(nums):
if k==len(nums) or found==len(groups): #reached the end of list nums or matched all the groups
break
if nums[k]==groups[j][0]: #as groups must be in nums in the given order, start checking from group at index 0
if nums[k:k+len(groups[j])]==groups[j]: #check whether the subarray matches the group
found+=1
k+=len(groups[j]) #increase k by the length of the group
j+=1 #increment j
else:
k+=1 #not matched, increment k
else:
k+=1 #nums[k] does not match leftmost value of group, increment k
return found==len(groups) | form-array-by-concatenating-subarrays-of-another-array | Python3 Simple Approach with Comments, beats 94% and 97% | bPapan | 1 | 104 | form array by concatenating subarrays of another array | 1,764 | 0.527 | Medium | 25,299 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.