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/detect-pattern-of-length-m-repeated-k-or-more-times/discuss/1916791/One-for-loop-with-list-slicing | class Solution:
def containsPattern(self, arr: List[int], m: int, k: int) -> bool:
# arr = [1,2,1,1,2,1,1,1,3], m = 3, k = 2
for i in range(len(arr)):
p = arr[i:i+m] # sub-array of length m
if arr[i:i+m*k]==p*k: # check if sub-array of length m*k == p*k
return True
return False | detect-pattern-of-length-m-repeated-k-or-more-times | One for loop with list slicing | back2square1 | 0 | 44 | detect pattern of length m repeated k or more times | 1,566 | 0.436 | Easy | 23,100 |
https://leetcode.com/problems/detect-pattern-of-length-m-repeated-k-or-more-times/discuss/1884940/Python3-Solution | class Solution:
def containsPattern(self, arr: List[int], m: int, k: int) -> bool:
for i in range(len(arr) - m * k + 1):
pattern = arr[i:i + m]
for j in range(k - 1):
if arr[i + m * (j + 1):i + m * (j + 2)] != pattern:
break
if j == k - 2:
return True
return False | detect-pattern-of-length-m-repeated-k-or-more-times | Python3 Solution | hgalytoby | 0 | 41 | detect pattern of length m repeated k or more times | 1,566 | 0.436 | Easy | 23,101 |
https://leetcode.com/problems/detect-pattern-of-length-m-repeated-k-or-more-times/discuss/1480365/One-pass-of-k-slicing-88-speed | class Solution:
def containsPattern(self, arr: List[int], m: int, k: int) -> bool:
len_arr = len(arr)
if len_arr < m * k:
return False
for start in range(len_arr + 1 - m * k):
pattern = arr[start: start + m]
if all(arr[start + i * m: start + (i + 1) * m] == pattern
for i in range(1, k)):
return True
return False | detect-pattern-of-length-m-repeated-k-or-more-times | One pass of k-slicing, 88% speed | EvgenySH | 0 | 118 | detect pattern of length m repeated k or more times | 1,566 | 0.436 | Easy | 23,102 |
https://leetcode.com/problems/detect-pattern-of-length-m-repeated-k-or-more-times/discuss/1022315/Python-3.-Iterate-over-pre-defined-sliding-windows-easy-to-understand | class Solution:
def containsPattern(self, arr: List[int], m: int, k: int) -> bool:
str_arr = str(arr[0])
for ii in range(1, len(arr)):
str_arr += str(arr[ii])
for jj in range(len(arr)-m+1):
pat = str_arr[jj:jj+m]
st_idx = list(range(jj, len(arr)-m+1, m))
cnt = 0
for kk in st_idx:
if str_arr[kk:kk+m] == pat:
cnt = cnt + 1
else:
break
if cnt >= k:
return True
return False | detect-pattern-of-length-m-repeated-k-or-more-times | Python 3. Iterate over pre-defined sliding windows; easy to understand | user4043Xl | 0 | 104 | detect pattern of length m repeated k or more times | 1,566 | 0.436 | Easy | 23,103 |
https://leetcode.com/problems/detect-pattern-of-length-m-repeated-k-or-more-times/discuss/920387/Python-3-faster-than-98.70-Memory-Usage-less-than-100.00 | class Solution:
def containsPattern(self, arr: List[int], m: int, k: int) -> bool:
for i in range(len(arr)):
## length not long enough
if len(arr) - i < m * k:
break
hasPattern = True
# check the value index ranged (i + m, i + m * k -1) against (i, i + m -1) correspondingly
for j in range(m, m*k):
value = arr[i + j]
checkAgainstValue = arr[i + j % m]
if value != checkAgainstValue:
hasPattern = False
break
if hasPattern:
return True
return False | detect-pattern-of-length-m-repeated-k-or-more-times | Python 3 - faster than 98.70%, Memory Usage less than 100.00% | zju3757 | 0 | 222 | detect pattern of length m repeated k or more times | 1,566 | 0.436 | Easy | 23,104 |
https://leetcode.com/problems/detect-pattern-of-length-m-repeated-k-or-more-times/discuss/823157/Intuitive-approach-by-iteratively-search | class Solution:
def containsPattern(self, arr: List[int], m: int, k: int) -> bool:
if m == 1 and k == 1:
return True
mk_len = m * k
arr_str = ''.join(map(lambda e: str(e), arr))
for i in range(len(arr) - m*k + 1):
if arr_str[i:i+mk_len] == arr_str[i:i+m] * k:
return True
return False | detect-pattern-of-length-m-repeated-k-or-more-times | Intuitive approach by iteratively search | puremonkey2001 | 0 | 59 | detect pattern of length m repeated k or more times | 1,566 | 0.436 | Easy | 23,105 |
https://leetcode.com/problems/detect-pattern-of-length-m-repeated-k-or-more-times/discuss/1179938/easy-solution | class Solution:
def containsPattern(self, arr: List[int], m: int, k: int) -> bool:
i=0
d=m
if m >len(arr) or k >len(arr):
return(False)
while d < len(arr):
p=arr[i:d]
count=1
j,l=i+m,d+m
while l<len(arr)+1:
if arr[j:l]==p:
count+=1
else:
break
if count>=k:
return(True)
break
j+=m
l+=m
i+=1
d+=1
return(False) | detect-pattern-of-length-m-repeated-k-or-more-times | easy solution | janhaviborde23 | -1 | 94 | detect pattern of length m repeated k or more times | 1,566 | 0.436 | Easy | 23,106 |
https://leetcode.com/problems/maximum-length-of-subarray-with-positive-product/discuss/819332/Python3-7-line-O(N)-time-and-O(1)-space | class Solution:
def getMaxLen(self, nums: List[int]) -> int:
ans = pos = neg = 0
for x in nums:
if x > 0: pos, neg = 1 + pos, 1 + neg if neg else 0
elif x < 0: pos, neg = 1 + neg if neg else 0, 1 + pos
else: pos = neg = 0 # reset
ans = max(ans, pos)
return ans | maximum-length-of-subarray-with-positive-product | [Python3] 7-line O(N) time & O(1) space | ye15 | 59 | 2,700 | maximum length of subarray with positive product | 1,567 | 0.438 | Medium | 23,107 |
https://leetcode.com/problems/maximum-length-of-subarray-with-positive-product/discuss/1742691/Python-Sol-by-tracking-%2Bve-and-ve-subarray-lengths. | class Solution:
def getMaxLen(self, nums: List[int]) -> int:
max_len = pos = neg = 0
for i in nums:
if i == 0: # Case 1 -> Reset the subarrays
pos = neg = 0
elif i > 0: # Case 2 -> +ve subarray remains +ve and -ve remains -ve after adding the new value
pos += 1 # increment pos
neg = 0 if neg == 0 else neg + 1 # neg remains 0 if it is already 0 otherwise increment it.
else: # Case 3 -> +ve subarray becomes -ve and -ve becomes +ve after adding the new value due to sign reversal.
old_pos = pos
pos = 0 if neg == 0 else neg + 1 # pos becomes 0 if it is neg is 0 otherwise it is neg+1
neg = old_pos + 1 # neg becomes old pos + 1
max_len = max(max_len, pos) # Update the max_len
return max_len | maximum-length-of-subarray-with-positive-product | Python Sol by tracking +ve & -ve subarray lengths. | anCoderr | 11 | 387 | maximum length of subarray with positive product | 1,567 | 0.438 | Medium | 23,108 |
https://leetcode.com/problems/maximum-length-of-subarray-with-positive-product/discuss/1759738/Python-O(n)-simple-solution | class Solution:
def getMaxLen(self, nums: List[int]) -> int:
ans = neg = pos = 0
for x in nums:
if x > 0:
if neg > 0:
neg += 1
pos += 1
elif x < 0:
neg, pos = pos+1, (neg+1 if neg else 0)
else:
neg = pos = 0
ans = max(ans, pos)
return ans | maximum-length-of-subarray-with-positive-product | Python O(n) simple solution | DaiSier | 8 | 566 | maximum length of subarray with positive product | 1,567 | 0.438 | Medium | 23,109 |
https://leetcode.com/problems/maximum-length-of-subarray-with-positive-product/discuss/1790137/Python3-O(n)-time-O(1)-space | class Solution:
def getMaxLen(self, nums: List[int]) -> int:
curLenPos = 0
curLenNeg = 0
ans = 0
for num in nums:
if num > 0:
curLenPos,curLenNeg = curLenPos + 1, curLenNeg + 1 if curLenNeg != 0 else 0
elif num < 0:
curLenNeg,curLenPos = curLenPos + 1, curLenNeg + 1 if curLenNeg != 0 else 0
else:
curLenNeg = 0
curLenPos = 0
ans = max(ans,curLenPos)
return ans | maximum-length-of-subarray-with-positive-product | Python3 O(n) time O(1) space | Yihang-- | 6 | 287 | maximum length of subarray with positive product | 1,567 | 0.438 | Medium | 23,110 |
https://leetcode.com/problems/maximum-length-of-subarray-with-positive-product/discuss/1487643/Beats-100-or-Detailed-Explanation-or-From-Beginner-to-Pro-or-Python | class Solution:
def findMax(self,start,end,totalNegitive,firstNegitive,lastNegitive):
if totalNegitive%2==0:
return end+1-start
else:
if firstNegitive:
return max(lastNegitive-start,end-firstNegitive)
else:
return end-start
def getMaxLen(self, nums: List[int]) -> int:
start=0
totalNegitive=0
firstNegitive=None
lastNegitive=None
result=0
for end,value in enumerate(nums):
if value<0:
totalNegitive+=1
if firstNegitive is None:
firstNegitive=end
lastNegitive=end
elif value==0:
if start==end:
start+=1
continue
result=max(result,self.findMax(start,end-1,totalNegitive,firstNegitive,lastNegitive))
start=end+1
lastNegitive=None
firstNegitive=None
totalNegitive=0
result=max(result,self.findMax(start,end,totalNegitive,firstNegitive,lastNegitive))
return result | maximum-length-of-subarray-with-positive-product | Beats 100% | Detailed Explanation | From Beginner to Pro | Python | kshitijb | 2 | 498 | maximum length of subarray with positive product | 1,567 | 0.438 | Medium | 23,111 |
https://leetcode.com/problems/maximum-length-of-subarray-with-positive-product/discuss/839439/Python-Greedy-Solution | class Solution:
def getMaxLen(self, nums: List[int]) -> int:
def helper(nums):
result = 0
positiveSoFar = 0
negativeSoFar = 0
for i in range(len(nums)):
if nums[i] == 0:
positiveSoFar = 0
negativeSoFar = 0
elif nums[i] > 0 :
positiveSoFar += 1
if negativeSoFar > 0:
negativeSoFar += 1
elif nums[i] < 0:
if negativeSoFar > 0:
positiveSoFar = max(negativeSoFar, positiveSoFar) +1
negativeSoFar = 0
else:
negativeSoFar = positiveSoFar + 1
positiveSoFar = 0
result = max(result, positiveSoFar)
return result
# scan from left and scan from right
return max(helper(nums), helper(nums[::-1])) | maximum-length-of-subarray-with-positive-product | Python Greedy Solution | pochy | 2 | 318 | maximum length of subarray with positive product | 1,567 | 0.438 | Medium | 23,112 |
https://leetcode.com/problems/maximum-length-of-subarray-with-positive-product/discuss/1689625/A-fast-O(n)-Python-solution | class Solution:
def getMaxLen(self, nums: List[int]) -> int:
n = len(nums)
start = 0
neg_places = [] # track placement of negatives, and how many there are
longest = 0
# Note adding a zero to the end of the array for the loop because when x==0 we check lengths and update
for i, x in enumerate(nums+[0]):
# We don't need to do anything but increment 'i' if x>0, which 'enumerate' does for us
if x < 0:
neg_places.append(i)
elif x == 0:
# If x==0, we need to cut off our array, because every sub-array containing 0 has product=0
# So measure max length of the last subarray, and start fresh from there
# In fact, we don't need to measure the subarray's length at any other time, since it can always grows unless it hits 0
try_len = i-start
if len(neg_places) % 2 == 1:
# positive products require an even number of negatives, otherwise need to cut off subarray from left or right side
try_len = max(i-neg_places[0]-1, neg_places[-1]-start)
longest = max(try_len, longest) # standard to update longest, our returned variable, if the new subarray's length is bigger
start = i+1
neg_places = []
return longest | maximum-length-of-subarray-with-positive-product | A fast O(n) Python solution | briancoj | 1 | 197 | maximum length of subarray with positive product | 1,567 | 0.438 | Medium | 23,113 |
https://leetcode.com/problems/maximum-length-of-subarray-with-positive-product/discuss/822633/Python-O(n)-or-Split-on-0-or-Explanation | class Solution:
def getMaxLen(self, nums: List[int]) -> int:
start = 0 ## starting index of subarray
ans = 0
first_neg, last_neg = -1, -1 ## first and last negative initially -1
c = 0 ## count of negative numbers in the subarray
for i in range(len(nums)):
if nums[i] < 0:
if first_neg!=-1:
last_neg = i ## if first negative is assigned
else:
first_neg = i ## assign first negative of subarray
c += 1 ## increase count of negative by 1
elif nums[i] == 0: ## when 0 is encountered i.e breaking point of the subarray
if c%2!=0: ## if there are odd number of negative numbers
# max(last negative - starting point, end - first negative + 1, first negative to starting point)
# the term in max is for only one negative number in the subarray
ans = max(last_neg - start, i - first_neg - 1, first_neg - start, ans)
else:
ans = max(i - start, ans) ## when even number of negative numbers, just length of subarray
start = i + 1
c = 0
first_neg, last_neg = -1, -1
## after the array ends we need to check the same condition since the last subarray might not end with 0
if c%2!=0:
ans = max(last_neg - start, len(nums) - first_neg - 1, first_neg- start, ans)
else:
ans = max(len(nums) - start, ans)
return ans | maximum-length-of-subarray-with-positive-product | Python O(n) | Split on 0 | Explanation | mihirrane | 1 | 137 | maximum length of subarray with positive product | 1,567 | 0.438 | Medium | 23,114 |
https://leetcode.com/problems/maximum-length-of-subarray-with-positive-product/discuss/2801449/Python-(Simple-Dynamic-Programming) | class Solution:
def getMaxLen(self, nums):
n = len(nums)
pos, neg = [0]*n, [0]*n
pos[0] = 1 if nums[0] > 0 else 0
neg[0] = 1 if nums[0] < 0 else 0
for i in range(1,n):
if nums[i] > 0:
pos[i] = pos[i-1] + 1
neg[i] = neg[i-1] + 1 if neg[i-1] > 0 else 0
elif nums[i] < 0:
pos[i] = neg[i-1] + 1 if neg[i-1] > 0 else 0
neg[i] = pos[i-1] + 1
return max(pos) | maximum-length-of-subarray-with-positive-product | Python (Simple Dynamic Programming) | rnotappl | 0 | 2 | maximum length of subarray with positive product | 1,567 | 0.438 | Medium | 23,115 |
https://leetcode.com/problems/maximum-length-of-subarray-with-positive-product/discuss/2743162/Simple-Fast-and-*Readable*-Python-Explained.-O(n)-Time-O(1)-Space. | class Solution:
def getMaxLen(self, nums: List[int]) -> int:
positive = 0
negative = 0
max_len = 0
for num in nums:
if num == 0:
# Case 1: Reset our subarrays.
positive = 0
negative = 0
elif num > 0:
# Case 2: Add to our positive subarray and, if it exists, our negative subarray.
if negative:
negative += 1
positive += 1
else:
# Case 3: Flip the positive and negative subarrays.
new_positive = 0
if negative:
new_positive = negative + 1
negative, positive = positive + 1, new_positive
max_len = max(max_len, positive)
return max_len | maximum-length-of-subarray-with-positive-product | Simple, Fast, and *Readable* Python Explained. O(n) Time, O(1) Space. | ShippingContainer | 0 | 9 | maximum length of subarray with positive product | 1,567 | 0.438 | Medium | 23,116 |
https://leetcode.com/problems/maximum-length-of-subarray-with-positive-product/discuss/2704472/Easy-to-understand-O(n)-Python-solution-(Beat-90) | class Solution:
def getMaxLen(self, nums: List[int]) -> int:
neg, pos, res = 0, 0, 0
for n in nums:
new_neg, new_pos = 0, 0
# n is positvie
if n > 0:
new_pos = pos + 1
new_neg = neg + 1 if neg else 0
# n is negative
elif n < 0:
new_pos = neg + 1 if neg > 0 else 0
new_neg = pos + 1
pos, neg = new_pos, new_neg
# β coverded situation that n == 0
# update res
res = max(res, pos)
return res | maximum-length-of-subarray-with-positive-product | Easy to understand O(n) Python solution (Beat 90%) | Vansterochrhoger | 0 | 11 | maximum length of subarray with positive product | 1,567 | 0.438 | Medium | 23,117 |
https://leetcode.com/problems/maximum-length-of-subarray-with-positive-product/discuss/2524420/Easy-python-solution-TC%3A-O(N) | class Solution:
def getMaxLen(self, nums: List[int]) -> int:
dp=[-1]*len(nums)
neg=[]
ze=-1
for i in range(len(nums)):
if nums[i]==0:
dp[i]=0
neg=[]
ze=i
else:
if nums[i]<0:
if len(neg)%2==1:
if ze==-1:
dp[i]=i+1
else:
dp[i]=i-ze
else:
if neg==[]:
dp[i]=0
else:
dp[i]=i-neg[0]
neg.append(i)
else:
if len(neg)%2==0:
if ze==-1:
dp[i]=i+1
else:
dp[i]=i-ze
else:
dp[i]=i-neg[0]
return max(dp) | maximum-length-of-subarray-with-positive-product | Easy python solution TC: O(N) | shubham_1307 | 0 | 88 | maximum length of subarray with positive product | 1,567 | 0.438 | Medium | 23,118 |
https://leetcode.com/problems/maximum-length-of-subarray-with-positive-product/discuss/2511965/Python-runtime-90.21-memory-43.69 | class Solution:
def getMaxLen(self, nums: List[int]) -> int:
pos = [0]
neg = [0]
for n in nums:
if n == 0:
pos.append(0)
neg.append(0)
elif n > 0:
pos.append(pos[-1]+1)
if neg[-1] != 0:
neg.append(neg[-1]+1)
else:
neg.append(neg[-1])
else:
if neg[-1] != 0:
pos.append(neg[-1]+1)
else:
pos.append(neg[-1])
neg.append(pos[-2]+1)
return max(pos) | maximum-length-of-subarray-with-positive-product | Python, runtime 90.21%, memory 43.69% | tsai00150 | 0 | 92 | maximum length of subarray with positive product | 1,567 | 0.438 | Medium | 23,119 |
https://leetcode.com/problems/maximum-length-of-subarray-with-positive-product/discuss/2511965/Python-runtime-90.21-memory-43.69 | class Solution:
def getMaxLen(self, nums: List[int]) -> int:
ans = negCount = curCount = 0
zeroPos = firstNegPos = -1
for i, e in enumerate(nums):
if e == 0:
negCount = 0
zeroPos = firstNegPos = i
continue
elif e < 0:
negCount += 1
if negCount == 1:
firstNegPos = i
if negCount%2 == 0:
ans = max(ans, i-zeroPos)
else:
ans = max(ans, i-firstNegPos)
return ans | maximum-length-of-subarray-with-positive-product | Python, runtime 90.21%, memory 43.69% | tsai00150 | 0 | 92 | maximum length of subarray with positive product | 1,567 | 0.438 | Medium | 23,120 |
https://leetcode.com/problems/maximum-length-of-subarray-with-positive-product/discuss/2483418/Yet-another-python-O(n)-O(n)-lazy-solution | class Solution:
def splitZeros(self, nums: List[int]) -> tuple:
# partition into nonzero consecutive subarrays
# with detecting negative elements local indices
nnz, nnz_buf = [], []
negs, negs_buf = [], []
i = 0
for num in nums:
if num != 0:
nnz_buf.append(num)
if num < 0:
negs_buf.append(i)
i += 1
else:
if nnz_buf:
nnz.append(nnz_buf)
negs.append(negs_buf)
nnz_buf, negs_buf = [], []
i = 0
if nnz_buf:
nnz.append(nnz_buf)
negs.append(negs_buf)
return nnz, negs
def getMaxLenNnz(self, nums: List[int], neg_pos: List[int]) -> int:
n = len(nums)
if len(neg_pos) % 2 == 0:
# even number of negative entries, can take all elements
return len(nums)
else:
# odd number of negative entries, we can remove
# first negative and use all elements to the right, or
# last negative and use all elements to the left
# any other positive subarrays will be subarrays of
# these two
return max(n - neg_pos[0] - 1, neg_pos[-1])
def getMaxLen(self, nums: List[int]) -> int:
# consider only nonzero subarrays divided by 0s
# as zeros breaks positivity
nnz, negs = self.splitZeros(nums)
# check if we have any nonzero elements
# function will return nonempty nnz list if there is atleast one
if not nnz:
return 0
# simply max of all nonzero subarrays max positive lengths
return max(self.getMaxLenNnz(*args) for args in zip(nnz, negs)) | maximum-length-of-subarray-with-positive-product | Yet another python O(n) O(n) lazy solution | thatdeep | 0 | 78 | maximum length of subarray with positive product | 1,567 | 0.438 | Medium | 23,121 |
https://leetcode.com/problems/maximum-length-of-subarray-with-positive-product/discuss/2470577/Python-dp-with-space-compression | class Solution:
def getMaxLen(self, nums: List[int]) -> int:
# p[i] represents the maximum length of subarray with positive product
# including nums[i]
p = 0
# n[i] represents the maximum length of subarray with positive product
# including nums[i]
n = 0
# Initialization
if nums[0] > 0:
p = 1
elif nums[0] < 0:
n = 1
res = p
# dp state transfer
for i in range(1, len(nums)):
if nums[i] == 0:
p = 0
n = 0
elif nums[i] > 0:
p = p + 1
n = n + 1 if n else 0
else:
temp = n
n = p + 1
p = temp + 1 if temp else 0
res = max(res, p)
return res | maximum-length-of-subarray-with-positive-product | Python dp with space compression | Aden-Q | 0 | 36 | maximum length of subarray with positive product | 1,567 | 0.438 | Medium | 23,122 |
https://leetcode.com/problems/maximum-length-of-subarray-with-positive-product/discuss/2470428/Python-sliding-window-O(N)-time-O-(1)-space-solution | class Solution:
def getMaxLen(self, nums: List[int]) -> int:
nums.append(0)
left, right = 0, 0
res = 0
while left < len(nums) and right < len(nums):
if nums[left] == 0:
left += 1
continue
# left points to the first nonzero element in the list
neg_cnt = 0
first_neg_idx = -1
last_neg_idx = -1
right = left
while nums[right] != 0:
if nums[right] < 0:
if first_neg_idx == -1:
first_neg_idx = right
last_neg_idx = right
neg_cnt += 1
right += 1
if neg_cnt % 2 == 0:
res = max(res, right - left)
else:
res = max(res, right - first_neg_idx - 1)
res = max(res, last_neg_idx - left)
left = right + 1
return res | maximum-length-of-subarray-with-positive-product | Python sliding window O(N) time O (1) space solution | Aden-Q | 0 | 63 | maximum length of subarray with positive product | 1,567 | 0.438 | Medium | 23,123 |
https://leetcode.com/problems/maximum-length-of-subarray-with-positive-product/discuss/2401873/python-O(n) | class Solution:
def getMaxLen(self, nums: List[int]) -> int:
start = 0
neg = 0
sn = -1
en = -1
ans = 0
for i in range(len(nums)):
if nums[i] < 0:
neg += 1
if sn == -1:
sn = i
en = i
elif nums[i] == 0:
if neg % 2 == 0:
ans = max(ans , (i - start))
else:
ans = max(ans ,(i - (sn + 1)) ,(en - start))
start = i + 1
neg = 0
sn = -1
en = -1
if neg % 2 == 0:
ans = max(ans , len(nums) - start)
else:
ans = max(ans ,(len(nums) - (sn + 1)) ,(en - start))
return ans | maximum-length-of-subarray-with-positive-product | python O(n) | akashp2001 | 0 | 125 | maximum length of subarray with positive product | 1,567 | 0.438 | Medium | 23,124 |
https://leetcode.com/problems/maximum-length-of-subarray-with-positive-product/discuss/2292274/Python-O(n)-runtime-O(1)-space | class Solution:
def getMaxLen(self, nums: List[int]) -> int:
if len(nums) == 1:
return 1 if nums[0] > 0 else 0
negative_count = 0
first_negative_index = -1
max_len = 0
nearest_zero_point = -1
for i,n in enumerate(nums):
if n == 0:
nearest_zero_point = i
negative_count = 0
first_negative_index = -1
continue
if n < 0:
negative_count += 1
if first_negative_index == -1:
first_negative_index = i
if negative_count % 2 == 0:
max_len = max(max_len, i - nearest_zero_point)
else:
max_len = max(max_len, min(i - first_negative_index, i - nearest_zero_point))
return max_len | maximum-length-of-subarray-with-positive-product | Python O(n) runtime O(1) space | JimmyZhu1234 | 0 | 101 | maximum length of subarray with positive product | 1,567 | 0.438 | Medium | 23,125 |
https://leetcode.com/problems/maximum-length-of-subarray-with-positive-product/discuss/1849793/Python-One-Pass-or-First-ever-solution-posted-by-me | class Solution:
def getMaxLen(self, nums: List[int]) -> int:
n=len(nums)
totalNeg, firstNegIndex, lastNegIndex = 0, n, -1
start = maxLength = 0
for i,num in enumerate(nums):
#if zero, divide the array into subarray and calculate maxLength until now
if num==0:
if totalNeg%2==0:#even negatives
currLength = i- start
else:
currLength = max(firstNegIndex-start, i-firstNegIndex-1, lastNegIndex-start, i-lastNegIndex-1)
maxLength = max(maxLength,currLength)
#reset the counters
totalNeg, firstNegIndex, lastNegIndex = 0, n, -1
start=i+1
elif num<0:
#if negative, update the counters
totalNeg+=1
firstNegIndex=min(firstNegIndex,i)
lastNegIndex=i
else:
continue
if totalNeg%2==0:
currLength = i- start+1
else:
currLength = max(firstNegIndex-start, i-firstNegIndex, lastNegIndex-start, i-lastNegIndex)
maxLength = max(maxLength,currLength)
return maxLength | maximum-length-of-subarray-with-positive-product | Python One Pass | First ever solution posted by me | deepanksinghal | 0 | 317 | maximum length of subarray with positive product | 1,567 | 0.438 | Medium | 23,126 |
https://leetcode.com/problems/maximum-length-of-subarray-with-positive-product/discuss/1750840/Python%3A-Calculate-lengths-using-indexes | class Solution:
def getMaxLen(self, nums: List[int]) -> int:
"""
All subarrays can be found between zeroes. When there are negative numbers involved, we
only care about calculating the lengths of subarrays containing even number of negative
numbers, otherwise the product of subarray is negative.
When do we know a subarray has even number (0, 2, 4, etc) of negative numbers? When product
is positive.
What about negative (1, 3, 5, etc)? When product is negative.
For this problem, we don't care about the actual product, only the sign.
Let's take this example:
[1,-2,3,-4,5,-6,7,8]
The product is a negative, so there are two subarrays within this array we need to consider:
[1,-2,3,-4,5]
[3,-4,5,-6,7,8]
Obviously the second subarray is longer, but how do we get this?
We just need to keep track of the product as we iterate through the array. If the product is
positive, we should calculate the length using current index and subtract the index of the
beginning of array (value 1 in the example).
If the product is negative, we should exclude the numbers leading up to the first negative number,
which is -2 in the example. So the length for that is current index minus the index after
the first negative number (value 3 in the example).
"""
i = j = output = 0
curr = 1
for idx, num in enumerate(nums):
if not num:
i = j = idx + 1
curr = 1
else:
if num < 0 and i == j:
j = idx + 1
curr /= 1 if num > 0 else -1
if curr > 0:
output = max(output, idx - i + 1)
else:
output = max(output, idx - j + 1)
return output | maximum-length-of-subarray-with-positive-product | Python: Calculate lengths using indexes | johnro | 0 | 184 | maximum length of subarray with positive product | 1,567 | 0.438 | Medium | 23,127 |
https://leetcode.com/problems/maximum-length-of-subarray-with-positive-product/discuss/1706310/2-pass-scan-beats-100-memory.-O(n)-time-O(1)-space | class Solution:
def getMaxLen(self, nums: List[int]) -> int:
# reduce calculation time
for i, n in enumerate(nums):
if n < 0:
nums[i] = -1
elif n > 0:
nums[i] = 1
# from left to right, and from right to left
return max(self.getMaxLength(nums), self.getMaxLength(nums[::-1]))
def getMaxLength(self, nums: List[int]) -> int:
if not nums:
return 0
maxLen, curLen, curP = 0, 0, 1
for n in nums:
curP *= n
curLen += 1
if curP > 0:
maxLen = max(maxLen, curLen)
elif curP == 0:
curP = 1
curLen = 0
return maxLen | maximum-length-of-subarray-with-positive-product | 2 pass scan, beats 100% memory. O(n) time, O(1) space | r04922101 | 0 | 144 | maximum length of subarray with positive product | 1,567 | 0.438 | Medium | 23,128 |
https://leetcode.com/problems/maximum-length-of-subarray-with-positive-product/discuss/1691863/Split-the-array-int-subarray-with-no-zero-element.-and-then-calculate-the-maximum-length-of-it | class Solution:
def getMaxLen(self, nums: List[int]) -> int:
num_size = len(nums) - 1
# Edge case for only one element.
if num_size == 0:
return 1 if nums[0] > 0 else 0
def _find_max_len(bi, ei, ni_list):
"""Find maximum length.
Args:
bi: Begin position index
ei: End position index (inclusive)
ni_list: List of position index with negative value.
Returns:
The maxinum length of subarray with positive product.
"""
if len(ni_list) % 2 == 0:
return ei - bi + 1
elif len(ni_list) == 1:
return max(abs(bi-ni_list[0]), abs(ei-ni_list[0]))
else:
return max(
ni_list[-2] - min(bi, ni_list[0]) + 1,
ni_list[-1] - min(bi, ni_list[0]),
ei - ni_list[1] + 1,
ei - ni_list[0],
)
ans = bi = 0
ni_list = []
# Look for subarray with all elements as not zero.
for i, v in enumerate(nums):
if v == 0:
ans = max(ans, _find_max_len(bi, i-1, ni_list))
ni_list = []
bi = i+1
elif v < 0:
ni_list.append(i)
if bi < num_size:
ans = max(ans, _find_max_len(bi, num_size, ni_list))
return ans | maximum-length-of-subarray-with-positive-product | Split the array int subarray with no zero element. and then calculate the maximum length of it | puremonkey2001 | 0 | 108 | maximum length of subarray with positive product | 1,567 | 0.438 | Medium | 23,129 |
https://leetcode.com/problems/maximum-length-of-subarray-with-positive-product/discuss/1601136/Python3-One-pass-solution | class Solution:
def getMaxLen(self, nums: List[int]) -> int:
res = neg = pos = 0
for i in range(len(nums)):
if nums[i] > 0:
pos += 1
if neg != 0:
neg += 1
elif nums[i] < 0:
neg, pos = pos, neg
neg += 1
if pos != 0:
pos += 1
else:
neg = 0
pos = 0
res = max(res, pos)
return res | maximum-length-of-subarray-with-positive-product | [Python3] One pass solution | maosipov11 | 0 | 177 | maximum length of subarray with positive product | 1,567 | 0.438 | Medium | 23,130 |
https://leetcode.com/problems/maximum-length-of-subarray-with-positive-product/discuss/861226/Python-Simple-and-concise-linear-time-solution-O(1)-space | class Solution:
@staticmethod
def process(st, end, cnt_neg, arr):
if st >= 0 and st <= end and end >= 0:
if not (cnt_neg % 2):
return end - st + 1
first_neg_ind = st
last_neg_ind = end
while(first_neg_ind <= end and arr[first_neg_ind] >= 0):
first_neg_ind += 1
while(last_neg_ind >= st and arr[last_neg_ind] >= 0):
last_neg_ind -= 1
print((st, end, first_neg_ind, last_neg_ind))
return max(last_neg_ind - st, end - first_neg_ind)
return 0
def getMaxLen(self, nums: List[int]) -> int:
prev = 0
ans = 0
cnt_neg = 0
for i in range(len(nums)):
if not nums[i]:
ans = max(ans, Solution.process(prev, i-1, cnt_neg, nums))
prev = i + 1
cnt_neg = 0
if nums[i] < 0:
cnt_neg += 1
ans = max(ans, Solution.process(prev, len(nums)-1, cnt_neg, nums))
return ans | maximum-length-of-subarray-with-positive-product | [Python] Simple and concise linear time solution O(1) space | vasu6 | 0 | 108 | maximum length of subarray with positive product | 1,567 | 0.438 | Medium | 23,131 |
https://leetcode.com/problems/minimum-number-of-days-to-disconnect-island/discuss/819360/Python3-bfs | class Solution:
def minDays(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0]) # dimension
grid = "".join("".join(map(str, x)) for x in grid)
@lru_cache(None)
def fn(s):
"""Return True if grid is disconnected."""
row, grid = [], []
for i, c in enumerate(s, 1):
row.append(int(c))
if i%n == 0:
grid.append(row)
row = []
def dfs(i, j):
""""""
grid[i][j] = 0
for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j):
if 0 <= ii < m and 0 <= jj < n and grid[ii][jj]: dfs(ii, jj)
return 1
return sum(dfs(i, j) for i in range(m) for j in range(n) if grid[i][j])
#bfs
queue = [grid]
level = 0
seen = {grid}
while queue:
tmp = []
for node in queue:
if fn(node) == 0 or fn(node) >= 2: return level
for i in range(m*n):
if node[i] == "1":
nn = node[:i] + "0" + node[i+1:]
if nn not in seen:
seen.add(nn)
tmp.append(nn)
queue = tmp
level += 1 | minimum-number-of-days-to-disconnect-island | [Python3] bfs | ye15 | 0 | 66 | minimum number of days to disconnect island | 1,568 | 0.468 | Hard | 23,132 |
https://leetcode.com/problems/number-of-ways-to-reorder-array-to-get-same-bst/discuss/819349/Python3-math-ish | class Solution:
def numOfWays(self, nums: List[int]) -> int:
def fn(nums):
"""Post-order traversal."""
if len(nums) <= 1: return len(nums) # boundary condition
ll = [x for x in nums if x < nums[0]]
rr = [x for x in nums if x > nums[0]]
left, right = fn(ll), fn(rr)
if not left or not right: return left or right
ans = comb(len(rr)+len(ll), len(rr))
return ans*left*right
return (fn(nums)-1) % 1_000_000_007 | number-of-ways-to-reorder-array-to-get-same-bst | [Python3] math-ish | ye15 | 2 | 337 | number of ways to reorder array to get same bst | 1,569 | 0.481 | Hard | 23,133 |
https://leetcode.com/problems/number-of-ways-to-reorder-array-to-get-same-bst/discuss/2783524/A-cheating-way | class Solution:
def numOfWays(self, nums: List[int]) -> int:
FACT = [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800, 479001600, 227020758, 178290591, 674358851, 789741546, 425606191, 660911389, 557316307, 146326063, 72847302, 602640637, 860734560, 657629300, 440732388, 459042011, 394134213, 35757887, 36978716, 109361473, 390205642, 486580460, 57155068, 943272305, 14530444, 523095984, 354551275, 472948359, 444985875, 799434881, 776829897, 626855450, 954784168, 10503098, 472639410, 741412713, 846397273, 627068824, 726372166, 318608048, 249010336, 948537388, 272481214, 713985458, 269199917, 75195247, 286129051, 595484846, 133605669, 16340084, 996745124, 798197261, 286427093, 331333826, 536698543, 422103593, 280940535, 103956247, 172980994, 108669496, 715534167, 518459667, 847555432, 719101534, 932614679, 878715114, 661063309, 562937745, 472081547, 766523501, 88403147, 249058005, 671814275, 432398708, 753889928, 834533360, 604401816, 187359437, 674989781, 749079870, 166267694, 296627743, 586379910, 119711155, 372559648, 765725963, 275417893, 990953332, 104379182, 437918130, 229730822, 432543683, 551999041, 407899865, 829485531, 925465677, 24826746, 681288554, 260451868, 649705284, 117286020, 136034149, 371858732, 391895154, 67942395, 881317771, 114178486, 473061257, 294289191, 314702675, 79023409, 640855835, 825267159, 333127002, 640874963, 750244778, 281086141, 979025803, 294327705, 262601384, 400781066, 903100348, 112345444, 54289391, 329067736, 753211788, 190014235, 221964248, 853030262, 424235847, 817254014, 50069176, 159892119, 24464975, 547421354, 923517131, 757017312, 38561392, 745647373, 847105173, 912880234, 757794602, 942573301, 156287339, 224537377, 27830567, 369398991, 365040172, 41386942, 621910678, 127618458, 674190056, 892978365, 448450838, 994387759, 68366839, 417262036, 100021558, 903643190, 619341229, 907349424, 64099836, 89271551, 533249769, 318708924, 92770232, 420330952, 818908938, 584698880, 245797665, 489377057, 66623751, 192146349, 354927971, 661674180, 71396619, 351167662, 19519994, 689278845, 962979640, 929109959, 389110882, 98399701, 89541861, 460662776, 289903466, 110982403, 974515647, 928612402, 722479105, 218299090, 96415872, 572421883, 774063320, 682979494, 693774784, 611379287, 166890807, 880178425, 837467962, 705738750, 616613957, 338771924, 497191232, 896114138, 560652457, 661582322, 224945188, 262995829, 859081981, 857116478, 279856786, 408062844, 406076419, 367193638, 985761614, 767884817, 77737051, 801784560, 410447512, 813374614, 702909132, 777826615, 11426636, 685259446, 721228129, 931065383, 593559607, 860745086, 578819198, 495425745, 893029457, 6156532, 502193801, 37480384, 220174401, 383076669, 3013247, 750298503, 574624441, 230733683, 144887710, 656590378, 773954850, 358485371, 772254339, 469363737, 95843299, 823414273, 87709482, 892174648, 749756145, 185864756, 68295241, 98238739, 131504392, 111672419, 928208089, 687974198, 753032165, 71715287, 506557931, 290314197, 546089425, 174590825, 187067364, 817659471, 309331349, 303445769, 964814732, 112937795, 848457973, 113604679, 263728612, 162653895, 519013648, 956915940, 591788795, 26960558, 818561771, 201473695, 830318534, 283328761, 298655153, 103269519, 567777414, 629890782, 707451727, 528064896, 419467694, 259775012, 452053078, 972081682, 512829263, 412924123, 354780756, 917691336, 648929514, 519218426, 957710940, 848100261, 607279584, 78508462, 651656900, 271922065, 927371945, 976904514, 655633282, 147015495, 44958071, 431540693, 956102180, 821001984, 4640954, 508310043, 709072863, 866824584, 318461564, 773853828, 371761455, 53040744, 609526889, 972452623, 799173814, 723225821, 3874155, 305590228, 289496343, 139259591, 348260611, 756867525, 848691744, 101266155, 835557082, 267191274, 448180160, 518514435, 443022120, 614718802, 151579195, 204297074, 912569551, 137049249, 515433810, 979001276, 524451820, 229298431, 88837724, 892742699, 387369393, 840349900, 206661672, 18186411, 619853562, 246548548, 236767938, 893832644, 930410696, 321544423, 971435684, 402636244, 780681725, 194281388, 661238608, 964476271, 643075362, 439409780, 96895678, 723461710, 915447882, 785640606, 114709392, 933696835, 539582134, 739120141, 300372431, 244129985, 722433522, 26638091, 388855420, 42468156, 647517040, 474194942, 832805846, 958306874, 489519451, 339220689, 9833277, 923477502, 390998217, 790283925, 694135631, 736657340, 609563281, 873127083, 489593220, 264439147, 891171227, 489029295, 502009550, 325923608, 280525558, 857054649, 820622208, 558213940, 216997416, 487921842, 951328535, 606653379, 794417402, 449723904, 783486165, 414645478, 809681447, 114612567, 824953206, 255016498, 147060381, 88903008, 228293174, 394357308, 362355866, 900088886, 638573794, 779598451, 904922263, 451026166, 549459329, 212643744, 563246709, 391796933, 174243175, 189725986, 238337196, 60051478, 782959006, 982673239, 237607992, 685987666, 694447544, 195840153, 519748540, 446086975, 523485236, 185780714, 716004996, 214280883, 140643728, 555470704, 516522055, 116665689, 899547947, 490696549, 683197147, 686671136, 988747143, 744912554, 619072836, 345158054, 224284246, 637879131, 78947725, 342273666, 237716550, 915360466, 711578771, 423071394, 228124918, 271834959, 480779410, 254894593, 859192972, 990202578, 258044399, 151532640, 644862529, 48049425, 448119239, 130306338, 850105179, 401639970, 606863861, 183881380, 837401090, 513536652, 714177614, 946271680, 243293343, 403377310, 688653593, 15447678, 754734307, 631353768, 202296846, 159906516, 912696536, 737140518, 467380526, 896686075, 309895051, 356369955, 461415686, 706245266, 10064183, 183054210, 455971702, 737368289, 956771035, 564163693, 365118309, 226637659, 304857172, 440299843, 717116122, 485961418, 615704083, 476049473, 354119987, 329471814, 620060202, 251964959, 45357250, 175414082, 671119137, 48735782, 122378970, 717506435, 18459328, 949577729, 771970076, 635808197, 608040366, 165916428, 258536202, 902229110, 617090616, 548564593, 613394864, 753777984, 577888302, 416452176, 881599549, 524547188, 599140122, 522765386, 657552586, 256787840, 287613719, 776067801, 597965522, 458655497, 764387515, 350167935, 494713961, 513386012, 576480762, 864589772, 86987059, 495636228, 512647986, 721997962, 982831380, 162376799, 204281975, 462134806, 189646394, 425968575, 209834628, 494248765, 664281698, 947663843, 540352769, 25662122, 986679150, 207298711, 477043799, 24708053, 528335066, 189351697, 717500453, 42764755, 316734785, 823726196, 293357001, 547414377, 258966410, 602945692, 561521296, 351253952, 752369730, 174204566, 871148004, 302242737, 554611874, 540181425, 349941261, 414343943, 921115587, 959388563, 227019335, 708812719, 793380997, 342547759, 324322556, 458370547, 356254978, 809319893, 159690374, 848340820, 971304725, 180230004, 103061704, 207441144, 443272953, 45593686, 541647240, 612817107, 849140508, 109375794, 906749744, 159084460, 541378020, 692284266, 908221578, 720697998, 363923522, 819281897, 701846632, 479994712, 196613531, 29272489, 792937812, 859009553, 202148261, 385627435, 115321267, 612859231, 132778909, 173511339, 782369566, 322583903, 324703286, 31244274, 433755056, 109559692, 871157455, 350443931, 592104988, 197184362, 141678010, 649163959, 746537855, 954594407, 850681817, 703404350, 467293824, 684978431, 565588709, 378843675, 825260479, 749777538, 850502015, 387852091, 412307507, 307565279, 914127155, 864079609, 845970807, 414173935, 638273833, 664477235, 173471099, 480759791, 839694748, 190898355, 956270620, 957911348, 43002811, 628936576, 966234409, 667971950, 236586166, 954211897, 223051884, 21058295, 656573222, 631532535, 809706350, 984734695, 314281677, 311454037, 640732448, 434907794, 175084834, 434807109, 973816812, 488481268, 844735329, 917344075, 314288693, 459259162, 992521062, 667512257, 603748166, 679935673, 833938466, 933875943, 522922384, 981191471, 457854178, 112860028, 484939649, 611363777, 627371454, 844300972, 962501388, 738504183, 631041465, 29224765, 334078303, 211237785, 626057542, 900175080, 728504100, 450509755, 575177363, 905713570, 416609984, 874776027, 334255451, 683287462, 999293262, 474888472, 317020697, 180417613, 591538360, 879151833, 605566485, 569294094, 970567518, 896200922, 943088633, 145735679, 884701203, 949403596, 749113557, 78958680, 850679027, 665376978, 686499745, 426302291, 842343474, 708066168, 962548572, 349652428, 833757979, 492365420, 136639914, 76093131, 591710464, 208764552, 166233017, 498121245, 545840935, 26721664, 736011124, 880639351, 137410283, 42609708, 235572009, 981737748, 718913567, 909319027, 906112184, 298059463, 274736280, 217450848, 351267027, 149682364, 249066734, 11785215, 333890217, 774940233, 302540697, 519852435, 802535369, 620684620, 306323295, 752310997, 848793393, 883503040, 569433124, 254795373, 855478464, 660158704, 87911700, 944741410, 351053939, 2634663, 134077016, 736459220, 4882454, 969435081, 120150411, 922584286, 828772112, 106810765, 371205161, 17024731, 960279329, 389323593, 23991206, 744762405, 684217429, 479374977, 963728237, 3246420, 688035746, 381629444, 752436308, 274567573, 440219140, 702541058, 919238277, 563955926, 467150839, 5249506, 399086000, 833151662, 847391187, 655983283, 337920422, 866913758, 675206635, 549602585, 963783662, 324756002, 393087771, 731515248, 787956453, 550936813, 398161393, 631665856, 442637251, 454846959, 348994181, 88011024, 513458067, 60476466, 9760396, 403700900, 990173371, 519613195, 945797344, 114696834, 327457551, 905694736, 143025346, 289024806, 451579463, 325709522, 18701196, 326143996, 49850509, 619195074, 414881030, 850660769, 880149960, 651809429, 592293509, 810577782, 929598726, 835669318, 731671946, 529667681, 285562083, 293565850, 686472980, 274474950, 282703792, 889076915, 56602629, 546147347, 255724802, 873696194, 831784350, 110556728, 279941051, 667003092, 302778600, 803516696, 772054724, 165410893, 531446229, 958833885, 703493734, 68812272, 481542542, 722167619, 172528691, 173636402, 356397518, 390931659, 311533827, 53449710, 959934024, 259493848, 215350798, 907381983, 791418522, 896453666, 530274270, 443147787, 468552325, 410897594, 491169384, 314015783, 406644587, 772818684, 721371094, 596483817, 922913559, 78344520, 173781169, 485391881, 326797438, 209197264, 227032260, 183290649, 293208856, 909531571, 778733890, 346053132, 674154326, 75833611, 738595509, 449942130, 545136258, 334305223, 589959631, 51605154, 128106265, 85269691, 347284647, 656835568, 934798619, 602272125, 976691718, 647351010, 456965253, 143605060, 148066754, 588283108, 104912143, 240217288, 49898584, 251930392, 868617755, 690598708, 880742077, 200550782, 935358746, 104053488, 348096605, 394187502, 726999264, 278275958, 153885020, 653433530, 364854920, 922674021, 65882280, 762280792, 84294078, 29666249, 250921311, 659332228, 420236707, 614100318, 959310571, 676769211, 355052615, 567244231, 840761673, 557858783, 627343983, 461946676, 22779421, 756641425, 641419708]
MMI = [0, 1, 500000004, 333333336, 250000002, 400000003, 166666668, 142857144, 125000001, 111111112, 700000005, 818181824, 83333334, 153846155, 71428572, 466666670, 562500004, 352941179, 55555556, 157894738, 850000006, 47619048, 409090912, 739130440, 41666667, 280000002, 576923081, 370370373, 35714286, 758620695, 233333335, 129032259, 281250002, 939393946, 676470593, 628571433, 27777778, 621621626, 78947369, 717948723, 425000003, 658536590, 23809524, 395348840, 204545456, 822222228, 369565220, 404255322, 520833337, 448979595, 140000001, 784313731, 788461544, 56603774, 685185190, 763636369, 17857143, 385964915, 879310351, 50847458, 616666671, 688524595, 564516133, 15873016, 140625001, 30769231, 469696973, 686567169, 838235300, 579710149, 814285720, 98591550, 13888889, 410958907, 310810813, 93333334, 539473688, 831168837, 858974365, 202531647, 712500005, 123456791, 329268295, 84337350, 11904762, 670588240, 197674420, 252873565, 102272728, 415730340, 411111114, 164835166, 184782610, 43010753, 202127661, 231578949, 760416672, 268041239, 724489801, 646464651, 570000004, 940594066, 892156869, 572815538, 394230772, 209523811, 28301887, 224299067, 342592595, 9174312, 881818188, 873873880, 508928575, 893805316, 692982461, 147826088, 939655179, 239316241, 25423729, 478991600, 808333339, 438016532, 844262301, 886178868, 782258070, 856000006, 7936508, 480314964, 570312504, 798449618, 515384619, 190839696, 734848490, 165413535, 843283588, 274074076, 419117650, 58394161, 789855078, 604316551, 407142860, 134751774, 49295775, 832167838, 506944448, 151724139, 705479457, 149659865, 655405410, 530201346, 46666667, 483443712, 269736844, 594771246, 915584422, 625806456, 929487186, 343949047, 601265827, 685534596, 856250006, 962732926, 561728399, 116564418, 664634151, 587878792, 42168675, 5988024, 5952381, 242603552, 335294120, 795321643, 98837210, 791907520, 626436786, 325714288, 51136364, 683615824, 207865170, 435754193, 205555557, 933701664, 82417583, 562841534, 92391305, 524324328, 521505380, 577540111, 601063834, 338624341, 615789478, 439790579, 380208336, 694300523, 634020623, 343589746, 862244904, 969543154, 823232329, 507537692, 285000002, 228855723, 470297033, 108374385, 946078438, 131707318, 286407769, 526570052, 197115386, 832535891, 604761909, 90047394, 514150947, 32863850, 612149537, 79069768, 671296301, 875576043, 4587156, 470319638, 440909094, 950226251, 436936940, 125560539, 754464291, 364444447, 446902658, 35242291, 846491234, 711790398, 73913044, 277056279, 969827593, 90128756, 619658124, 880851070, 512711868, 67510549, 239495800, 280334730, 904166673, 406639007, 219008266, 707818935, 922131154, 89795919, 443089434, 165991904, 391129035, 28112450, 428000003, 912350604, 3968254, 339920951, 240157482, 556862749, 285156252, 70038911, 399224809, 517374521, 757692313, 417624524, 95419848, 836501907, 367424245, 611320759, 582706771, 138576780, 421641794, 743494429, 137037038, 450184505, 209558825, 388278391, 529197084, 752727278, 394927539, 252707583, 802158279, 681003589, 203571430, 718861215, 67375887, 650176683, 524647891, 77192983, 416083919, 808362375, 253472224, 961937723, 575862073, 756013751, 852739732, 522184304, 574829936, 210169493, 327702705, 215488217, 265100673, 441471575, 523333337, 770764125, 241721856, 646864691, 134868422, 137704919, 297385623, 749185673, 457792211, 857605184, 312903228, 787781356, 464743593, 492012783, 671974527, 403174606, 800632917, 652996850, 342767298, 614420067, 428125003, 741433027, 481366463, 597523224, 780864203, 406153849, 58282209, 3058104, 832317079, 343465048, 293939396, 631419944, 521084341, 624624629, 2994012, 737313438, 502976194, 41543027, 121301776, 631268441, 167647060, 284457480, 897660825, 206997086, 49418605, 715942034, 395953760, 985590785, 313218393, 521489975, 162857144, 413105416, 25568182, 175637395, 341807912, 19718310, 103932585, 826330538, 717877100, 713091927, 602777782, 113573408, 466850832, 812672182, 541208795, 882191787, 281420767, 376021801, 546195656, 295392956, 262162164, 436657685, 260752690, 16085791, 788770059, 618666671, 300531917, 212201593, 669312174, 195250661, 307894739, 160104988, 719895293, 172323761, 190104168, 966233773, 847150265, 932816544, 817010315, 951156819, 171794873, 102301791, 431122452, 63613232, 484771577, 840506335, 911616168, 760705295, 253768846, 55137845, 142500001, 855361602, 614427865, 779156333, 735148520, 424691361, 554187196, 238329240, 473039219, 188264060, 65853659, 352798056, 643203888, 578692498, 263285026, 16867470, 98557693, 534772186, 916267949, 844868741, 802380958, 966745850, 45023697, 44917258, 757075477, 134117648, 16431925, 526932088, 806074772, 610722615, 39534884, 761020887, 835648154, 614318711, 937788025, 50574713, 2293578, 354691078, 235159819, 642369025, 220454547, 716553293, 975113129, 88036118, 218468470, 83146068, 562780273, 176733782, 877232149, 285077953, 682222227, 605321512, 223451329, 161147904, 517621149, 432967036, 423245617, 172866522, 355895199, 198257082, 36956522, 321041217, 638528143, 820734347, 984913800, 208602152, 45064378, 775160605, 309829062, 240938168, 440425535, 447983018, 256355934, 763213536, 533755278, 646315794, 119747900, 228511532, 140167365, 206680586, 952083340, 355509358, 703319507, 654244311, 109504133, 653608252, 853909471, 607802879, 461065577, 38854806, 544897963, 641547866, 221544717, 632860045, 82995952, 529292933, 695564521, 156941651, 14056225, 266533068, 714000005, 1996008, 456175302, 282306165, 1984127, 588118816, 669960479, 747534522, 120078741, 491159139, 778431378, 344422703, 142578126, 598440550, 535019459, 314563109, 699612408, 400386850, 758687264, 597302509, 878846160, 191938581, 208812262, 921606125, 47709924, 441904765, 918250957, 301707782, 683712126, 510396979, 805660383, 561205277, 791353389, 589118203, 69288390, 844859819, 210820897, 811918069, 871747218, 404452693, 68518519, 60998152, 725092256, 311233888, 604779416, 801834868, 694139199, 541133459, 264598542, 854280516, 376363639, 39927405, 697463773, 457504524, 626353795, 174774776, 901079143, 457809698, 840501798, 491949914, 101785715, 525846706, 859430611, 433392543, 533687947, 578761066, 825088345, 446208116, 762323949, 732864680, 538596495, 334500878, 708041963, 813263531, 904181191, 229565219, 126736112, 771230508, 980968865, 898100179, 787931040, 869191056, 878006879, 732418530, 426369866, 447863251, 261092152, 724020448, 287414968, 585738544, 605084750, 656514387, 663851356, 160202362, 607744112, 95798320, 632550340, 835845902, 720735791, 410684477, 761666672, 296173047, 885382066, 76285241, 120860928, 887603312, 823432349, 729818786, 67434211, 36124795, 568852463, 492635028, 648692815, 696574230, 874592840, 377235775, 728896109, 716369535, 428802592, 953150249, 156451614, 842190022, 393890678, 630818624, 732371800, 571200004, 746006395, 944178635, 835987267, 36565978, 201587303, 438985740, 900316462, 30015798, 326498425, 696062997, 171383649, 880690744, 807210037, 677621288, 714062505, 720748835, 870716517, 43545879, 740683235, 359689925, 298761612, 119010820, 890432105, 640986137, 703076928, 291858681, 529141108, 29096478, 1529052, 438167942, 916158543, 823439884, 171732524, 698027319, 146969698, 216338882, 315709972, 983408755, 760542174, 33082707, 812312318, 163418292, 1497006, 41853513, 368656719, 62593145, 251488097, 493313525, 520771517, 454814818, 60650888, 320531760, 815634224, 609720181, 83823530, 345080766, 142228740, 530014645, 948830416, 411678835, 103498543, 237263466, 524709306, 927431066, 357971017, 444283650, 197976880, 92352093, 992795396, 520863313, 656609200, 862266864, 760744991, 696709590, 81428572, 489301002, 206552708, 85348507, 12784091, 626950359, 587818701, 991513444, 170903956, 385049368, 9859155, 355836852, 551966296, 701262277, 413165269, 366433569, 358938550, 93444910, 856545967, 318497916, 301388891, 224687935, 56786704, 802213007, 233425416, 630344832, 406336091, 696011009, 770604401, 235939645, 941095897, 729138172, 640710387, 66848568, 688010904, 29931973, 273097828, 698778838, 147696478, 538565633, 131081082, 721997306, 718328846, 590847918, 130376345, 506040272, 508042899, 676037488, 894385033, 889185587, 809333339, 215712385, 650265962, 304116868, 606100800, 896688748, 334656087, 952443864, 597625334, 779973655, 653947373, 582128782, 80052494, 1310616, 859947650, 518954252, 586161884, 850065195, 95052084, 855656703, 983116890, 690012975, 923575136, 648124196, 466408272, 525161294, 908505161, 839124845, 975578413, 613607193, 585897440, 645326509, 551150899, 805874846, 215561226, 868789815, 31806616, 419313853, 742385792, 278833969, 920253171, 841972193, 455808084, 822194205, 880352651, 537106922, 126884423, 877038902, 527568926, 964956202, 571250004, 46192260, 427680801, 764632633, 807213936, 592546588, 889578170, 581164812, 367574260, 102595798, 712345684, 755856972, 277093598, 816728173, 119164620, 223312885, 736519613, 73439413, 94132030, 462759466, 532926833, 618757617, 176399028, 52247874, 321601944, 917575764, 289346249, 617896014, 131642513, 712907122, 8433735, 84235861, 549278850, 496998803, 267386093, 601197609, 958133978, 560334532, 922434374, 696066751, 401190479, 853745547, 483372925, 239620405, 522511852, 848520716, 22458629, 348288078, 878537742, 216725561, 67058824, 722679206, 508215966, 690504108, 263466044, 359064330, 403037386, 792298722, 805361311, 67520373, 19767442, 269454125, 880510447, 718424107, 417824077, 158381504, 807159359, 987312579, 968894016, 200230151, 525287360, 360505169, 1146789, 918671255, 177345539, 265142859, 617579913, 891676175, 821184516, 840728106, 610227277, 759364364, 858276650, 612684036, 987556568, 736723169, 44018059, 559188279, 109234235, 497187855, 41573034, 738496077, 781390140, 705487127, 88366891, 287150840, 938616078, 813823863, 642538980, 314794218, 841111117, 591564932, 302660756, 256921375, 611725668, 786740337, 80573952, 324145537, 758810578, 882288235, 216483518, 963776077, 711622812, 371303398, 86433261, 712568311, 677947603, 741548533, 99128541, 41349293, 18478261, 916395229, 660520612, 776814740, 819264075, 304864867, 910367177, 952535066, 492456900, 252960174, 104301076, 23630505, 22532189, 595927121, 887580306, 515508025, 154914531, 16008538, 120469084, 164004261, 720212771, 568544106, 223991509, 115588548, 128177967, 467724871, 381606768, 551214365, 266877639, 262381456, 323157897, 884332288, 59873950, 383001052, 114255766, 687958120, 570083686, 204806689, 103340293, 8342023, 476041670, 746097820, 177754679, 580477678, 851659757, 338860106, 827122159, 260599795, 554752070, 199174408, 326804126, 669412981, 926954739, 943473799, 803901443, 468717952, 730532792, 584442174, 19427403, 492339125, 772448985, 1019368, 320773933, 399796544, 610772362, 793908635, 816430026, 447821685, 41497976, 17189080, 764646470, 172552978, 847782264, 877139986, 578470829, 901507544, 507028116, 911735212, 133266534, 874874881, 857000006]
n = len(nums)
lis = [0] * n
def count(subnums):
nonlocal lis
if subnums:
low = [num for num in subnums if num < subnums[0]]
high = [num for num in subnums if num > subnums[0]]
lis[subnums[0]-1] = len(subnums)
count(low)
count(high)
count(nums)
M = 10 ** 9 + 7
denum = 1
for k in range(1,n+1):
denum = (denum * MMI[lis[k-1]]) % M
return (FACT[n] * denum) % M - 1 | number-of-ways-to-reorder-array-to-get-same-bst | A cheating way | Fredrick_LI | 0 | 4 | number of ways to reorder array to get same bst | 1,569 | 0.481 | Hard | 23,134 |
https://leetcode.com/problems/matrix-diagonal-sum/discuss/1369404/PYTHON-Best-solution-with-explanation.-SC-%3A-O(1)-TC-%3A-O(n) | class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
"""
The primary diagonal is formed by the elements A00, A11, A22, A33.
Condition for Primary Diagonal:
The row-column condition is row = column.
The secondary diagonal is formed by the elements A03, A12, A21, A30.
Condition for Secondary Diagonal:
The row-column condition is row = numberOfRows - column -1.
"""
s = 0
l , mid = len(mat), len(mat)//2
for i in range(l):
s += mat[i][i] # primary diagonal
s += mat[len(mat)-i-1][i] # secondary diagonal
# If the mat is odd, then diagonal will coincide, so subtract the middle element
if l%2 != 0:
s -= mat[mid][mid]
return s | matrix-diagonal-sum | [PYTHON] Best solution with explanation. SC : O(1) TC : O(n) | er1shivam | 5 | 233 | matrix diagonal sum | 1,572 | 0.798 | Easy | 23,135 |
https://leetcode.com/problems/matrix-diagonal-sum/discuss/2074738/Python-Easy-To-Understand-Solution | class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
total = 0
for i, x in enumerate(mat):
if i == len(mat)-i-1:
total += x[i]
else:
total += x[i] + x[len(mat)-i-1]
return total | matrix-diagonal-sum | Python Easy To Understand Solution | Shivam_Raj_Sharma | 4 | 182 | matrix diagonal sum | 1,572 | 0.798 | Easy | 23,136 |
https://leetcode.com/problems/matrix-diagonal-sum/discuss/1775861/Python3-solution-or-O(n)-or-Single-For-loop-or-86.30-lesser-memory | class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
x = 0
y = len(mat)-1
dsum = 0
for _ in range(len(mat)):
if x == y:
dsum += mat[x][x]
x += 1
y -= 1
continue
dsum += (mat[x][x])
dsum += (mat[x][y])
x += 1
y -= 1
return dsum | matrix-diagonal-sum | Python3 solution | O(n) | Single For loop | 86.30% lesser memory | Coding_Tan3 | 3 | 146 | matrix diagonal sum | 1,572 | 0.798 | Easy | 23,137 |
https://leetcode.com/problems/matrix-diagonal-sum/discuss/2573377/SIMPLE-PYTHON3-SOLUTION-lineartime | class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
ans = []
count = 0
rightcount = len(mat[0]) - 1
for i in range(len(mat)):
if rightcount == count: ans.append(mat[i][count])
if i == count and rightcount != count:
ans.append(mat[i][count])
ans.append(mat[i][rightcount])
count += 1
rightcount -= 1
return sum(ans) | matrix-diagonal-sum | β
β SIMPLE PYTHON3 SOLUTION β
β lineartime | rajukommula | 1 | 108 | matrix diagonal sum | 1,572 | 0.798 | Easy | 23,138 |
https://leetcode.com/problems/matrix-diagonal-sum/discuss/2238950/Python3-one-loop-solution | class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
n = len(mat)
result,primary,i,secondary = 0,0,0,n-1
while i < n:
x, y = mat[i][primary], mat[i][secondary]
if primary!=secondary:
result+= x + y
else:
result+=x
primary,secondary,i = primary+1, secondary-1, i+1
return result | matrix-diagonal-sum | π Python3 one loop solution | Dark_wolf_jss | 1 | 34 | matrix diagonal sum | 1,572 | 0.798 | Easy | 23,139 |
https://leetcode.com/problems/matrix-diagonal-sum/discuss/1748070/Easy-Python | class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
r = len(mat)
s = 0
for i in range(r):
for j in range(r):
if i == j or i+j == r-1:
s += mat[i][j]
return s | matrix-diagonal-sum | Easy Python | MengyingLin | 1 | 53 | matrix diagonal sum | 1,572 | 0.798 | Easy | 23,140 |
https://leetcode.com/problems/matrix-diagonal-sum/discuss/1437485/Python-Simple-solution | class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
s = 0
for x in range(len(mat)):
s += mat[x][x] + mat[x][-x-1]
if len(mat) % 2 != 0:
s -= mat[len(mat)//2][len(mat)//2]
return s | matrix-diagonal-sum | [Python] Simple solution | sushil021996 | 1 | 86 | matrix diagonal sum | 1,572 | 0.798 | Easy | 23,141 |
https://leetcode.com/problems/matrix-diagonal-sum/discuss/1394870/Python3-Faster-than-97-of-the-Solutions | class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
s = 0
l = len(mat)
for i in range(l):
s = s + mat[i][i]
for i in range(l):
s = s + mat[i][l-i-1]
if l%2 != 0:
s = s - mat[l//2][l//2]
return s | matrix-diagonal-sum | Python3 - Faster than 97% of the Solutions | harshitgupta323 | 1 | 36 | matrix diagonal sum | 1,572 | 0.798 | Easy | 23,142 |
https://leetcode.com/problems/matrix-diagonal-sum/discuss/1136020/Python-faster-than-94 | class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
d1, d2 = 0, 0
for i in range(len(mat)):
# top left to bottom right
d1 += mat[i][i]
# bottom left to top right, skips if it reaches the mid
d2 += mat[len(mat)-i-1][i] if len(mat)-i-1 != i else 0
# somehow, leetcode is faster if result is assigned to a var rather than returning as is. Can anyone explain?
t = d1 + d2
return t | matrix-diagonal-sum | Python faster than 94% | 111110100 | 1 | 137 | matrix diagonal sum | 1,572 | 0.798 | Easy | 23,143 |
https://leetcode.com/problems/matrix-diagonal-sum/discuss/830529/Python3-straightforward-5-line | class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
ans = 0
for i in range(len(mat)):
ans += mat[i][i]
if 2*i+1 != len(mat): ans += mat[i][~i]
return ans | matrix-diagonal-sum | [Python3] straightforward 5-line | ye15 | 1 | 49 | matrix diagonal sum | 1,572 | 0.798 | Easy | 23,144 |
https://leetcode.com/problems/matrix-diagonal-sum/discuss/2839517/one-liner-easy-to-understand-python-solution | class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
return sum(map(lambda idx: mat[idx][idx]+mat[idx][len(mat)-1-idx] if idx!=len(mat)-1-idx else mat[idx][idx],range(len(mat)))) | matrix-diagonal-sum | one-liner, easy to understand python solution | goezsoy | 0 | 1 | matrix diagonal sum | 1,572 | 0.798 | Easy | 23,145 |
https://leetcode.com/problems/matrix-diagonal-sum/discuss/2833459/Simple-Python-Solution | class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
length = len(mat)
summ = 0
for i in range(length):
for j in range(length):
if i== j:
summ += mat[i][j]
elif i+j == length-1:
summ += mat[i][j]
return summ | matrix-diagonal-sum | Simple Python Solution | danishs | 0 | 1 | matrix diagonal sum | 1,572 | 0.798 | Easy | 23,146 |
https://leetcode.com/problems/matrix-diagonal-sum/discuss/2832914/Python3-one-line-solution-beats-94-with-explanation | class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
return sum([mat[i][i] for i in range(len(mat))] + [mat[i][len(mat)-i-1] for i in range(len(mat)) if i/1 != (len(mat)-1) / 2]) | matrix-diagonal-sum | Python3 one-line solution beats 94% - with explanation | sipi09 | 0 | 2 | matrix diagonal sum | 1,572 | 0.798 | Easy | 23,147 |
https://leetcode.com/problems/matrix-diagonal-sum/discuss/2832914/Python3-one-line-solution-beats-94-with-explanation | class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
ans = 0
for i in range(len(mat)):
ans += mat[i][i]
if i/1 != (len(mat)-1) / 2:
ans += mat[i][len(mat)-i-1]
return ans | matrix-diagonal-sum | Python3 one-line solution beats 94% - with explanation | sipi09 | 0 | 2 | matrix diagonal sum | 1,572 | 0.798 | Easy | 23,148 |
https://leetcode.com/problems/matrix-diagonal-sum/discuss/2817567/Easy-Beginner-Friendly-Solution-Python | class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
c = 0
for i in range(len(mat)):
temp = mat[i]
for j in range(len(temp)):
if(i == j or i+j == len(mat)-1):
c += temp[j]
return c | matrix-diagonal-sum | [Easy Beginner Friendly Solution Python] | imash_9 | 0 | 2 | matrix diagonal sum | 1,572 | 0.798 | Easy | 23,149 |
https://leetcode.com/problems/matrix-diagonal-sum/discuss/2814908/Matrix-Diagonal-Sum-or-Python-3.x-or-O(n) | class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
side = len(mat)
if side % 2 == 0:
correction = 0
else:
correction = mat[side // 2][side // 2]
sum_diags = sum(mat[idx][idx] + mat[idx][side - idx - 1] for idx in range(side)) - correction
return sum_diags | matrix-diagonal-sum | Matrix Diagonal Sum | Python 3.x | O(n) | SnLn | 0 | 3 | matrix diagonal sum | 1,572 | 0.798 | Easy | 23,150 |
https://leetcode.com/problems/matrix-diagonal-sum/discuss/2814883/Matrix-Diagonal-Sum-or-Python-3.x | class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
side = len(mat)
if side % 2 == 0:
correction = 0
else:
correction = mat[side // 2][side // 2]
prime_diag = sum(mat[idx][idx] for idx in range(side))
secon_diag = sum(mat[idx][side - idx - 1] for idx in range(side))
sum_diags = prime_diag + secon_diag - correction
return sum_diags | matrix-diagonal-sum | Matrix Diagonal Sum | Python 3.x | SnLn | 0 | 2 | matrix diagonal sum | 1,572 | 0.798 | Easy | 23,151 |
https://leetcode.com/problems/matrix-diagonal-sum/discuss/2809547/MATRIX-DIAGONAL-SUM-or-PYTHON | class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
j = len(mat) - 1
count = 0
for i in range(len(mat)):
count += mat[i][i] + mat[i][j - i]
if len(mat) % 2 == 0:
return count
return count - mat[int(j/2)][int(j/2)] | matrix-diagonal-sum | MATRIX DIAGONAL SUM | PYTHON | jashii96 | 0 | 2 | matrix diagonal sum | 1,572 | 0.798 | Easy | 23,152 |
https://leetcode.com/problems/matrix-diagonal-sum/discuss/2772678/Python-Fastest-Solution-Beats-93-users-with-full-explanation-in-comments | class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
n=len(mat)
sum=0
mid=n//2
#loop for iteration in matrix
for i in range(n):
#for primary diagonal we have to add the values of mat[i][i] like [0][0] ,[1][1] position
sum+=mat[i][i]
#for secondary diagonal we have to add the values of mat[n-1-i][i] like [0][2],[1][1],[2.1]
sum+=mat[n-1-i][i]
#for odd length case we have to remove the mid value because in odd length case the [mid][mid] value is same in primary diagonal and secondary diagonal
if n%2==1:
sum-=mat[mid][mid]
return sum | matrix-diagonal-sum | Python Fastest Solution Beats 93 % users with full explanation in comments | mritunjayyy | 0 | 1 | matrix diagonal sum | 1,572 | 0.798 | Easy | 23,153 |
https://leetcode.com/problems/matrix-diagonal-sum/discuss/2746262/Use-minus-index-to-find-inverse-line | class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
"""TC: O(n), SC: O(n)"""
diag_sum = 0
for i in range(len(mat)):
diag_sum += mat[i][i]
diag_sum += mat[-i-1][i]
if len(mat) % 2 == 1:
middle_value = mat[int(len(mat)/2)][int(len(mat)/2)]
diag_sum -= middle_value
return diag_sum | matrix-diagonal-sum | Use minus index to find inverse line | woora3 | 0 | 2 | matrix diagonal sum | 1,572 | 0.798 | Easy | 23,154 |
https://leetcode.com/problems/matrix-diagonal-sum/discuss/2738477/python-easy-solution-93-faster | class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
ans = 0
n = len(mat)
for i in range(n):
k = mat[i] # row data list
ans += k[i] + k[-(i+1)] # sum diagonal element
if n > 1:
if n&1:
ans -= mat[n//2][n//2] # substract common diagonal element for total sum
else:
ans = mat[0][0] # if input len == 1
return ans | matrix-diagonal-sum | python easy solution 93% faster | arifkhan1990 | 0 | 4 | matrix diagonal sum | 1,572 | 0.798 | Easy | 23,155 |
https://leetcode.com/problems/matrix-diagonal-sum/discuss/2682272/Python-or-Simple-O(n)-solution | class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
ans = 0
for i in range(len(mat)):
ans += mat[i][i]
for i in range(len(mat) - 1, -1, -1):
if len(mat) and len(mat) - i - 1 == i:
continue
ans += mat[len(mat) - i - 1][i]
return ans | matrix-diagonal-sum | Python | Simple O(n) solution | LordVader1 | 0 | 20 | matrix diagonal sum | 1,572 | 0.798 | Easy | 23,156 |
https://leetcode.com/problems/matrix-diagonal-sum/discuss/2668317/Pythonor-O(N)-Time-Complexityor-n2-time-loop-execution | class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
res = 0
n = len(mat)
for i in range(0,n//2 if n%2==0 else n//2 + 1):
if i != n-i-1:
res = res + mat[i][i] + mat[i][n-i-1] + mat[n-i-1][i] + mat[n-i-1][n-i-1]
else:
res += mat[i][i]
return res | matrix-diagonal-sum | Python| O(N) Time Complexity| n//2 time loop execution | tanaydwivedi095 | 0 | 3 | matrix diagonal sum | 1,572 | 0.798 | Easy | 23,157 |
https://leetcode.com/problems/matrix-diagonal-sum/discuss/2625461/Simple-approach-or-Python-or-begineers-friendly | class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
row=len(mat)
dia_left=0
for i in range(0,row):
dia_left+=mat[i][i]
left=0
right=row-1
dia_right=0
for i in range(0,row):
dia_right+=mat[left][right]
left+=1
right-=1
if row==1:
return mat[0][0]
elif row%2!=0:
return ((dia_left+dia_right)-mat[row//2][row//2])
return dia_left+dia_right | matrix-diagonal-sum | Simple approach | Python | begineers friendly | Mom94 | 0 | 6 | matrix diagonal sum | 1,572 | 0.798 | Easy | 23,158 |
https://leetcode.com/problems/matrix-diagonal-sum/discuss/2556639/Easy-Python3-Solution | class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
summ=0
for i in range(len(mat)):
summ+=mat[i][i]
for i in range(len(mat)):
if len(mat[i])-1-i!=i:
summ+=mat[i][len(mat[i])-1-i]
return summ | matrix-diagonal-sum | Easy Python3 Solution | pranjalmishra334 | 0 | 31 | matrix diagonal sum | 1,572 | 0.798 | Easy | 23,159 |
https://leetcode.com/problems/matrix-diagonal-sum/discuss/2549638/Python-matrix-O(n) | class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
s = 0
for i in range(len(mat)):
s += mat[i][i]
if i != len(mat) - i - 1:
s += mat[i][len(mat) - i - 1]
return s | matrix-diagonal-sum | Python matrix O(n) | nika_macharadze | 0 | 24 | matrix diagonal sum | 1,572 | 0.798 | Easy | 23,160 |
https://leetcode.com/problems/matrix-diagonal-sum/discuss/2521506/Python-or-Short-and-easy-or-Explained | class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
n = len(mat)
# add both primary and secondary diagonals
s = sum([mat[i][i] + mat[i][n-1-i] for i in range(n)])
# if matrix size is odd, the middle element will be repeated --> subtract it
if n % 2: s -= mat[n//2][n//2]
return s | matrix-diagonal-sum | Python | Short and easy | Explained | anon82214 | 0 | 36 | matrix diagonal sum | 1,572 | 0.798 | Easy | 23,161 |
https://leetcode.com/problems/matrix-diagonal-sum/discuss/2463976/Python-using-builtin-sum | class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
dim = len(mat[0])
center = dim // 2
s = sum(mat[idx][idx] + mat[dim - idx - 1][idx] for idx in range(dim))
return s - mat[center][center] if dim & 1 else s | matrix-diagonal-sum | Python using builtin sum | Potentis | 0 | 12 | matrix diagonal sum | 1,572 | 0.798 | Easy | 23,162 |
https://leetcode.com/problems/matrix-diagonal-sum/discuss/2448198/Python-Simple-Solution | class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
ans = 0
for i in range(len(mat)):
ans += (mat[i][i] + mat[i][-i-1])
if len(mat)%2 != 0:
ans -= mat[len(mat)//2][len(mat)//2]
return ans | matrix-diagonal-sum | Python Simple Solution | xinhuangtien | 0 | 32 | matrix diagonal sum | 1,572 | 0.798 | Easy | 23,163 |
https://leetcode.com/problems/matrix-diagonal-sum/discuss/2431950/Python-indexing-but-not-memory-efficient | class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
n = len(mat)
total = sum([mat[i][i] + mat[i][n - i - 1] for i in range(n)])
total -= mat[n//2][n//2] if n % 2 else 0
return total | matrix-diagonal-sum | Python indexing but not memory efficient | russellizadi | 0 | 20 | matrix diagonal sum | 1,572 | 0.798 | Easy | 23,164 |
https://leetcode.com/problems/matrix-diagonal-sum/discuss/2407071/Python-solution-91.11-faster | class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
total_sum = 0
for i in range(len(mat)):
total_sum += mat[i][i]
if len(mat) % 2 != 0 and i != len(mat) // 2:
total_sum += mat[i][-1 - i]
if len(mat) % 2 == 0:
total_sum += mat[i][-1 - i]
return total_sum | matrix-diagonal-sum | Python solution 91.11% faster | samanehghafouri | 0 | 15 | matrix diagonal sum | 1,572 | 0.798 | Easy | 23,165 |
https://leetcode.com/problems/matrix-diagonal-sum/discuss/2317608/Faster-than-99.41 | class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
size = len(mat)
res = sum([(mat[i][i] + mat[size-1-i][size-1-i] +
mat[i][size - 1 - i] + mat[size - 1 - i][i])
for i in range(size//2)])
if size % 2 == 1:
res += mat[size //2][size//2]
return res | matrix-diagonal-sum | Faster than 99.41% | trohin | 0 | 21 | matrix diagonal sum | 1,572 | 0.798 | Easy | 23,166 |
https://leetcode.com/problems/matrix-diagonal-sum/discuss/2315264/Fast-and-Easy-python-3-solution | class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
# There're at most two elements that can be counted in the sum per row which is mat[i][i] and mat[i][n - i - 1]
n = len(mat)
res = 0
for i in range(n):
res += mat[i][i]
if i != n - i -1:
res += mat[i][n - i - 1]
return res
# Runtime: 130 ms, faster than 77.89% of Python3 online submissions for Matrix Diagonal Sum.
``` | matrix-diagonal-sum | Fast and Easy python 3 solution | Ultraviolet0909 | 0 | 12 | matrix diagonal sum | 1,572 | 0.798 | Easy | 23,167 |
https://leetcode.com/problems/matrix-diagonal-sum/discuss/2136910/Easy-and-simple-Python3-solution | class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
ans = 0
j = 0
k = -1
for i in range(len(mat)):
if mat[i][j] == mat[i][k] and len(mat)%2 != 0 and i == (len(mat)-1)//2:
ans += mat[i][j]
j += 1
k -= 1
else:
ans += mat[i][j]
ans += mat[i][k]
j += 1
k -= 1
return ans | matrix-diagonal-sum | Easy and simple Python3 solution | rohansardar | 0 | 54 | matrix diagonal sum | 1,572 | 0.798 | Easy | 23,168 |
https://leetcode.com/problems/matrix-diagonal-sum/discuss/2058482/Python-Generator-Expression-greater-oneliner | class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
# return sum(row[i] + row[len(mat) - 1 - i] if i != len(mat) - 1 - i else row[i] for i, row in enumerate(mat))
return sum(
row[i] + row[len(mat) - 1 - i]
if i != len(mat) - 1 - i
else row[i]
for i, row in enumerate(mat)
) | matrix-diagonal-sum | Python Generator Expression > oneliner | kedeman | 0 | 55 | matrix diagonal sum | 1,572 | 0.798 | Easy | 23,169 |
https://leetcode.com/problems/matrix-diagonal-sum/discuss/2053462/Faster-than-94.68-or-Simple-Python-code | class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
n=len(mat)
x=[]
m=[]
for i in range(n):
x.append(mat[i][i])
x.append(mat[n-1-i][i])
if n%2!=0:
middle=n//2
x.remove(mat[middle][middle])
return sum(x)
else:
return sum(x) | matrix-diagonal-sum | Faster than 94.68% | Simple Python code | glimloop | 0 | 37 | matrix diagonal sum | 1,572 | 0.798 | Easy | 23,170 |
https://leetcode.com/problems/matrix-diagonal-sum/discuss/2018943/Python-Simple-O(n)-Solution | class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
sum = 0
matLen = len(mat)
for i, x in enumerate(mat):
if i == matLen-i-1:
sum += x[i]
else:
sum += x[i] + x[matLen-i-1]
return sum | matrix-diagonal-sum | Python Simple O(n) Solution | parksung | 0 | 47 | matrix diagonal sum | 1,572 | 0.798 | Easy | 23,171 |
https://leetcode.com/problems/matrix-diagonal-sum/discuss/2013945/Python-95-Memory-Solution! | class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
visited = []
output = 0
for i in range(len(mat)):
if (i, i) not in visited:
output += mat[i][i]
visited.append((i, i))
y = len(mat) - 1
for x in range(len(mat)):
if (x, y) not in visited:
output += mat[x][y]
visited.append((x, y))
y -= 1
return output | matrix-diagonal-sum | π₯ Python 95% Memory Solution! π₯ | PythonerAlex | 0 | 109 | matrix diagonal sum | 1,572 | 0.798 | Easy | 23,172 |
https://leetcode.com/problems/matrix-diagonal-sum/discuss/1996910/Python-Easiest-Soltuion!!-or-Simple-or-Optimized-or-One-loop | class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
n = t = len(mat)
total = 0
for i in range(n):
for j in range(n):
if i == j:
total += mat[i][j]
elif j == t - 1:
total += mat[i][j]
t -= 1
return total | matrix-diagonal-sum | [Python] Easiest Soltuion!! | Simple | Optimized | One loop | jamil117 | 0 | 54 | matrix diagonal sum | 1,572 | 0.798 | Easy | 23,173 |
https://leetcode.com/problems/matrix-diagonal-sum/discuss/1989577/python3-solution-with-2-pointers | class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
result = 0
d = len(mat)
l, r = 0, d - 1
for row in mat:
result += row[l] + row[r]
l += 1
r -= 1
if d % 2:
m = d//2
result -= mat[m][m]
return result
``` | matrix-diagonal-sum | python3 solution with 2 pointers | turael | 0 | 35 | matrix diagonal sum | 1,572 | 0.798 | Easy | 23,174 |
https://leetcode.com/problems/matrix-diagonal-sum/discuss/1985300/Python-or-Simple-Loop | class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
n = len(mat)
result = 0
for i in range(n):
result += mat[i][i] + mat[n-1-i][i]
if n % 2 == 1:
result -= mat[n//2][n//2]
return result | matrix-diagonal-sum | Python | Simple Loop | Mikey98 | 0 | 36 | matrix diagonal sum | 1,572 | 0.798 | Easy | 23,175 |
https://leetcode.com/problems/matrix-diagonal-sum/discuss/1979180/Python-Understandable-solution-O(n)-runtime | class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int
diagonalsSum = 0
for index, array in enumerate(mat):
if index != len(array) - index - 1:
diagonalsSum += array[index] + array[-1 - index]
else:
diagonalsSum += array[index]
return diagonalsSum | matrix-diagonal-sum | [Python] Understandable solution O(n) runtime | romanduenin | 0 | 35 | matrix diagonal sum | 1,572 | 0.798 | Easy | 23,176 |
https://leetcode.com/problems/matrix-diagonal-sum/discuss/1966687/Understandable-solution-Py | class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
prim = [(x,x) for x in range(len(mat))]
sec = [(x,y) for x,y in enumerate(range(len(mat)-1,-1,-1))]
ans = 0
for i,j in set(prim+sec):
ans += mat[j][i]
return ans | matrix-diagonal-sum | Understandable solution Py | StikS32 | 0 | 25 | matrix diagonal sum | 1,572 | 0.798 | Easy | 23,177 |
https://leetcode.com/problems/matrix-diagonal-sum/discuss/1956273/Easy-Python-Solution | class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
c = len(mat[0])-1
count_p = 0
count_s = 0
for i in range(len(mat)):
count_p += mat[i][i]
for j in range(len(mat)):
count_s += mat[i][c]
c -= 1
break
if len(mat) % 2 != 0:
mid = (len(mat)//2)
total = (count_p + count_s) - mat[mid][mid]
else:
total = count_p + count_s
return total | matrix-diagonal-sum | Easy Python Solution | itsmeparag14 | 0 | 40 | matrix diagonal sum | 1,572 | 0.798 | Easy | 23,178 |
https://leetcode.com/problems/matrix-diagonal-sum/discuss/1889370/Ez-oror-2-sols-oror-O(n)-and-O(n2) | class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
r, s = len(mat), 0
for i in range(r):
for j in range(r):
if i==j:
s+=mat[i][j]
break
for i in range(r):
for j in range(r-1, -1, -1):
if i==r-1-j:
s+=mat[i][j]
break
return s if r%2==0 else s-mat[r//2][r//2] | matrix-diagonal-sum | Ez || 2 sols || O(n) and O(n^2) | ashu_py22 | 0 | 25 | matrix diagonal sum | 1,572 | 0.798 | Easy | 23,179 |
https://leetcode.com/problems/matrix-diagonal-sum/discuss/1889370/Ez-oror-2-sols-oror-O(n)-and-O(n2) | class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
r, s = len(mat), 0
for i in range(r):
for j in range(r):
if i==j:
s+=mat[i][j]+mat[i][r-j-1]
break
if r%2==0:
return s
return s - mat[r//2][r//2] | matrix-diagonal-sum | Ez || 2 sols || O(n) and O(n^2) | ashu_py22 | 0 | 25 | matrix diagonal sum | 1,572 | 0.798 | Easy | 23,180 |
https://leetcode.com/problems/matrix-diagonal-sum/discuss/1889370/Ez-oror-2-sols-oror-O(n)-and-O(n2) | class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
r, s = len(mat), 0
for i in range(r):
s+=mat[i][i]+mat[i][r-i-1]
if r%2==0:
return s
return s - mat[r//2][r//2] | matrix-diagonal-sum | Ez || 2 sols || O(n) and O(n^2) | ashu_py22 | 0 | 25 | matrix diagonal sum | 1,572 | 0.798 | Easy | 23,181 |
https://leetcode.com/problems/matrix-diagonal-sum/discuss/1862065/Python-(Simple-Approach-and-Beginner-Friendly) | class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
n = len(mat)
mid = 0
odd = False
if n % 2 != 0:
odd = True
mid = n//2 + 1
count = 0
for r in range(0, len(mat)):
count+=mat[r][r]
j = 1
for r in range(0, len(mat)):
count+=mat[r][-j]
j+=1
return count-mat[mid-1][mid-1] if odd else count | matrix-diagonal-sum | Python (Simple Approach and Beginner-Friendly) | vishvavariya | 0 | 48 | matrix diagonal sum | 1,572 | 0.798 | Easy | 23,182 |
https://leetcode.com/problems/matrix-diagonal-sum/discuss/1854333/Python-easy-beginner's-solution | class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
sec_i = 0
sec_j = len(mat) - 1
s = 0
for i in range(len(mat)):
for j in range(len(mat)):
if i == j:
s = s + mat[i][j] + mat[sec_i][sec_j]
sec_i += 1
sec_j -= 1
if len(mat) % 2 != 0:
s -= mat[len(mat)//2][len(mat)//2]
return s | matrix-diagonal-sum | Python easy beginner's solution | alishak1999 | 0 | 37 | matrix diagonal sum | 1,572 | 0.798 | Easy | 23,183 |
https://leetcode.com/problems/matrix-diagonal-sum/discuss/1825042/2-Lines-Python-Solution-oror-70-Faster-oror-Memory-less-than-98 | class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
n=len(mat) ; sm=sum(mat[i][i]+mat[i][n-i-1] for i in range(n))
return sm-mat[n//2][n//2] if n%2==1 else sm | matrix-diagonal-sum | 2-Lines Python Solution || 70% Faster || Memory less than 98% | Taha-C | 0 | 66 | matrix diagonal sum | 1,572 | 0.798 | Easy | 23,184 |
https://leetcode.com/problems/matrix-diagonal-sum/discuss/1814986/Python3-O(n)-solution | class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
summ=0
n=len(mat)
r,c=0,0
while r<n and c<n:
summ+=mat[r][c]
if r!=n-c-1:
summ+=mat[r][n-c-1]
r+=1
c+=1
return summ | matrix-diagonal-sum | [Python3] O(n) solution | __PiYush__ | 0 | 41 | matrix diagonal sum | 1,572 | 0.798 | Easy | 23,185 |
https://leetcode.com/problems/matrix-diagonal-sum/discuss/1786511/Python-(On)-simple-solution-easy-understanding | class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
count = 0
start,end = 0, len(mat)-1
while start < len(mat):
if start == end:
count += mat[start][end]
else:
count += mat[start][end]
count += mat[start][start]
start+=1
end-=1
return count | matrix-diagonal-sum | Python, (On) simple solution, easy understanding | Nish786 | 0 | 72 | matrix diagonal sum | 1,572 | 0.798 | Easy | 23,186 |
https://leetcode.com/problems/matrix-diagonal-sum/discuss/1657403/Python-O(N)-Time-O(1)-Space-Better-than-83.69-and-99.41 | class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
n = len(mat)
diagonal_sum = 0
for i in range(n):
diagonal_sum += mat[i][i]
# Before adding the element for the second diagonal,
# make sure we are not in the middle element
if n - i != i + 1:
diagonal_sum += mat[i][-i - 1]
return diagonal_sum | matrix-diagonal-sum | Python O(N) Time, O(1) Space, Better than 83.69% and 99.41% | bobbyzia123 | 0 | 101 | matrix diagonal sum | 1,572 | 0.798 | Easy | 23,187 |
https://leetcode.com/problems/number-of-ways-to-split-a-string/discuss/830700/Python-3-or-Math-(Pass)-Backtracking-(TLE)-or-Explanation | class Solution:
def numWays(self, s: str) -> int:
total = s.count('1')
if total % 3: return 0
n = len(s)
if not total: return (1+n-2) * (n-2) // 2 % 1000000007
avg, ans = total // 3, 0
cnt = first_part_right_zeros = last_part_left_zeros = 0
for i in range(n):
if s[i] == '1': cnt += 1
elif cnt == avg: first_part_right_zeros += 1
elif cnt > avg: break
cnt = 0
for i in range(n-1, -1, -1):
if s[i] == '1': cnt += 1
elif cnt == avg: last_part_left_zeros += 1
elif cnt > avg: break
return (first_part_right_zeros+1) * (last_part_left_zeros+1) % 1000000007 | number-of-ways-to-split-a-string | Python 3 | Math (Pass), Backtracking (TLE) | Explanation | idontknoooo | 2 | 215 | number of ways to split a string | 1,573 | 0.325 | Medium | 23,188 |
https://leetcode.com/problems/number-of-ways-to-split-a-string/discuss/830700/Python-3-or-Math-(Pass)-Backtracking-(TLE)-or-Explanation | class Solution:
def numWays(self, s: str) -> int:
total = s.count('1')
if total % 3: return 0
avg = total // 3
n, ans = len(s), 0
@lru_cache(maxsize=None)
def dfs(s, idx, part):
nonlocal avg, n
if part == 4 and idx == n: return 1
cnt = cur = 0
for i in range(idx, n):
if s[i] == '1': cnt += 1
if cnt == avg: cur += dfs(s, i+1, part+1)
elif cnt > avg: break
return cur
return dfs(s, 0, 1) % 1000000007 | number-of-ways-to-split-a-string | Python 3 | Math (Pass), Backtracking (TLE) | Explanation | idontknoooo | 2 | 215 | number of ways to split a string | 1,573 | 0.325 | Medium | 23,189 |
https://leetcode.com/problems/number-of-ways-to-split-a-string/discuss/2520656/Python-easy-to-read-and-understand-or-math | class Solution:
def numWays(self, s: str) -> int:
cnt, n = 0, len(s)
mod = 10**9 + 7
for i in range(n):
if s[i] == '1':
cnt += 1
if cnt%3 != 0:
return 0
if cnt == 0:
return (n-1)*(n-2)//2 % (mod)
parts = cnt // 3
left, val1, i = 0, 0, 0
while i < n:
if s[i] == '1':
left += 1
i += 1
if left == parts:
while i < n and s[i] == '0':
val1 += 1
i += 1
break
right, val2, i = 0, 0, n-1
while i >= 0:
if s[i] == '1':
right += 1
i -= 1
if right == parts:
while i >= 0 and s[i] == '0':
val2 += 1
i -= 1
break
return (val1+1)*(val2+1) % (mod) | number-of-ways-to-split-a-string | Python easy to read and understand | math | sanial2001 | 0 | 117 | number of ways to split a string | 1,573 | 0.325 | Medium | 23,190 |
https://leetcode.com/problems/number-of-ways-to-split-a-string/discuss/1657626/Python-O(n)-time-O(n)-space-solution | class Solution:
def numWays(self, s: str) -> int:
n = len(s)
ones = s.count('1')
if ones % 3 != 0:
return 0
if ones == 0:
return (n-1)*(n-2)//2 % (10**9+7)
# now ones % 3 ==0, ones >= 3
k = ones//3
idx = []
total_idx = []
t = 0
for i in range(n):
if s[i] == '1':
t += 1
total_idx.append(i)
if t == k or t == 2*k or t == ones:
idx.append(i)
res = 1
idx.pop()
idx = set(idx)
for i in range(len(total_idx)):
if total_idx[i] in idx:
res = res * (total_idx[i+1]-total_idx[i]) % (10**9+7)
return res % (10**9+7) | number-of-ways-to-split-a-string | Python O(n) time, O(n) space solution | byuns9334 | 0 | 412 | number of ways to split a string | 1,573 | 0.325 | Medium | 23,191 |
https://leetcode.com/problems/number-of-ways-to-split-a-string/discuss/1358164/Python-Dynamic-Programming-%2B-Memoization | class Solution:
def numWays(self, s: str) -> int:
memo = {}
def backTracking(curr_path, s, count):
if (len(s), count) in memo:
return memo[(len(s), count)]
if not s:
if count == 3:
return 1
return 0
res = 0
for i in range(1, len(s) + 1):
sub_string = s[0 : i]
if curr_path == None:
res += backTracking(sub_string.count("1"), s[i : ], count + 1)
else:
if sub_string.count("1") == curr_path:
res += backTracking(sub_string.count("1"), s[i : ], count + 1)
else:
continue
memo[(len(s), count)] = res
return memo[(len(s), count)]
L = backTracking(None, s, 0)
return L | number-of-ways-to-split-a-string | [Python] Dynamic Programming + Memoization | Sai-Adarsh | 0 | 294 | number of ways to split a string | 1,573 | 0.325 | Medium | 23,192 |
https://leetcode.com/problems/number-of-ways-to-split-a-string/discuss/830874/Python3-counting-zeros-between-groups | class Solution:
def numWays(self, s: str) -> int:
n = s.count("1")
if n % 3: return 0 # impossible
if not n: ans = ((len(s)-1)*(len(s)-2)//2) # len(s)-1 choose 2
else:
ans = 1
ones = zeros = 0
for c in s:
if c == "1":
ones += 1
ans *= zeros + 1
zeros = 0
elif ones in (n//3, n*2//3): zeros += 1 # counting zeros between groups
return ans % 1_000_000_007 | number-of-ways-to-split-a-string | [Python3] counting zeros between groups | ye15 | 0 | 69 | number of ways to split a string | 1,573 | 0.325 | Medium | 23,193 |
https://leetcode.com/problems/number-of-ways-to-split-a-string/discuss/830785/Naive-Python-Solution | class Solution:
def numWays(self, s: str) -> int:
n = len(s)
mod = 10**9+7
numOnes = [0]*n
numOnes[0] = 1 if s[0] == '1' else 0
for i, ch in enumerate(s[1:]):
numOnes[i+1] += numOnes[i]
if ch == '1':
numOnes[i+1] += 1
i += 1
if numOnes[-1]%3 != 0:
return 0
elif numOnes[-1] == 0:
return ((n - 1)*(n-2)%mod)//2
else:
# get the required number of ones in each partition
val = numOnes[-1]//3
multiples = [val*1, val*2] # values to be counted in 'numOnes' array
res = 1
for multiple in multiples:
res = res*numOnes.count(multiple)%mod
return res | number-of-ways-to-split-a-string | Naive Python Solution | leetcodesujitraman | 0 | 60 | number of ways to split a string | 1,573 | 0.325 | Medium | 23,194 |
https://leetcode.com/problems/shortest-subarray-to-be-removed-to-make-array-sorted/discuss/835866/Python-Solution-Based-on-Binary-Search | class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
def lowerbound(left, right, target):
while left < right:
mid = left + (right - left) // 2
if arr[mid] == target:
right = mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid
return left
N = len(arr)
# find the longest ascending array on the left side
i = 0
while i + 1 < N and arr[i] <= arr[i+1]:
i += 1
if i == N - 1:
# it is already in ascending order
return 0
# find the longest ascending array on the right side
j = N - 1
while j - 1 >= 0 and arr[j] >= arr[j-1]:
j -= 1
if j == 0:
# the entire array is in decending order
return N - 1
# keep ascending array on right side or left side
result = min(N - (N - j), N - i -1)
# find the shortest unordered subarray in the middle
for k in range(i+1):
l = lowerbound(j, len(arr), arr[k])
result = min(result, l - (k + 1))
return result | shortest-subarray-to-be-removed-to-make-array-sorted | Python Solution Based on Binary Search | pochy | 4 | 694 | shortest subarray to be removed to make array sorted | 1,574 | 0.366 | Medium | 23,195 |
https://leetcode.com/problems/shortest-subarray-to-be-removed-to-make-array-sorted/discuss/865971/Python-Simple-and-concise-linear-time-Solution-beats-99.2 | class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
st = 0
end = len(arr) - 1
prev = None
st = Solution.find_end_subarray(arr=arr, st=0, inc_flag=True)
end = Solution.find_end_subarray(arr=arr, st=len(arr)-1, inc_flag=False)
merge_length = Solution.merge(st-1, end+1, arr)
take_first = len(arr) - st
take_end = end + 1
take_merged = len(arr) - merge_length
return min(take_first, min(take_end, take_merged))
@staticmethod
def find_end_subarray(arr, st, inc_flag, prev=None):
while(st < len(arr) if inc_flag else st >= 0):
if prev is None or (arr[st] >= prev if inc_flag else arr[st] <= prev):
prev = arr[st]
st = st + 1 if inc_flag else st - 1
else:
break
return st
@staticmethod
def merge(first_arr_end, second_arr_st, arr):
ans = 0
first_arr_st = 0
while(first_arr_st <= first_arr_end and second_arr_st < len(arr)):
if arr[first_arr_st] <= arr[second_arr_st]:
if first_arr_st >= second_arr_st:
ans = max(ans, len(arr) - 1)
break
else:
ans = max(ans, first_arr_st + len(arr) - second_arr_st + 1)
first_arr_st += 1
else:
second_arr_st += 1
return ans | shortest-subarray-to-be-removed-to-make-array-sorted | [Python] Simple and concise linear time Solution beats 99.2 % | vasu6 | 2 | 472 | shortest subarray to be removed to make array sorted | 1,574 | 0.366 | Medium | 23,196 |
https://leetcode.com/problems/shortest-subarray-to-be-removed-to-make-array-sorted/discuss/2470235/Python3-or-O(n)-Time-complexity-or-Two-pointers | class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
# sentinel
arr.append(float("inf"))
arr.insert(0, 0)
left = 0
right = len(arr) - 1
shortest = float("inf")
# find longest ascending array at left side.
while left < len(arr) - 2 and arr[left] <= arr[left + 1]:
left += 1
# [0, 1, 2, 3, 10, 4, 2, 3, 5, β]
# β
# left
# move right pointer while moving left pointer.
while left >= 0:
while right - 1 > left and arr[right - 1] >= arr[left] and arr[right] >= arr[right - 1]:
right -= 1
shortest = min(shortest, right - left - 1)
left -= 1
# [0, 1, 2, 3, 10, 4, 2, 3, 5, β]
# β β
# left right -> length = 4
#
# [0, 1, 2, 3, 10, 4, 2, 3, 5, β]
# β β
# left right -> length = 3
#
# [0, 1, 2, 3, 10, 4, 2, 3, 5, β]
# β β
# left right -> length = 3
#
# [0, 1, 2, 3, 10, 4, 2, 3, 5, β]
# β β
# left right -> length = 3
#
# [0, 1, 2, 3, 10, 4, 2, 3, 5, β]
# β β
# left right -> length = 4
#
# [0, 1, 2, 3, 10, 4, 2, 3, 5, β]
# β β
# left right -> length = 5
return shortest | shortest-subarray-to-be-removed-to-make-array-sorted | Python3 | O(n) Time complexity | Two pointers | shugokra | 1 | 197 | shortest subarray to be removed to make array sorted | 1,574 | 0.366 | Medium | 23,197 |
https://leetcode.com/problems/shortest-subarray-to-be-removed-to-make-array-sorted/discuss/2846886/Break-the-array-and-binary-search | class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
left, right = 0, len(arr) - 1
while left < len(arr) - 1 and arr[left] <= arr[left + 1]:
left += 1
if left == right: return 0
while right > 0 and arr[right] >= arr[right - 1]:
right -= 1
res = inf
for i in range(left + 1):
if arr[-1] < arr[i]:
res = min(res, len(arr) - i - 1)
continue
lo, hi = right, len(arr) - 1
while lo < hi:
mid = lo + (hi - lo) // 2
if arr[mid] >= arr[i]:
hi = mid
else:
lo = mid + 1
res = min(res, hi - i - 1)
for i in range(right, len(arr)):
if arr[0] > arr[i]:
res = min(res, right)
continue
lo, hi = 0, left
while lo < hi:
mid = lo + (hi - lo + 1) // 2
if arr[mid] <= arr[i]:
lo = mid
else:
hi = mid - 1
res = min(res, i - lo - 1)
return res | shortest-subarray-to-be-removed-to-make-array-sorted | Break the array and binary search | michaelniki | 0 | 1 | shortest subarray to be removed to make array sorted | 1,574 | 0.366 | Medium | 23,198 |
https://leetcode.com/problems/shortest-subarray-to-be-removed-to-make-array-sorted/discuss/2316103/Python-easy-to-read-and-understand-or-two-pointers | class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
n = len(arr)
i = 0
while i < n-1 and arr[i+1] >= arr[i]:
i += 1
if i == n-1:
return 0
j = n-1
while j >= 0 and arr[j-1] <= arr[j]:
j -= 1
ans = min(n, n-i-1, j)
for l in range(i+1):
r = j
while r < n and arr[r] < arr[l]:
r += 1
ans = min(ans, r-l-1)
return ans | shortest-subarray-to-be-removed-to-make-array-sorted | Python easy to read and understand | two-pointers | sanial2001 | 0 | 192 | shortest subarray to be removed to make array sorted | 1,574 | 0.366 | Medium | 23,199 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.