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/maximum-length-of-repeated-subarray/discuss/1324567/well-explained-oror-With-and-Without-DP-oror-99.66-faster-oror-Easily-Understandable | class Solution:
def findLength(self, nums1: List[int], nums2: List[int]) -> int:
m=len(nums1)
n=len(nums2)
dp = [[0 for _ in range(n+1)] for _ in range(m+1)]
res=0
for i in range(m):
for j in range(n):
if nums1[i]==nums2[j]:
dp[i+1][j+1]=dp[i][j]+1
else:
dp[i+1][j+1]=0
res=max(res,dp[i+1][j+1])
return res | maximum-length-of-repeated-subarray | π well-explained || [ With and Without DP ] || 99.66 % faster || Easily-Understandable π | abhi9Rai | 10 | 994 | maximum length of repeated subarray | 718 | 0.515 | Medium | 11,800 |
https://leetcode.com/problems/maximum-length-of-repeated-subarray/discuss/1557033/Very-simple-and-fast-Python-solution | class Solution:
def findLength(self, nums1: List[int], nums2: List[int]) -> int:
res = 0
# left to right sliding
for k in range(len(nums1)):
s = 0
for (x1,x2) in zip(nums1[k:],nums2):
if x1==x2:
s += 1
else:
res = max(res,s)
s = 0
res = max(res,s)
# right to left sliding
for k in range(len(nums2)):
s = 0
for (x1,x2) in zip(nums2[k:],nums1):
if x1==x2:
s += 1
else:
res = max(res,s)
s = 0
res = max(res,s)
return res | maximum-length-of-repeated-subarray | Very simple and fast Python solution | cyrille-k | 9 | 520 | maximum length of repeated subarray | 718 | 0.515 | Medium | 11,801 |
https://leetcode.com/problems/maximum-length-of-repeated-subarray/discuss/958194/Python3-%22Longest-Common-Substring%22-concept-!! | class Solution:
def findLength(self, A: List[int], B: List[int]) -> int:
if not A or not B:
return 0
return self.lcs(A,B)
def lcs(self,a,b):
n = len(a)
m = len(b)
dp = [[0]*(n+1) for i in range(m+1)]
res = 0
for i in range(1,n+1):
for j in range(1,m+1):
if a[i-1] == b[j-1]:
dp[i][j] = 1 + dp[i-1][j-1]
res = max(res,dp[i][j])
else:
dp[i][j] = 0
return res | maximum-length-of-repeated-subarray | [Python3] "Longest Common Substring" concept !! | tilak_ | 4 | 565 | maximum length of repeated subarray | 718 | 0.515 | Medium | 11,802 |
https://leetcode.com/problems/maximum-length-of-repeated-subarray/discuss/2600837/Python-Simple-Python-Solution-Using-Dynamic-Programming | class Solution:
def findLength(self, nums1: List[int], nums2: List[int]) -> int:
result = 0
dp = [[0] * (len(nums2)+1) for _ in range(len(nums1)+1)]
for i in range(len(nums1)):
for j in range(len(nums2)):
if nums1[i] == nums2[j]:
new_value = dp[i][j] + 1
dp[i+1][j+1] = new_value
result = max(result, new_value)
return result | maximum-length-of-repeated-subarray | [ Python ] β
β
Simple Python Solution Using Dynamic Programming π₯³βπ | ASHOK_KUMAR_MEGHVANSHI | 3 | 417 | maximum length of repeated subarray | 718 | 0.515 | Medium | 11,803 |
https://leetcode.com/problems/maximum-length-of-repeated-subarray/discuss/2599274/python3-oror-7-lines-memo-wexplanation-oror-TM%3A-8179 | class Solution: # 1) We build memo, a 2Darray, 2) iterate thru nums1 & nums2
# in reverse to populate memo, and then 3) find the max element
# in memo; its row and col in memo shows the starting indices
# for the common seq in nums1 and nums2.
def findLength(self, nums1: List[int], nums2: List[int]) -> int:
n1, n2 = len(nums1), len(nums2)
memo = [[0]*(n2+1) for _ in range(n1+1)] # <-- 1)
for idx1 in range(n1)[::-1]:
for idx2 in range(n2)[::-1]:
if nums1[idx1] == nums2[idx2]:
memo[idx1][idx2] = 1 + memo[idx1+1][idx2+1] # <-- 2)
return max(chain(*memo)) # <-- 3) | maximum-length-of-repeated-subarray | python3 || 7 lines, memo, w/explanation || T/M: 81%/79% | warrenruud | 3 | 271 | maximum length of repeated subarray | 718 | 0.515 | Medium | 11,804 |
https://leetcode.com/problems/maximum-length-of-repeated-subarray/discuss/915316/Python3-DP-and-binary-search | class Solution:
def findLength(self, A: List[int], B: List[int]) -> int:
m, n = len(A), len(B)
dp = [[0]*(n+1) for _ in range(m+1)] # (m+1) x (n+1)
ans = 0
for i in reversed(range(m)):
for j in reversed(range(n)):
if A[i] == B[j]: dp[i][j] = 1 + dp[i+1][j+1]
ans = max(ans, dp[i][j])
return ans | maximum-length-of-repeated-subarray | [Python3] DP & binary search | ye15 | 3 | 222 | maximum length of repeated subarray | 718 | 0.515 | Medium | 11,805 |
https://leetcode.com/problems/maximum-length-of-repeated-subarray/discuss/915316/Python3-DP-and-binary-search | class Solution:
def findLength(self, A: List[int], B: List[int]) -> int:
def fn(k):
"""Return True if a subarray of length k can be found in A and B."""
seen = {}
rh = 0 # rolling hash
for i in range(len(A)):
rh = (100*rh + A[i] - (i >= k)*A[i-k]*100**k) % 1_000_000_007
if i >= k-1: seen.setdefault(rh, []).append(i)
rh = 0
for i in range(len(B)):
rh = (100*rh + B[i] - (i >= k)*B[i-k]*100**k) % 1_000_000_007
if i >= k-1:
for ii in seen.get(rh, []):
if A[ii-k+1:ii+1] == B[i-k+1:i+1]: return True
return False
# last True binary search
lo, hi = -1, len(A)
while lo < hi:
mid = lo + hi + 1>> 1
if fn(mid): lo = mid
else: hi = mid - 1
return lo | maximum-length-of-repeated-subarray | [Python3] DP & binary search | ye15 | 3 | 222 | maximum length of repeated subarray | 718 | 0.515 | Medium | 11,806 |
https://leetcode.com/problems/maximum-length-of-repeated-subarray/discuss/2599312/Python-Elegant-and-Short-or-Bottom-Up-DP | class Solution:
"""
Time: O(n*m)
Memory: O(n*m)
"""
def findLength(self, a: List[int], b: List[int]) -> int:
n, m = len(a), len(b)
dp = [[0] * (m + 1) for _ in range(n + 1)]
for i in range(n):
for j in range(m):
if a[i] == b[j]:
dp[i + 1][j + 1] = dp[i][j] + 1
return max(map(max, dp)) | maximum-length-of-repeated-subarray | Python Elegant & Short | Bottom-Up DP | Kyrylo-Ktl | 2 | 260 | maximum length of repeated subarray | 718 | 0.515 | Medium | 11,807 |
https://leetcode.com/problems/maximum-length-of-repeated-subarray/discuss/1449088/Simple-Python-O(mn)-dynamic-programming-solution | class Solution:
def findLength(self, nums1: List[int], nums2: List[int]) -> int:
# let dp[i][j] be the maximum length of repeated subarray
# ending with the ith element in nums1 and jth element in nums2
# state transition:
# dp[i][j] = dp[i-1][j-1]+1 if nums[i-1] == nums[j-1]
# dp[i][j] = 0 otherwise
m, n = len(nums1), len(nums2)
dp = [[0]*(n+1) for _ in range(m+1)]
for i in range(1, m+1):
for j in range(1, n+1):
if nums1[i-1] == nums2[j-1]:
dp[i][j] = dp[i-1][j-1]+1
return max(max(row) for row in dp) | maximum-length-of-repeated-subarray | Simple Python O(mn) dynamic programming solution | Charlesl0129 | 2 | 228 | maximum length of repeated subarray | 718 | 0.515 | Medium | 11,808 |
https://leetcode.com/problems/maximum-length-of-repeated-subarray/discuss/772768/Python-1-liner | class Solution:
def findLength(self, A: List[int], B: List[int]) -> int:
return max(map(max,reduce(lambda y,a:y+[[a==b and(1+(i and y[-1][i-1]))for i,b in enumerate(B)]],A,[[0]*len(B)]))) | maximum-length-of-repeated-subarray | Python 1-liner | ekovalyov | 2 | 318 | maximum length of repeated subarray | 718 | 0.515 | Medium | 11,809 |
https://leetcode.com/problems/maximum-length-of-repeated-subarray/discuss/2637344/Python3-Solution-using-2D-DP-oror-Tabulation-Solution | class Solution:
def findLength(self, nums1: List[int], nums2: List[int]) -> int:
m = len(nums1)
n = len(nums2)
dp = [[0]*n for _ in range(m)]
maxval = 0
for i in range(m):
for j in range(n):
if nums1[i] == nums2[j]:
if i > 0 and j >0:
dp[i][j] = 1+dp[i-1][j-1]
else:
dp[i][j] = 1
maxval = max(maxval,dp[i][j])
return maxval
#Please Upvote if you like the solution!!! | maximum-length-of-repeated-subarray | Python3 Solution using 2D DP || Tabulation Solution | hoo__mann | 1 | 38 | maximum length of repeated subarray | 718 | 0.515 | Medium | 11,810 |
https://leetcode.com/problems/maximum-length-of-repeated-subarray/discuss/2599421/SIMPLE-PYTHON3-SOLUTION-98-fassster-than-others | class Solution:
def findLength(self, nums1: List[int], nums2: List[int]) -> int:
strnum2 = ''.join([chr(x) for x in nums2])
strmax = ''
ans = 0
for num in nums1:
strmax += chr(num)
if strmax in strnum2:
ans = max(ans,len(strmax))
else:
strmax = strmax[1:]
return ans | maximum-length-of-repeated-subarray | β
β SIMPLE PYTHON3 SOLUTION β
β98% fassster than others | rajukommula | 1 | 132 | maximum length of repeated subarray | 718 | 0.515 | Medium | 11,811 |
https://leetcode.com/problems/maximum-length-of-repeated-subarray/discuss/2543259/Longest-common-substring-or-Python-DP | class Solution:
def findLength(self, nums1: List[int], nums2: List[int]) -> int:
m=len(nums1)
n=len(nums2)
dp=[[0 for i in range(m+1)]for j in range(n+1)]
ans=0
for i in range(1,n+1):
for j in range(1,m+1):
if nums2[i-1]==nums1[j-1]:
dp[i][j]=dp[i-1][j-1]+1
if dp[i][j]>ans:
ans=dp[i][j]
# print(dp)
return ans | maximum-length-of-repeated-subarray | Longest common substring | Python DP | Prithiviraj1927 | 1 | 108 | maximum length of repeated subarray | 718 | 0.515 | Medium | 11,812 |
https://leetcode.com/problems/maximum-length-of-repeated-subarray/discuss/1777997/Java-Python3-Simple-DP-Solution-(Top-Down-and-Bottom-Up) | class Solution:
def findLength(self, nums1: List[int], nums2: List[int]) -> int:
m, n = len(nums1), len(nums2)
maxlen = 0
@lru_cache(None)
def dp(i: int, j: int) -> int:
nonlocal maxlen
if i == m:
return 0
if j == n:
return 0
dp(i+1, j)
dp(i, j+1)
if nums1[i] == nums2[j]:
res = 1 + dp(i+1, j+1)
maxlen = max(maxlen, res)
return res
else:
return 0
dp(0, 0)
return maxlen | maximum-length-of-repeated-subarray | β
[Java / Python3] Simple DP Solution (Top-Down & Bottom-Up) | JawadNoor | 1 | 153 | maximum length of repeated subarray | 718 | 0.515 | Medium | 11,813 |
https://leetcode.com/problems/maximum-length-of-repeated-subarray/discuss/1777997/Java-Python3-Simple-DP-Solution-(Top-Down-and-Bottom-Up) | class Solution:
def findLength(self, nums1: List[int], nums2: List[int]) -> int:
m, n = len(nums1), len(nums2)
dp = [[0]*(n+1) for _ in range(m+1)]
maxlen = 0
for i in range(m):
for j in range(n):
if nums1[i] == nums2[j]:
dp[i+1][j+1] = 1 + dp[i][j]
maxlen = max(maxlen, dp[i+1][j+1])
return maxlen | maximum-length-of-repeated-subarray | β
[Java / Python3] Simple DP Solution (Top-Down & Bottom-Up) | JawadNoor | 1 | 153 | maximum length of repeated subarray | 718 | 0.515 | Medium | 11,814 |
https://leetcode.com/problems/maximum-length-of-repeated-subarray/discuss/1325736/Python3Without-DP-or-faster-than-99.21-or-chr-or-Explained | class Solution:
def findLength(self, nums1: List[int], nums2: List[int]) -> int:
# Fetch the Ascii value for each elements and store them as string
nums1 = ''.join([chr(x) for x in nums1])
nums2 = ''.join([chr(x) for x in nums2])
bi, sm = "", ""
if len(nums1) < len(nums2):
bi, sm = nums2, nums1
else:
bi, sm = nums1, nums2
n, i, j, res = len(sm), 0, 1, 0
while j <= n:
if sm[i:j] in bi:
tmp = len(sm[i:j])
if tmp > res:
res = tmp
j += 1
else:
i += 1
j += 1
return res | maximum-length-of-repeated-subarray | [Python3]Without DP | faster than 99.21% | chr | Explained | SushilG96 | 1 | 138 | maximum length of repeated subarray | 718 | 0.515 | Medium | 11,815 |
https://leetcode.com/problems/maximum-length-of-repeated-subarray/discuss/1090222/Easy-Python-or-99-Speed-or-Binary-Search-%2B-HashSet-Database | class Solution:
def findLength(self, A, B):
if len(A)>len(B):
A,B = B,A
A = tuple(A)
B = tuple(B)
La, Lb = len(A), len(B)
def isvalid(k):
D = set( A[i:i+k] for i in range(La-k+1) )
for j in range(Lb-k+1):
if B[j:j+k] in D:
return True
return False
lo, hi = 0, len(A)
best = 0
while lo<=hi:
mid = (lo+hi) >> 1
if isvalid(mid):
best = mid
lo = mid + 1
else:
hi = mid - 1
return best | maximum-length-of-repeated-subarray | Easy Python | 99% Speed | Binary Search + HashSet Database | Aragorn_ | 1 | 195 | maximum length of repeated subarray | 718 | 0.515 | Medium | 11,816 |
https://leetcode.com/problems/maximum-length-of-repeated-subarray/discuss/2818125/Python-Dynamic-Programming-Solution | class Solution:
def findLength(self, nums1: List[int], nums2: List[int]) -> int:
n, m = len(nums1), len(nums2)
dp = [[0] * (m+1) for _ in range(n+1)]
for i in range(n - 1, -1, -1):
for j in range(m - 1, -1, -1):
if nums1[i] == nums2[j]:
dp[i][j] = 1 + dp[i + 1][j + 1]
return max([max(row) for row in dp]) | maximum-length-of-repeated-subarray | Python Dynamic Programming Solution | Zhouyao_Xie | 0 | 4 | maximum length of repeated subarray | 718 | 0.515 | Medium | 11,817 |
https://leetcode.com/problems/maximum-length-of-repeated-subarray/discuss/2818105/Python-Sliding-Window-Solution | class Solution:
def findLength(self, nums1: List[int], nums2: List[int]) -> int:
max_len = 0
n, m = len(nums1), len(nums2)
for i in range(-n+1, n+m):
l = 0
for s2 in range(len(nums2)):
s1 = s2 + i
if s1 < 0: continue
if s1 >= n: break
if nums1[s1] == nums2[s2]:
l += 1
max_len = max(max_len, l)
else:
l = 0
return max_len | maximum-length-of-repeated-subarray | Python Sliding Window Solution | Zhouyao_Xie | 0 | 2 | maximum length of repeated subarray | 718 | 0.515 | Medium | 11,818 |
https://leetcode.com/problems/maximum-length-of-repeated-subarray/discuss/2607979/Python-3-Rolling-Hash-%2B-Binary-Search-or-Clean-Code-or-O(log(min(m-n))-*-max(m-n)) | class Solution:
def findLength(self, nums1: List[int], nums2: List[int]) -> int:
l, r = 0, min(len(nums1), len(nums2)) + 1
# for i in range(r + 1):
# print(i, self.exist_length_k(nums1, nums2, i))
while l < r: # O(log(min(m, n)) * O(exist_length_k) = O(log(min(m, n)) * O(max(m, n))
k = l + (r - l) // 2
# print(l, r, k)
if self.exist_length_k(nums1, nums2, k):
l = k + 1
else:
r = k
return l - 1
def exist_length_k(self, nums1: List[int], nums2: List[int], k: int, p = 101, m = 10 ** 9 + 7) -> bool:
# O(m) + O(n) + O(min(m, n)) = O(max(m, n))
if k == 0:
return True
s1 = self.rolling_hash(nums1, k) # O(m)
s2 = self.rolling_hash(nums2, k) # O(n)
if len(s1) > len(s2):
s1, s2 = s2, s1
for h in s1: # O(min(m, n))
if h in s2:
return True
return False
def rolling_hash(self, nums: List[int], k: int, p = 101, m = 10 ** 9 + 7) -> Set[int]:
if k == 0:
return set()
s = set()
t = p ** k % m
h = 0
for i in range(k):
h = (h * p + nums[i]) % m
s.add(h)
for i in range(k, len(nums)):
h = (h * p - nums[i - k] * t + nums[i]) % m
s.add(h)
return s | maximum-length-of-repeated-subarray | [Python 3] Rolling Hash + Binary Search | Clean Code | O(log(min(m, n)) * max(m, n)) | ge-li | 0 | 17 | maximum length of repeated subarray | 718 | 0.515 | Medium | 11,819 |
https://leetcode.com/problems/maximum-length-of-repeated-subarray/discuss/2603100/Easy-explanation-Bottom-up-DP-but-not-from-n-1-to-0! | class Solution(object):
def findLength(self, A, B):
dp = [[0] * (len(B)) for _ in range(len(A))]
ans = 0
for i in range(len(A)):
for j in range(len(B)):
if A[i] == B[j]:
dp[i][j] = 1
if i > 0 and j > 0 and dp[i-1][j-1]:
dp[i][j] = dp[i-1][j-1] + 1
ans = max(ans,dp[i][j])
return ans | maximum-length-of-repeated-subarray | Easy explanation, Bottom up DP but not from n-1 to 0! | imanhn | 0 | 12 | maximum length of repeated subarray | 718 | 0.515 | Medium | 11,820 |
https://leetcode.com/problems/maximum-length-of-repeated-subarray/discuss/2603028/Faster-than-99.69-FAST-and-SiMPLE-python-solution-Runtime%3A-155-ms-faster-than-99.69-of-Python3 | class Solution:
def findLength(self, nums1, nums2):
string_num2 = "".join([chr(ch) for ch in nums2])
curr = ""
ans = 0
for num in nums1:
curr += chr(num)
# if curr in num2 then check the length of curr
if curr in string_num2:
ans = max(ans, len(curr))
else:
# removing first char from curr string because its not in nums2
curr = curr[1:]
return ans | maximum-length-of-repeated-subarray | Faster than 99.69% FAST and SiMPLE python solution [Runtime: 155 ms, faster than 99.69% of Python3] | 01_Toyota_Land_Cruiser | 0 | 13 | maximum length of repeated subarray | 718 | 0.515 | Medium | 11,821 |
https://leetcode.com/problems/maximum-length-of-repeated-subarray/discuss/2600479/GolangPython-O(M*N)-time-or-O(min(MN))-space.-Dynamic-programming-solution | class Solution:
def findLength(self, nums1: List[int], nums2: List[int]) -> int:
if len(nums2) > len(nums1):
nums1,nums2 = nums2,nums1
prev = [0 for _ in range(len(nums2)+1)]
curr = [0 for _ in range(len(nums2)+1)]
answer = 0
for i in range(1,len(nums1)+1):
for j in range(1,len(nums2)+1):
if nums1[i-1] == nums2[j-1]:
curr[j] = prev[j-1]+1
answer = max(answer,curr[j])
else:
curr[j] = 0
curr,prev = prev,curr
return answer | maximum-length-of-repeated-subarray | Golang/Python O(M*N) time | O(min(M,N)) space. Dynamic programming solution | vtalantsev | 0 | 17 | maximum length of repeated subarray | 718 | 0.515 | Medium | 11,822 |
https://leetcode.com/problems/maximum-length-of-repeated-subarray/discuss/2600464/Simple-%22python%22-Solution | class Solution:
def findLength(self, nums1: List[int], nums2: List[int]) -> int:
nums2_str = "".join([chr(i) for i in nums2])
max_str = ""
res = 0
for i in nums1:
max_str += chr(i)
if max_str in nums2_str:
res = max(res,len(max_str))
else:
max_str = max_str[1:]
return res | maximum-length-of-repeated-subarray | Simple "python" Solution | anandchauhan8791 | 0 | 45 | maximum length of repeated subarray | 718 | 0.515 | Medium | 11,823 |
https://leetcode.com/problems/maximum-length-of-repeated-subarray/discuss/2599631/Python-Solution-or-LCS-or-DP | class Solution:
def findLength(self, nums1: List[int], nums2: List[int]) -> int:
n=len(nums1)
m=len(nums2)
dp=[[0]*(m+1) for i in range(n+1)]
ans=0
for i in range(1, n+1):
for j in range(1, m+1):
if nums1[i-1]==nums2[j-1]:
dp[i][j]=1+dp[i-1][j-1]
ans=max(ans, dp[i][j])
return ans | maximum-length-of-repeated-subarray | Python Solution | LCS | DP | Siddharth_singh | 0 | 50 | maximum length of repeated subarray | 718 | 0.515 | Medium | 11,824 |
https://leetcode.com/problems/maximum-length-of-repeated-subarray/discuss/2457543/Easy-DP | class Solution:
def findLength(self, nums1: List[int], nums2: List[int]) -> int:
n = len(nums1)
m = len(nums2)
dp = [[0 for i in range(n+1)] for j in range(m+1)]
ans = 0
for i in range(1,m+1):
for j in range(1,n+1):
if nums1[j-1] == nums2[i-1]:
dp[i][j] = dp[i-1][j-1]+1
ans = max(ans,dp[i][j])
return ans | maximum-length-of-repeated-subarray | Easy DP | jayeshmaheshwari555 | 0 | 34 | maximum length of repeated subarray | 718 | 0.515 | Medium | 11,825 |
https://leetcode.com/problems/maximum-length-of-repeated-subarray/discuss/2450234/Maximum-Length-of-Repeated-Subarray-oror-Python3-oror-DP | class Solution:
def findLength(self, nums1: List[int], nums2: List[int]) -> int:
dp = [[0] * (len(nums1)+1) for i in range(len(nums2)+1)]
ans = 0
for i in range(1, len(dp)): # for nums2
for j in range(1, len(dp[0])): # for nums1
if(nums2[i-1] == nums1[j-1]):
dp[i][j] = dp[i-1][j-1] + 1
ans = max(ans, dp[i][j])
return ans | maximum-length-of-repeated-subarray | Maximum Length of Repeated Subarray || Python3 || DP | vanshika_2507 | 0 | 45 | maximum length of repeated subarray | 718 | 0.515 | Medium | 11,826 |
https://leetcode.com/problems/maximum-length-of-repeated-subarray/discuss/2393218/Python3-oror-Tabulation-method-oror-Dynamic-Programming-oror-Elegant-and-clean | class Solution:
def findLength(self, nums1: List[int], nums2: List[int]) -> int:
dp = [[0]*(len(nums1)+ 1) for _ in range(len(nums2) + 1)]
max_len = 0
for row in range(len(nums2)):
for col in range(len(nums1)):
if nums2[row] == nums1[col]:
dp[row][col] = 1 + dp[row - 1][col - 1]
max_len = max(max_len,dp[row][col])
else:
dp[row][col] = 0
return max_len | maximum-length-of-repeated-subarray | Python3 || Tabulation method || Dynamic Programming || Elegant and clean | Sefinehtesfa34 | 0 | 32 | maximum length of repeated subarray | 718 | 0.515 | Medium | 11,827 |
https://leetcode.com/problems/maximum-length-of-repeated-subarray/discuss/2334271/Very-Simple-Bottom-Up-or-Python | class Solution:
def findLength(self, nums1: List[int], nums2: List[int]) -> int:
dp = [[0 for _ in range(len(nums2)+1)] for _ in range(len(nums1)+1)]
ans = 0
for i in range(1,len(dp)):
for j in range(1,len(dp[0])):
if nums1[i-1] == nums2[j-1]:
dp[i][j] = 1 + dp[i-1][j-1]
ans = max(ans,dp[i][j])
return ans | maximum-length-of-repeated-subarray | Very Simple Bottom-Up | Python | bliqlegend | 0 | 61 | maximum length of repeated subarray | 718 | 0.515 | Medium | 11,828 |
https://leetcode.com/problems/maximum-length-of-repeated-subarray/discuss/2140474/Python3-or-DP-or-T(n)-O(m*n)-S(n)-O(n) | class Solution:
def findLength(self, nums1: List[int], nums2: List[int]) -> int:
m, n = len(nums1), len(nums2)
mx = -float('inf')
prev = [0 for _ in range(n + 1)]
cur = [0 for _ in range(n + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if nums1[i-1] == nums2[j-1]:
cur[j] = prev[j-1] + 1
mx = max(mx, cur[j])
prev = cur
cur = [0 for _ in range(n + 1)]
return mx | maximum-length-of-repeated-subarray | Python3 | DP | T(n) = O(m*n), S(n) = O(n) | Ploypaphat | 0 | 39 | maximum length of repeated subarray | 718 | 0.515 | Medium | 11,829 |
https://leetcode.com/problems/maximum-length-of-repeated-subarray/discuss/1324844/Python-3-Binary-Search-%2B-Rolling-Hash-(164ms)-O(log(min(m-n))*(m%2Bn)) | class Solution:
def findLength(self, nums1: List[int], nums2: List[int]) -> int:
def helper(l):
base = 1 << 7
M = 10 **9 + 7
a = pow(base, l, M)
t1, t2 = 0, 0
hashes = set()
for i in range(len(nums1)):
t1 = (base * t1 + nums1[i]) % M
if i >= l:
t1 -= a * nums1[i - l]
t1 %= M
if i >= l - 1:
hashes.add(t1)
for j in range(len(nums2)):
t2 = (base * t2 + nums2[j]) % M
if j >= l:
t2 -= a * nums2[j - l]
t2 %= M
if j >= l - 1:
if t2 in hashes: return True
return False
a, b = 0, min(len(nums1), len(nums2))
while a < b:
m = (a + b + 1) // 2
if helper(m):
a = m
else:
b = m - 1
return a | maximum-length-of-repeated-subarray | [Python 3] Binary Search + Rolling Hash (164ms) O(log(min(m, n))*(m+n)) | chestnut890123 | 0 | 100 | maximum length of repeated subarray | 718 | 0.515 | Medium | 11,830 |
https://leetcode.com/problems/find-k-th-smallest-pair-distance/discuss/2581420/Simple-python-binary-search | class Solution:
def smallestDistancePair(self, nums: List[int], k: int) -> int:
def getPairs(diff):
l = 0
count = 0
for r in range(len(nums)):
while nums[r] - nums[l] > diff:
l += 1
count += r - l
return count
nums.sort()
l, r = 0, nums[-1] - nums[0]
while l < r:
mid = (l + r) // 2
res = getPairs(mid)
if res >= k:
r = mid
else:
l = mid + 1
return l | find-k-th-smallest-pair-distance | Simple python binary search | shubhamnishad25 | 1 | 123 | find k th smallest pair distance | 719 | 0.364 | Hard | 11,831 |
https://leetcode.com/problems/find-k-th-smallest-pair-distance/discuss/1495743/Python3-binary-search | class Solution:
def smallestDistancePair(self, nums: List[int], k: int) -> int:
nums.sort()
def fn(val):
"""Return count of pairs whose diff <= val."""
ans = ii = 0
for i, x in enumerate(nums):
while ii < i and x - nums[ii] > val: ii += 1
ans += i - ii
return ans
lo, hi = 0, nums[-1] - nums[0]
while lo < hi:
mid = lo + hi >> 1
if fn(mid) < k: lo = mid + 1
else: hi = mid
return lo | find-k-th-smallest-pair-distance | [Python3] binary search | ye15 | 1 | 112 | find k th smallest pair distance | 719 | 0.364 | Hard | 11,832 |
https://leetcode.com/problems/find-k-th-smallest-pair-distance/discuss/2732256/Sort-%2B-Binary-Search-Distance-Value-%2B-Sliding-Window-(Beats-94.72) | class Solution:
def smallestDistancePair(self, nums: List[int], k: int) -> int:
nums.sort()
N = len(nums)
def less(v):
"""number of distances < v"""
cnt, left = 0, 0
for right in range(1, N):
while left < right and nums[right] - nums[left] >= v:
left += 1
cnt += right - left
return cnt
lo, hi = 0, max(nums) - min(nums)
while lo <= hi:
v = (lo+hi) // 2
cnt = less(v)
if cnt < k:
lo = v + 1
else:
hi = v - 1
return hi | find-k-th-smallest-pair-distance | Sort + Binary Search Distance Value + Sliding Window (Beats 94.72%) | GregHuang | 0 | 11 | find k th smallest pair distance | 719 | 0.364 | Hard | 11,833 |
https://leetcode.com/problems/longest-word-in-dictionary/discuss/2075147/Python-O(n-log(n))-Time-O(n)-Space-Faster-Than-95 | class Solution:
def longestWord(self, words: List[str]) -> str:
words.sort() # for smallest lexicographical order
visited = {""} # hashset to keep a track of visited words
res = ''
for word in words:
if word[:-1] in visited: # check previous word ie. word[:len(word)-1] visited or not
visited.add(word) # add this word to the set
if len(word) > len(res): # current word have greater lenght and lexicographically smaller
res = word # update res
return res
# Time: O(n log(n)) # for sorting the words
# Space: O(n) # for making the set visited | longest-word-in-dictionary | [Python] O(n log(n)) Time, O(n) Space Faster Than 95% | samirpaul1 | 4 | 217 | longest word in dictionary | 720 | 0.518 | Medium | 11,834 |
https://leetcode.com/problems/longest-word-in-dictionary/discuss/2795751/Binary-search-O(nlogn)-time-without-allocated-memory | class Solution:
def longestWord(self, words: List[str]) -> str:
words.sort()
max_len = 1
symbol = ']'
ans = None
for i in range(len(words)):
if len(words[i]) == 1:
words[i] = words[i] + symbol
if max_len < len(words[i]):
max_len = len(words[i])
ans = words[i]
else:
word = words[i][:-1] + symbol
index = bisect.bisect_left(words, word)
if index < len(words) and words[index] == word:
words[i] = words[i] + symbol
if max_len < len(words[i]):
max_len = len(words[i])
ans = words[i]
if not ans:
return ""
return ans[:-1] | longest-word-in-dictionary | Binary search O(nlogn) time, without allocated memory | zlmrfi | 0 | 7 | longest word in dictionary | 720 | 0.518 | Medium | 11,835 |
https://leetcode.com/problems/longest-word-in-dictionary/discuss/2648390/Solution-using-dictionary-Python3 | class Solution:
def longestWord(self, words: List[str]) -> str:
word_map = {}
max_len = 0
for word in sorted(words):
if len(word) == 1:
word_map[word] = True
max_len = max(max_len, len(word))
elif word_map.get(word[:-1]):
word_map[word] = True
max_len = max(max_len, len(word))
else:
word_map[word] = False
answers = [word for word, flag in word_map.items() if flag and len(word) == max_len]
if len(answers) > 0:
return min(answers)
return "" | longest-word-in-dictionary | Solution using dictionary Python3 | ogbird | 0 | 7 | longest word in dictionary | 720 | 0.518 | Medium | 11,836 |
https://leetcode.com/problems/longest-word-in-dictionary/discuss/2415280/Python-beats-95-simple-solution-without-Trie-DFS-%2B-memoization | class Solution:
def longestWord(self, words: List[str]) -> str:
# dfs + memo
# Complexity Analysis:
# Time: O(NK)
# Space: O(N)
max_word = ''
def dfs(word):
nonlocal max_word
if word in memo: return memo[word]
curr_len = 0
if word == '':
curr_len = 0
elif word[:-1] in words_set:
curr_len = 1 + dfs(word[:-1])
else:
curr_len = float('-inf')
if curr_len > len(max_word) or (curr_len == len(max_word) and word < max_word):
max_word = word
memo[word] = curr_len
return curr_len
# create words set
words_set = set(words)
words_set.add('')
memo = {}
# iterate words
for word in words:
# call dfs for each word
dfs(word)
return max_word | longest-word-in-dictionary | Python - beats 95% - simple solution without Trie - DFS + memoization | ChenAmos | 0 | 48 | longest word in dictionary | 720 | 0.518 | Medium | 11,837 |
https://leetcode.com/problems/longest-word-in-dictionary/discuss/1895623/Python-easy-to-read-and-understand | class Solution:
def longestWord(self, words: List[str]) -> str:
words.sort()
ans = ''
contains = set([''])
for word in words:
if word[:-1] in contains:
contains.add(word)
if len(word) > len(ans):
ans = word
return ans | longest-word-in-dictionary | Python easy to read and understand | sanial2001 | 0 | 85 | longest word in dictionary | 720 | 0.518 | Medium | 11,838 |
https://leetcode.com/problems/longest-word-in-dictionary/discuss/1827757/Python-or-Sorting | class Solution:
def longestWord(self, words: List[str]) -> str:
words.sort(key=lambda item:(-len(item),item),reverse=True)
#print(words)
for word in words[::-1]:
tmp=''
for ch in word:
tmp+=ch
if tmp not in words:
break
if tmp==word:
return word
return '' | longest-word-in-dictionary | Python | Sorting | heckt27 | 0 | 32 | longest word in dictionary | 720 | 0.518 | Medium | 11,839 |
https://leetcode.com/problems/longest-word-in-dictionary/discuss/1552208/python3-simple-hash-and-sort-or-64ms-beats-98-or-easy-to-understand | class Solution:
def longestWord(self, words: List[str]) -> str:
words = set(words)
lens = sorted([(w, len(w)) for w in words], key = lambda x: (-x[1], x[0]))
for w, w_len in lens:
nxt = False
for i in range(w_len-1, 0, -1):
if w[:i] not in words:
nxt = True
break
if nxt:
continue
return w
return "" | longest-word-in-dictionary | [python3] simple hash and sort | 64ms beats 98% | easy to understand | kevintancs | 0 | 47 | longest word in dictionary | 720 | 0.518 | Medium | 11,840 |
https://leetcode.com/problems/longest-word-in-dictionary/discuss/1201780/Easy-Python-Solution-Beats-99-runtime | class Solution:
def longestWord(self, words: List[str]) -> str:
# Function which checks whether the given word is present in dictionary or not
def isContain(word, dict1):
temp_str = ''
for i in range(len(word)):
temp_str += word[i]
if temp_str in dict1:
pass
else:
return False
return True
# dictionary for word searching
dict1 = dict()
for word in words:
dict1[word] = 1
# Sort dictionary
words.sort()
# Sort dict by word length. (- is for sorting in reverse)
words.sort(key=lambda x:-len(x))
# Return first word whose sub-parts are in the dictionary
for word in words:
if isContain(word,dict1):
return word | longest-word-in-dictionary | Easy Python Solution, Beats 99% runtime | dakshal33 | 0 | 189 | longest word in dictionary | 720 | 0.518 | Medium | 11,841 |
https://leetcode.com/problems/longest-word-in-dictionary/discuss/694152/Python3-chill-with-sort-beats-98.7 | class Solution:
def longestWord(self, words: List[str]) -> str:
if not words:
return None
seen = {}
w = ""
for i in sorted(words):
if len(i) > 1 and i[:-1] not in seen:
continue
seen[i] = {}
if len(i) > len(w):
w = i
return w | longest-word-in-dictionary | Python3 - chill with sort π beats 98.7% | shankha117 | 0 | 85 | longest word in dictionary | 720 | 0.518 | Medium | 11,842 |
https://leetcode.com/problems/longest-word-in-dictionary/discuss/1220854/Python3-simple-solution-using-sorting | class Solution:
def longestWord(self, words: List[str]) -> str:
words.sort(reverse=True)
words.sort(key=lambda x : len(x))
i = len(words)-1
while i > -1:
flag = True
for j in range(1,len(words[i])):
if words[i][:j] not in words:
flag = False
if flag:
return words[i]
i -= 1
return '' | longest-word-in-dictionary | Python3 simple solution using sorting | EklavyaJoshi | -1 | 83 | longest word in dictionary | 720 | 0.518 | Medium | 11,843 |
https://leetcode.com/problems/accounts-merge/discuss/2014051/Python-easy-to-read-and-understand-or-DFS | class Solution:
def dfs(self, graph, node, visit):
visit.add(node)
for nei in graph[node]:
if nei not in visit:
self.dfs(graph, nei, visit)
self.res.append(node)
def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:
graph = collections.defaultdict(set)
for account in accounts:
for email in account[1:]:
graph[account[1]].add(email)
graph[email].add(account[1])
#print(graph.items())
visit = set()
ans = []
for account in accounts:
name = account[0]
for email in account[1:]:
if email not in visit:
self.res = []
self.dfs(graph, email, visit)
ans.append([name]+sorted(self.res))
return ans | accounts-merge | Python easy to read and understand | DFS | sanial2001 | 7 | 507 | accounts merge | 721 | 0.564 | Medium | 11,844 |
https://leetcode.com/problems/accounts-merge/discuss/286039/My-easy-to-understand-Python3-Union-Find-solution | class Solution:
def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:
def find(x):
if parent[x] != x:
parent[x] = find(parent[x])
return parent[x]
def union(x, y):
rootx = find(x)
rooty = find(y)
if rootx == rooty:
return
if rank[rootx] > rank[rooty]:
parent[rooty] = rootx
elif rank[rooty] > rank[rootx]:
parent[rootx] = rooty
else:
parent[rootx] = rooty
rank[rooty] += 1
parent = list(range(len(accounts)))
rank = [0] * len(accounts)
email_parent = {}
for idx, account in enumerate(accounts):
for email in account[1:]:
if email in email_parent:
union(idx, email_parent[email])
email_parent[email] = idx
ans = {}
for email in email_parent:
root = find(email_parent[email])
if root in ans:
ans[root].append(email)
else:
ans[root] = [accounts[root][0], email]
ans = list(ans.values())
for account in ans:
account[1:] = sorted(account[1:])
return ans | accounts-merge | My easy to understand Python3 Union Find solution | maysonma98 | 5 | 696 | accounts merge | 721 | 0.564 | Medium | 11,845 |
https://leetcode.com/problems/accounts-merge/discuss/1602208/Python3-Union-Find-Explained | class Solution:
def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:
self.p = {i:i for i in range(len(accounts))} # parents
eta = dict() # maps email to account
for i, acc in enumerate(accounts):
for email in acc[1:]:
if email in eta:
self.union(eta[email], i)
continue
eta[email] = i
ate = dict() # maps account to emails
for email in eta:
acc = self.find(eta[email])
if acc in ate:
ate[acc].append(email)
else:
ate[acc] = [email]
res = []
for p in ate: # build the result list
res.append([accounts[p][0]] + sorted(ate[p]))
return res
def union(self, a, b):
self.p[self.find(b)] = self.find(a)
def find(self, res):
while self.p[res] != res:
self.p[res] = self.p[self.p[res]]
res = self.p[res]
return res | accounts-merge | [Python3] Union-Find, Explained | artod | 4 | 313 | accounts merge | 721 | 0.564 | Medium | 11,846 |
https://leetcode.com/problems/accounts-merge/discuss/2543526/Python-DFS-Solution-Intuitive | class Solution:
def __init__(self):
self.accountConnections = defaultdict(set)
self.emailToName = dict()
self.seen = set()
def buildConnections(self, accounts):
for account in accounts:
name = account[0]
key = account[1]
for i in range(1, len(account)):
self.accountConnections[key].add(account[i])
self.accountConnections[account[i]].add(key)
self.emailToName[account[i]] = name
def walkAccountNode(self, accountNode):
if accountNode in self.seen:
return []
self.seen.add(accountNode)
connections = self.accountConnections[accountNode]
result = [accountNode]
for connection in connections:
result += self.walkAccountNode(connection)
return result
def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:
self.buildConnections(accounts)
mergedAccounts = []
for account in self.accountConnections:
localMerge = self.walkAccountNode(account)
name = self.emailToName[account]
if localMerge:
localMerge.sort()
mergedAccounts.append([name] + localMerge)
return mergedAccounts | accounts-merge | Python DFS Solution - Intuitive | EdwinJagger | 1 | 110 | accounts merge | 721 | 0.564 | Medium | 11,847 |
https://leetcode.com/problems/accounts-merge/discuss/1372984/Python-Simple-15-Lines-of-code-using-List-property.-O(M2) | class Solution:
def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:
tagged = {}
for cur_group in accounts:
for mail in cur_group[1:]:
if mail not in tagged:
tagged[mail] = cur_group
orig_group = tagged[mail]
if orig_group is cur_group:
continue
cur_group.extend(orig_group[1:])
for mail in orig_group[1:]:
tagged[mail] = cur_group
orig_group[0] = None
return [[group[0],] + sorted(list(set(group[1:]))) for group in accounts if group[0] is not None] | accounts-merge | [Python] Simple 15 Lines of code using List property. O(M^2) | annieFromTaiwan | 1 | 262 | accounts merge | 721 | 0.564 | Medium | 11,848 |
https://leetcode.com/problems/accounts-merge/discuss/1070360/Python-or-Set-%2B-Dict-or-Easy-to-Understand-or-Iterative-Solution | class Solution:
def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:
users,seen,curr,merged=set(),dict(),0,[]
for a in accounts:
if a[0] not in users:
for email in a[1:]:
seen[email]=curr
curr+=1
merged+=[[a[0]]+list(set(a[1:]))]
users.add(a[0])
else:
found=set()
for email in a[1:]:
if email in seen and seen[email] not in found:
found.add(seen[email])
found=list(found)
if len(found)==1:
merged[found[0]][1:]=list(set(merged[found[0]][1:]+a[1:]))
for email in a[1:]:seen[email]=found[0]
elif len(found)>1:
for i in found[1:]:
merged[found[0]]+=merged[i][1:]
merged[i]=[]
merged[found[0]][1:]=list(set(merged[found[0]][1:]+a[1:]))
for email in merged[found[0]][1:]:
seen[email]=found[0]
else:
for email in a[1:]:
seen[email]=curr
curr+=1
merged+=[[a[0]]+list(set(a[1:]))]
return [[merged[i][0]]+sorted(merged[i][1:]) for i in range(len(merged)) if merged[i]!=[]] | accounts-merge | Python | Set + Dict | Easy to Understand | Iterative Solution | rajatrai1206 | 1 | 311 | accounts merge | 721 | 0.564 | Medium | 11,849 |
https://leetcode.com/problems/accounts-merge/discuss/2814677/Python3-Union-Find-Solution | class Solution:
def find(self, email: str, parent) -> str:
if email != parent[email]:
parent[email] = self.find(parent[email], parent)
return parent[email]
def union(self, email1: str, email2: str, parent) -> None:
if email1 not in parent:
parent[email1] = email2
else:
self.find(email2, parent)
parent[parent[email2]] = self.find(email1, parent)
# O(nlogn) time, n -> number of emails
# O(n) space,
# Approach: Union find, dfs
def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:
owner = {}
parent = {}
children = defaultdict(list)
merged_accounts = []
for account in accounts:
# account = acc.split(',')
# print(account)
name = account[0]
root = account[1]
owner[root] = name
for i in range(1, len(account)):
self.union(account[i], root, parent)
for email in parent:
self.find(email, parent)
children[parent[email]].append(email)
for p in children:
merged_account = []
merged_account.append(owner[p])
children[p].sort()
for child in children[p]:
merged_account.append(child)
merged_accounts.append(merged_account)
# print(parent)
return merged_accounts | accounts-merge | Python3 Union Find Solution | destifo | 0 | 5 | accounts merge | 721 | 0.564 | Medium | 11,850 |
https://leetcode.com/problems/accounts-merge/discuss/2786504/python-dfs-approach | class Solution:
def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:
# T : N = number of accounts
# K = max number of emails per user
# O(N*K) * O(N * log(k)) => sorting purpose
# therefore final time complexity is O(N * K * (N * log(K)))
# S : O(NK)
# DFS approach
graph = collections.defaultdict(set)
email_to_name = {}
# fill graph connections
for account in accounts:
name = account[0]
for email in account[1:]:
graph[email].add(account[1])
graph[account[1]].add(email)
email_to_name[email] = name
# dfs appraoch
res = []
visited = set()
for email in graph:
if email not in visited:
stack = [email]
visited.add(email)
local_res = []
while stack:
node = stack.pop()
local_res.append(node)
for edge in graph[node]:
if edge not in visited:
stack.append(edge)
visited.add(edge)
res.append([email_to_name[email]] + sorted(local_res))
return res | accounts-merge | python dfs approach | sahilkumar158 | 0 | 7 | accounts merge | 721 | 0.564 | Medium | 11,851 |
https://leetcode.com/problems/accounts-merge/discuss/2750190/Intuitive-construction-of-adjacent-graph-and-basic-dfs | class Solution:
def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:
#create a adjacent lists that have connections
dic = collections.defaultdict(set)
email_to_name={}
visited = set()
ans = []
for account in accounts:
name = account[0]
for email in account[1:]:
dic[email].add(account[1])
dic[account[1]].add(email)
email_to_name[email] = name
def dfs(intial_email,dic,visited):
if intial_email in visited:
return
stack = [intial_email]
visited.add(intial_email)
lst = []
lst.append(intial_email)
while stack:
sub_email = stack.pop()
if dic[sub_email]:
for other_email in dic[sub_email]:
if other_email not in visited:
lst.append(other_email)
stack.append(other_email)
visited.add(other_email)
else:
continue
result = sorted(lst)
return result
for email in dic:
result = dfs(email,dic,visited)
if result:
ans.append([email_to_name[email]]+result)
return ans
# dic_emails = {}
# for account in accounts:
# for i in range(1,len(account)):
# if account[i] not in dic_emails:
# dic_emails[account[i]] =1
# else:
# dic_emails[account[i]] +=1
# dic_email2 = {}
# dic_email3 = []
# for key,value in dic_emails.items():
# if value > 1:
# for account in accounts:
# if key in account and key not in dic_email2:
# dic_email2[key] = []
# dic_email2[key].append(account)
# elif key in account and key in dic_email2:
# dic_email2[key].append(account)
# elif key not in account:
# dic_email3.append(account)
# total = []
# for key,value in dic_email2.items():
# lst = []
# if len(value) > 1:
# for infor in value:
# for in_f in infor:
# if in_f not in lst:
# lst.append(in_f)
# total.append(lst[:1]+sorted(lst[1:]))
# print(total)
# print(dic_email3)
# return sorted((total + dic_email3)) | accounts-merge | Intuitive construction of adjacent graph and basic dfs | fellowshiptech | 0 | 3 | accounts merge | 721 | 0.564 | Medium | 11,852 |
https://leetcode.com/problems/accounts-merge/discuss/2158901/Connected-Components-oror-DFS-oror-Fastest-Optimal-Solution-oror-Easy-to-Understand | class Solution:
# This dfs function will return the components for each node.
def dfs(self, comp, idx, visited, graph, mailsList):
visited[idx] = True
comp.append(mailsList[idx])
for neighbour in graph[mailsList[idx]]:
neighbourIdx = mailsList.index(neighbour)
if visited[neighbourIdx] == False:
comp = self.dfs(comp, neighbourIdx, visited, graph, mailsList)
return comp
def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:
# Initializing the graph
graph = {}
# A list for storing all mail ids, it will be used for performing dfs.
mailsList = []
# Storing the mails as key and empty list as values in the graph.
for account in accounts:
mails = account[1:]
mailsList.extend(mails)
for mail in mails:
graph[mail] = []
# For getting distinct mail ids.
mailsList = list(set(mailsList))
mailsListLength = len(mailsList)
connectedComponents = []
# Creating the graph by connecting mails.
for account in accounts:
mails = account[1:]
for mail in mails:
graph[mails[0]].append(mail)
graph[mail].append(mails[0])
# This list will be used for keeping the track of visited mail ids.
visited = [False]*(mailsListLength)
# Calling dfs for each mail id.
for i in range(mailsListLength):
if len(graph[mailsList[i]]) > 0 and visited[i] is False:
component = []
connectedComponents.append(self.dfs(component, i, visited, graph, mailsList))
# If a node has no neighbours then it is treated as a seprate component.
elif len(graph[mailsList[i]]) == 0:
connectedComponents.append([mailsList[i]])
# Sorting all the components obtained.
for component in connectedComponents:
if len(component) > 1:
component.sort()
# Inserting the names of accounts in each component
for component in connectedComponents:
for account in accounts:
if component[0] in account:
component.insert(0, account[0])
break
return connectedComponents | accounts-merge | Connected Components || DFS || Fastest Optimal Solution || Easy to Understand | Vaibhav7860 | 0 | 86 | accounts merge | 721 | 0.564 | Medium | 11,853 |
https://leetcode.com/problems/accounts-merge/discuss/1817838/A-DFS-approach-not-the-best-but-want-to-share-just-step-by-step | class Solution:
def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:
hashmap={}
for i in range(len(accounts)):
for j in range(1,len(accounts[i])):
if accounts[i][j] not in hashmap:
hashmap[accounts[i][j]] = accounts[i]
else:
hashmap[accounts[i][j]] += accounts[i][1:]
visited={}
res=[]
def dfs(email, index):
if not email:
index += 1
return
if email not in visited:
visited[email] = True
currentlist = hashmap[email]
if index > len(res)-1:
res.append([currentlist[0]])
res[index].append(email)
else:
res[index].append(email)
for i in range(1,len(currentlist)):
dfs(currentlist[i], index)
return
index=-1
for key in hashmap.keys():
if key not in visited:
index += 1
dfs(key, index)
for i in range(len(res)):
name = [res[i][0]]
emails = res[i][1:]
emails.sort()
new = name + emails
res[i] = new
return res | accounts-merge | A DFS approach, not the best but want to share, just step by step | Sunshinelalala | 0 | 93 | accounts merge | 721 | 0.564 | Medium | 11,854 |
https://leetcode.com/problems/accounts-merge/discuss/1602882/Union-find-solution-faster-than-94.83 | class Solution:
def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:
rank = list(range(len(accounts)))
def find(x):
if rank[x] == x:
return x
rank[x] = find(rank[x])
return rank[x]
mails = {} # mail : account_id
for i in range(len(accounts)):
for mail in accounts[i][1:]:
if mail in mails:
r = find(mails[mail])
if find(i) < r:
rank[r] = find(i)
else:
rank[find(i)] = r
else:
mails[mail] = i
for i in range(len(accounts)):
if find(i) != i:
accounts[find(i)].extend(accounts[i][1:])
return [accounts[i][0:1] + list(sorted(set(accounts[i][1:]))) for i in range(len(accounts)) if rank[i] == i] | accounts-merge | Union find solution, faster than 94.83% | timetoai | 0 | 95 | accounts merge | 721 | 0.564 | Medium | 11,855 |
https://leetcode.com/problems/accounts-merge/discuss/979002/Python-Iterative-Solution | class Solution:
def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:
email_to_ids = collections.defaultdict(list)
visited_accounts = [False]*len(accounts)
for i, acct in enumerate(accounts):
for email in acct[1:]:
email_to_ids[email].append(i)
res = []
for id, acct in enumerate(accounts):
if visited_accounts[id]:
continue
visited_accounts[id] = True
merged_emails = set()
stack = acct[1:]
while stack:
email = stack.pop()
merged_emails.add(email)
for id in email_to_ids[email]:
if not visited_accounts[id]:
stack.extend([new_email for new_email in accounts[id][1:] if new_email != email])
visited_accounts[id] = True
res.append([acct[0]] + sorted(merged_emails))
return res | accounts-merge | Python Iterative Solution | cj1989 | 0 | 212 | accounts merge | 721 | 0.564 | Medium | 11,856 |
https://leetcode.com/problems/remove-comments/discuss/2446606/Easy-to-understand-using-Python | class Solution:
def removeComments(self, source: List[str]) -> List[str]:
ans, inComment = [], False
new_str = ""
for c in source:
if not inComment: new_str = ""
i, n = 0, len(c)
# inComment, we find */
while i < n:
if inComment:
if c[i:i + 2] == '*/' and i + 1 < n:
i += 2
inComment = False
continue
i += 1
# not in Comment, we find /* // and common character
else:
if c[i:i + 2] == '/*' and i + 1 < n:
i += 2
inComment = True
continue
if c[i:i + 2] == '//' and i + 1 < n:
break
new_str += c[i]
i += 1
if new_str and not inComment:
ans.append(new_str)
return ans | remove-comments | Easy to understand using Python | fguo10 | 3 | 567 | remove comments | 722 | 0.38 | Medium | 11,857 |
https://leetcode.com/problems/remove-comments/discuss/1457370/Python3-1-pass | class Solution:
def removeComments(self, source: List[str]) -> List[str]:
ans = []
comment = False # True for block comment
for line in source:
if not comment: ans.append([]) # if not started as comment
i = 0
while i < len(line):
if comment:
if line[i:i+2] == "*/":
comment = False
i += 1
else:
if line[i:i+2] == "//": break
elif line[i:i+2] == "/*":
comment = True
i += 1
else: ans[-1].append(line[i])
i += 1
return filter(None, map("".join, ans)) | remove-comments | [Python3] 1-pass | ye15 | 1 | 241 | remove comments | 722 | 0.38 | Medium | 11,858 |
https://leetcode.com/problems/remove-comments/discuss/1395358/99.77-faster-Python-solution-easy-understand | class Solution:
def removeComments(self, source):
#decide the order for processing, return True if need to first process '//'
def who_first(line, commenting):
atype, btype, ctype = line.find('//'), line.find('/*'), line.find('*/')
if atype != -1 and ctype != -1 and commenting:
if commenting and ctype > atype:
return False
else: return ctype > atype
elif atype != -1 and btype != -1:
return btype > atype
return atype != -1
commenting, outputs, remained = False, [], ''
for line in source:
output = []
while True: #only execute one time in most cases
#processing '//'
if line.find('//') != -1 and who_first(line, commenting):
line = line[:line.find('//')]
if len(line) > 0: output.append(line)
#processing '/*'
if not commenting and line.find('/*') != -1:
remained, line, commenting = line[:line.find('/*')], line[line.find('/*')+2:], True
#processing '*/', call the main body again if there are some remainings comments in this line
if commenting and line.find('*/') != -1:
line = line[line.find('*/')+2:]
line, remained, commenting =remained + line, '', False
#processing unfinished comments
if line.find('//')!=-1 or line.find('/*')!=-1 or line.find('*/')!=-1: continue
if len(line) > 0: output.append(line)
break
if len(output) > 0: outputs.append(''.join(output)) #lines with comments removed
elif not commenting and len(line) > 0: outputs.append(line) #normal lines
return outputs | remove-comments | 99.77% faster Python solution, easy understand | bob23 | 1 | 464 | remove comments | 722 | 0.38 | Medium | 11,859 |
https://leetcode.com/problems/remove-comments/discuss/981251/Python-one-pass-with-explanation | class Solution:
def removeComments(self, source: List[str]) -> List[str]:
'''
is_block shows if we're in a block comment or not
Iterate over current line and detect line comments or start/end of block comments.
End line early for a line comment, update is_block for block start/end and continue
Only create new res_line if we reach the end of a line and is_block is false.
This accounts for test cases like ["a/*comment", "line", "more_comment*/b"] -> ["ab"].
'''
# define vars
is_block = False
res_line = []
result = []
# iterate over lines
for source_line in source:
# iterate over characters in line, look ahead for comment denoters
i = 0
while i < len(source_line):
char = source_line[i]
# is this the start of a line comment?
if not is_block and source_line[i:i+2] == '//':
i = len(source_line) # skip to end
# is this the start of a block comment?
elif not is_block and source_line[i:i+2] == '/*':
is_block = True
i += 2
# is this the end of a block comment?
elif is_block and source_line[i:i+2] == '*/':
is_block = False
i += 2
# we're in a block comment, skip the char
elif is_block:
i += 1
# we can add the char
else:
res_line.append(char)
i += 1
# if not is_block, add to result and reset, filter empty lines
if res_line and not is_block:
result.append(''.join(res_line))
res_line = []
return result | remove-comments | Python one-pass with explanation | gins1 | 1 | 395 | remove comments | 722 | 0.38 | Medium | 11,860 |
https://leetcode.com/problems/remove-comments/discuss/2351084/Python3-One-pass-with-guard-clauses-Explained-no-regex-just-bools | class Solution(object):
def removeComments(self, source):
"""
:type source: List[str]
:rtype: List[str]
"""
# initialize some variables to save lines and valid characters
result = []
current_line = ""
# initialize some state variables
in_block = False
in_line = False
skip_next = False
for line in source:
# in a new line we will never skip the first character
skip_next = False
# a new line can never be part of an inline comment
in_line = False
for index, character in enumerate(line):
# ----------------------------------------------------------------
# Guard clauses that will always skip the character, if we are in
# a comment or notified the loop to skip the next
# -----------------------------------------------------------------
# guard clause whether we want to skip the current character
if skip_next:
# reset the boolean in case we skip
skip_next = False
continue
# guard clause whether we are in an in line comment
# this comment can only be ended by a new line so we do not need
# to check the current character
if in_line:
continue
# guard clause whether we are in a block comment
if in_block:
# since the block comment can be ended, we need to check whether we find
# our ending symbol
# line[index:index+2] slicing works also at the end of a line
# (even if index+2 is out of scope)
if line[index:index+2] == '*/':
# in case we found the end of the block comment we switch the bool to false
# and we need to skip the next character
# Our current character (line[index]) is '*' and the next is '/' which we skip
in_block = False
skip_next = True
continue
else:
# we are still in block comment and therefore can continue
continue
# ----------------------------------------------------------------
# After all guard clauses passed, we are not in a comment and
# we need to check the current character whether it starts one
# -----------------------------------------------------------------
# check whether block comment begins
# slicing of list works even if index+2 is out of scope
if line[index:index+2] == '/*':
# switch the comment boolean and
# tell our loop we need to skip the next character
# since it will be a '*'
in_block = True
skip_next = True
continue
# check whether in line comment starts
# slicing works also at end of line
if line[index:index+2] == '//':
# we switch the boolean and skip the next character as it will be
# '/'
in_line = True
skip_next = True
continue
# ----------------------------------------------------------------
# Now that all checks have passed we found
# a character that is part of the code
# -----------------------------------------------------------------
# append our character to the current line
current_line += character
# we will append the current line to our result (finalize a line in the output)
# a) if we are not in a block comment that hasn't ended
# b) and the current line has characters in it
if not in_block and current_line:
# append the line and reset the current line
result.append(current_line)
current_line = ""
return result | remove-comments | Python3 - One pass with guard clauses - Explained - no regex just bools | Lucew | 0 | 93 | remove comments | 722 | 0.38 | Medium | 11,861 |
https://leetcode.com/problems/remove-comments/discuss/2351084/Python3-One-pass-with-guard-clauses-Explained-no-regex-just-bools | class Solution(object):
def removeComments(self, source):
result = []
current_line = ""
in_block = False
in_line = False
skip_next = False
for line in source:
skip_next = False
in_line = False
for index, character in enumerate(line):
if skip_next:
skip_next = False
continue
if in_line:
continue
if in_block:
if line[index:index+2] == '*/':
in_block = False
skip_next = True
continue
else:
continue
if line[index:index+2] == '/*':
in_block = True
skip_next = True
continue
if line[index:index+2] == '//':
in_line = True
skip_next = True
continue
current_line += character
if not in_block and current_line:
result.append(current_line)
current_line = ""
return result | remove-comments | Python3 - One pass with guard clauses - Explained - no regex just bools | Lucew | 0 | 93 | remove comments | 722 | 0.38 | Medium | 11,862 |
https://leetcode.com/problems/remove-comments/discuss/1451235/Python-one-pass-readable-code-with-comments | class Solution:
def removeComments(self, source: List[str]) -> List[str]:
result = []
SINGLE_LINE_COMMENT = '//'
MULTI_LINE_COMMENT_START = '/*'
MULTI_LINE_COMMENT_END = '*/'
is_multi_line_comment = False # this is to check if the current symbol withing multiline comment
CONTINUATION = '#'
for line in source:
code = []
i = 0
while i< len(line):
# we've got //, stop
if line[i:i+2] == SINGLE_LINE_COMMENT and not is_multi_line_comment:
break
# the multiline comment started
elif line[i:i+2] == MULTI_LINE_COMMENT_START and not is_multi_line_comment:
is_multi_line_comment=True
code.append(CONTINUATION) # append this special char, use it to join multiline comments
i+=1
elif line[i:i+2] == MULTI_LINE_COMMENT_END and is_multi_line_comment:
# if start and end of multiline comment are on the same line, extract special char
if code and code[-1] == CONTINUATION:
code.pop()
is_multi_line_comment = False
i+=1
elif not is_multi_line_comment: # add char if it is not in the multiline comment
code.append(line[i])
i+=1
# check if we want to join the collected code of the current line the to the code on the last line
if result and result[-1][-1] == CONTINUATION and not is_multi_line_comment:
last_line = result.pop()[:-1] + ''.join(code)
if last_line:
result.append(last_line)
else: # otherwise, just add new line of code
if code:
result.append(''.join(code))
return result | remove-comments | Python, one pass, readable code with comments | arsamigullin | 0 | 279 | remove comments | 722 | 0.38 | Medium | 11,863 |
https://leetcode.com/problems/remove-comments/discuss/1421637/Regex-solution | class Solution:
pat1 = re.compile(r"//[^~]*~")
pat2 = re.compile(r"/\*.*?\*/")
def removeComments(self, source: List[str]) -> List[str]:
one_line = "~".join(source) + "~"
idx_pat1 = one_line.find("//")
idx_pat2 = one_line.find("/*")
while -1 < idx_pat1 or -1 < idx_pat2:
if -1 < idx_pat1 and -1 < idx_pat2:
if idx_pat1 < idx_pat2:
one_line = Solution.pat1.sub("~", one_line, 1)
else:
one_line = Solution.pat2.sub("", one_line, 1)
elif -1 < idx_pat1:
one_line = Solution.pat1.sub("~", one_line, 1)
else:
one_line = Solution.pat2.sub("", one_line, 1)
idx_pat1 = one_line.find("//")
idx_pat2 = one_line.find("/*")
return [line for line in one_line.split("~") if line] | remove-comments | Regex solution | EvgenySH | 0 | 173 | remove comments | 722 | 0.38 | Medium | 11,864 |
https://leetcode.com/problems/find-pivot-index/discuss/2321669/Python-99.85-faster-or-Simplest-solution-with-explanation-or-Beg-to-Adv-or-Prefix-Sum | class Solution:
def findMiddleIndex(self, nums: List[int]) -> int:
left = 0 # nums[0] + nums[1] + ... + nums[middleIndex-1]
right = sum(nums) # nums[middleIndex+1] + nums[middleIndex+2] + ... + nums[nums.length-1]
for i, num in enumerate(nums): # we can use normal for loop as well.
right -= num # as we are trying to find out pivot index so iteratively we`ll reduce the value of right to find the pivot index
if left == right: # comparing the values for finding out the pivot index.
return i # if there is any return the index whixh will be our required index.
left += num # we have to add the num iteratively.
return -1 | find-pivot-index | Python 99.85% faster | Simplest solution with explanation | Beg to Adv | Prefix Sum | rlakshay14 | 9 | 725 | find pivot index | 724 | 0.535 | Easy | 11,865 |
https://leetcode.com/problems/find-pivot-index/discuss/1905287/My-easiest-to-understand-solution-that-beats-92-python-solutions. | class Solution:
def pivotIndex(self, nums: List[int]) -> int:
s1,s2=0,sum(nums)
for i in range(len(nums)):
s2-=nums[i]
if s1==s2:
return i
s1+=nums[i]
return -1 | find-pivot-index | My easiest to understand solution that beats 92% python solutions. | tkdhimanshusingh | 8 | 393 | find pivot index | 724 | 0.535 | Easy | 11,866 |
https://leetcode.com/problems/find-pivot-index/discuss/2233492/Python3-Solution-with-using-prefix-sum | class Solution:
def pivotIndex(self, nums: List[int]) -> int:
right_sum = sum(nums)
left_sum = 0
for i in range(len(nums)):
right_sum -= nums[i]
if left_sum == right_sum:
return i
left_sum += nums[i]
return -1 | find-pivot-index | [Python3] Solution with using prefix sum | maosipov11 | 5 | 220 | find pivot index | 724 | 0.535 | Easy | 11,867 |
https://leetcode.com/problems/find-pivot-index/discuss/2303414/Python-solution-with-explanation | class Solution:
def pivotIndex(self, nums: List[int]) -> int:
# We'll assume the right sum as sum of all the elements in the list.
right_sum = sum(nums)
# We'll assume the left sum as 0.
left_sum = 0
# Now we'll iterate in the whole list
for i in range(len(nums)):
# We'll decrease the current value of the element from the right sum
right_sum = right_sum-nums[i]
# Now we'll check if left sum is equal to the right sum
if(left_sum==right_sum):
# If they both are equal then that means this is the pivot index and we've to return the value of i or the index value
return i
# If not then we'll add the current value of the element to the left sum and again go in the loop.
left_sum = left_sum+nums[i]
# If the loop is over and till now none of the condition is satisfied then we'll return -1.
return -1 | find-pivot-index | Python solution with explanation | yashkumarjha | 2 | 227 | find pivot index | 724 | 0.535 | Easy | 11,868 |
https://leetcode.com/problems/find-pivot-index/discuss/2165091/Python-or-Two-easy-solution-space-optimized | class Solution:
def pivotIndex(self, nums: List[int]) -> int:
# ///// Solution 2 space optimized TC: O(N) and SC: O(1) ///////
leftSum = 0
rightSum = sum(nums)
for i in range(len(nums)):
leftSum += nums[i]
if leftSum == rightSum:
return i
rightSum -= nums[i]
return -1
# ///// Solution 1 using extra space TC: O(N) and SC: O(N) ///////
cumulativeSum = 0
cumulativeSumArr = []
for num in nums:
cumulativeSum += num
cumulativeSumArr.append(cumulativeSum)
leftSum = rightSum = 0
if len(nums) == 1:
return 0
# if len(nums) == 2:
# return -1
for i in range(len(nums)):
leftSum = cumulativeSumArr[i] - nums[i]
rightSum = cumulativeSumArr[-1] - cumulativeSumArr[i]
if leftSum == rightSum:
return i
return -1 | find-pivot-index | Python | Two easy solution space optimized | __Asrar | 2 | 185 | find pivot index | 724 | 0.535 | Easy | 11,869 |
https://leetcode.com/problems/find-pivot-index/discuss/1508815/Simple-or-Python-3-or-140-ms-faster-than-96.15 | class Solution:
def pivotIndex(self, nums: List[int]) -> int:
l_sum = 0
r_sum = sum(nums)
for index, num in enumerate(nums):
l_sum += num
r_sum -= num
if l_sum - num == r_sum:
return index
return -1 | find-pivot-index | Simple | Python 3 | 140 ms, faster than 96.15% | deep765 | 2 | 264 | find pivot index | 724 | 0.535 | Easy | 11,870 |
https://leetcode.com/problems/find-pivot-index/discuss/785434/Three-Liner-Python-Solution | class Solution(object):
def pivotIndex(self, nums):
for i in range(len(nums)):
if sum(nums[:i:])==sum(nums[i+1::]):return i
return -1 | find-pivot-index | Three Liner Python Solution | rachitsxn292 | 2 | 371 | find pivot index | 724 | 0.535 | Easy | 11,871 |
https://leetcode.com/problems/find-pivot-index/discuss/2277128/Python3-O(N)-time-and-O(1)-space | class Solution:
def pivotIndex(self, nums: List[int]) -> int:
length = len(nums)
for i in range(1,length):
nums[i] += nums[i-1]
def isPivot(index):
if index == 0:
return nums[-1] - nums[index] == 0
if index == length - 1:
return nums[index - 1] == 0
return nums[index - 1] == nums[-1] - nums[index]
for i in range(length):
if isPivot(i):
return i
return -1 | find-pivot-index | π Python3 O(N) time and O(1) space | Dark_wolf_jss | 1 | 93 | find pivot index | 724 | 0.535 | Easy | 11,872 |
https://leetcode.com/problems/find-pivot-index/discuss/2170806/Python-oror-O(1)-Space | class Solution:
def pivotIndex(self, nums: List[int]) -> int:
n=len(nums)
if n==1:
return nums[0]
left=0
array_sum=sum(nums)
#If 0th index is Pivot
if array_sum-nums[0]==0:
return 0
for i in range(1,n):
left+=nums[i-1]
right=array_sum-left-nums[i]
if left==right:
return i
return -1 | find-pivot-index | Python || O(1) Space | aksgupta98 | 1 | 84 | find pivot index | 724 | 0.535 | Easy | 11,873 |
https://leetcode.com/problems/find-pivot-index/discuss/2094476/Python3-O(n)ororO(1)-Runtime%3A-153ms-90.08 | class Solution:
def pivotIndex(self, nums: List[int]) -> int:
return self.findPivotIndexOptimal(nums)
# O(n) || O(1)
# runtime: 153ms 90.08%
def findPivotIndexOptimal(self, nums):
if not nums:
return nums
leftSum = 0
totalSum = sum(nums)
for i in range(len(nums)):
diff = totalSum - nums[i] - leftSum
if diff == leftSum:
return i
leftSum += nums[i]
return -1
# O(n^3) or O(n^4) || O(1) : TLE
def findPivotBruteForce(self, array):
if not array: return array
for i in range(len(array)): # O(n)
for j in range(i + 1, len(array)): #O(n)
if sum(array[:i]) == sum(array[i + 1:]): #sum is O(n) operation O(n^2)
return i
return -1 | find-pivot-index | Python3 O(n)||O(1) Runtime: 153ms 90.08% | arshergon | 1 | 90 | find pivot index | 724 | 0.535 | Easy | 11,874 |
https://leetcode.com/problems/find-pivot-index/discuss/1508276/short-python-O(n)-time-Clean-Code | class Solution:
def pivotIndex(self, nums: List[int]) -> int:
s=sum(nums)
l=len(nums)
res=[]
st=0
for i in range(0,l-1):
st=st+nums[i]
if st==(s-nums[i+1])/2:
res.append(i+1)
if sum(nums[1:])==0: res.append(0)
if sum(nums[:-1])==0: res.append(len(nums)-1)
if len(res)>0: return min(res)
return -1 | find-pivot-index | short python O(n) time Clean Code | srikarakkina | 1 | 131 | find pivot index | 724 | 0.535 | Easy | 11,875 |
https://leetcode.com/problems/find-pivot-index/discuss/1502069/Python-solution-with-one-hash-map | class Solution:
def pivotIndex(self, nums: List[int]) -> int:
right_sums = {}
current_sum = 0
for i in range(len(nums) - 1, -1, -1):
right_sums[i] = current_sum
current_sum += nums[i]
current_sum = 0
for i in range(len(nums)):
if current_sum == right_sums[i]:
return i
current_sum += nums[i]
return -1 | find-pivot-index | Python solution with one hash map | prnvshrn | 1 | 78 | find pivot index | 724 | 0.535 | Easy | 11,876 |
https://leetcode.com/problems/find-pivot-index/discuss/1355141/Python-Solution | class Solution:
def pivotIndex(self, nums: List[int]) -> int:
nums_sum = sum(nums)
n = len(nums)
left_sum, right_sum = 0, nums_sum
for i in range(n):
right_sum -= nums[i]
if left_sum == right_sum:
return i
left_sum += nums[i]
return -1 | find-pivot-index | Python Solution | mariandanaila01 | 1 | 185 | find pivot index | 724 | 0.535 | Easy | 11,877 |
https://leetcode.com/problems/find-pivot-index/discuss/1173032/simple-to-understand-python | class Solution(object):
def pivotIndex(self, nums):
sumL = 0
sumR = sum(nums)
for i in range(len(nums)):
sumR -= nums[i]
if sumL == sumR:
return i
sumL += nums[i]
return -1 | find-pivot-index | simple to understand python | pheobhe | 1 | 89 | find pivot index | 724 | 0.535 | Easy | 11,878 |
https://leetcode.com/problems/find-pivot-index/discuss/452281/efficient-as-well-as-easy-to-understand-beats-94-in-run-time-and-100-in-memory. | class Solution:
def pivotIndex(self, nums: List[int]) -> int:
"""Easy to understand """
piv = -1
sum_after_i= sum(nums)
sum_before_i = 0
if len(nums) not in [0,1]:
for i in range(len(nums)):
sum_after_i -=nums[i] #sum of numbers after i'th iteration
if sum_before_i == sum_after_i:
piv = i
break
sum_before_i += nums[i] ##sum of numbers till i'th iteration(for i+1 )
return piv
else:return piv | find-pivot-index | efficient as well as easy to understand, beats 94% in run time and 100% in memory. | sudhirkumarshahu80 | 1 | 341 | find pivot index | 724 | 0.535 | Easy | 11,879 |
https://leetcode.com/problems/find-pivot-index/discuss/2844117/Python-using-while-Loop | class Solution:
def pivotIndex(self, nums: List[int]) -> int:
n = len(nums)
nums.append(0)
pivot, left, right = 0, 0, sum(nums[1:])
while(pivot < n):
if(left == right):
return pivot
else:
left += nums[pivot]
right -= nums[pivot + 1]
pivot += 1
return -1 | find-pivot-index | Python using while Loop | esdark | 0 | 1 | find pivot index | 724 | 0.535 | Easy | 11,880 |
https://leetcode.com/problems/find-pivot-index/discuss/2844109/Find-pivot-index | class Solution:
def pivotIndex(self, nums: List[int]) -> int:
left_sum=0
total=sum(nums)
for index in range(len(nums)):
right_sum= total-nums[index]-left_sum
if left_sum==right_sum:
return index
left_sum+=nums[index]
return -1 | find-pivot-index | Find pivot index | sid_1603_ | 0 | 1 | find pivot index | 724 | 0.535 | Easy | 11,881 |
https://leetcode.com/problems/find-pivot-index/discuss/2841759/My-first-solutions-no-hate-please | class Solution:
def pivotIndex(self, nums: List[int]) -> int:
length = len(nums)
for i in range(length):
s = 0
s = sum(nums[0:i])
if s == sum(nums[i+1:length]):
return i
return -1 | find-pivot-index | My first solutions, no hate please | Slangeredet | 0 | 3 | find pivot index | 724 | 0.535 | Easy | 11,882 |
https://leetcode.com/problems/find-pivot-index/discuss/2835013/pivot-index | class Solution:
def pivotIndex(self, nums: List[int]) -> int:
for i in range(len(nums)):
if sum(nums[:i]) == sum(nums[i + 1:]):
return i
return -1 | find-pivot-index | pivot index | arthur54342 | 0 | 3 | find pivot index | 724 | 0.535 | Easy | 11,883 |
https://leetcode.com/problems/find-pivot-index/discuss/2835013/pivot-index | class Solution:
def pivotIndex(self, nums: List[int]) -> int:
right_sum = sum(nums)
left_sum = 0
prev_item = 0
for i, item in enumerate(nums):
if i > 0:
left_sum += prev_item
right_sum -= item
if left_sum == right_sum:
return i
prev_item = item
return -1 | find-pivot-index | pivot index | arthur54342 | 0 | 3 | find pivot index | 724 | 0.535 | Easy | 11,884 |
https://leetcode.com/problems/find-pivot-index/discuss/2828632/Python-with-explanation | class Solution:
def pivotIndex(self, nums: List[int]) -> int:
## below for auto-compute
total = sum(nums) #O(n)
## below for 1st var for auto-compute & criteria
leftSum = 0 #to compute the left sum
## loop through whole array
for i in range(len(nums)):
rightSum = total - leftSum - nums[i]
if leftSum == rightSum:
return i
leftSum += nums[i]
return -1 | find-pivot-index | Python with explanation | neon_pegasus | 0 | 10 | find pivot index | 724 | 0.535 | Easy | 11,885 |
https://leetcode.com/problems/find-pivot-index/discuss/2828023/Python-Keep-sliding-pivot-point-adding-to-left-taking-from-right | class Solution:
def pivotIndex(self, nums: List[int]) -> int:
pivot, left, right = 0, 0, sum(nums) - nums[0]
while pivot < len(nums):
# base case - if left and right of current index is equivalent
if left == right:
return pivot
# otherwise, move the pivot right-bound
# so take current num, add it to left
# and take next num, take if away from the right
# and move pivot to the taken num position
left += nums[pivot]
# but return -1 if we've reached the end and not yet found a match
if pivot + 1 == len(nums):
return -1
right -= nums[pivot+1]
pivot += 1 | find-pivot-index | [Python] Keep sliding pivot point, adding to left, taking from right | graceiscoding | 0 | 5 | find pivot index | 724 | 0.535 | Easy | 11,886 |
https://leetcode.com/problems/find-pivot-index/discuss/2819287/Python-code | class Solution:
def pivotIndex(self, nums: List[int]) -> int:
i=0
j=len(nums)
firstpart=[]
secondpart=[]
firstpart = nums[:j-1]
secondpart = nums[1:]
if(sum(secondpart)==0 ):
return 0
while(i<len(nums)-1):
if(sum(nums[i+2:])==sum(nums[:i+1])):
return i+1
i+=1
#j-=1
return -1 | find-pivot-index | Python code | saisupriyavaru | 0 | 5 | find pivot index | 724 | 0.535 | Easy | 11,887 |
https://leetcode.com/problems/find-pivot-index/discuss/2819026/Python-My-O(n)-Solution | class Solution:
def pivotIndex(self, nums: List[int]) -> int:
# build right sum list - O(n)
right_sum_list_inverse = [0]
for i in range(len(nums)-1, 0, -1):
right_sum_list_inverse.append(right_sum_list_inverse[-1]+nums[i])
# compare each left sum with right sum list - O(n)
left_sum = 0
for i, num in enumerate(nums):
right_sum = right_sum_list_inverse[len(nums)-1-i]
if left_sum == right_sum:
return i
left_sum += num
return -1 | find-pivot-index | [Python] My O(n) Solution | manytenks | 0 | 7 | find pivot index | 724 | 0.535 | Easy | 11,888 |
https://leetcode.com/problems/find-pivot-index/discuss/2816359/Simplest-solution | class Solution:
def pivotIndex(self, nums: List[int]) -> int:
sr=0
for i in range(0,len(nums)):
sr=sr+nums[i]
sl=0
for i in range (0,len(nums)):
sr=sr-nums[i]
if (sl==sr):
return i
sl=sl+nums[i]
return -1 | find-pivot-index | Simplest solution | pratyushjain99 | 0 | 5 | find pivot index | 724 | 0.535 | Easy | 11,889 |
https://leetcode.com/problems/find-pivot-index/discuss/2814386/Python-easy-solution-Sliding-window-approach | class Solution:
def pivotIndex(self, nums: List[int]) -> int:
left = 0
right = sum(nums[1:])
for i in range(len(nums)):
if left==right:
return i
left=left+nums[i]
if i+1 == len(nums):
right=0
else:
right=right-nums[i+1]
return -1 | find-pivot-index | Python easy solution Sliding window approach | ankansharma1998 | 0 | 8 | find pivot index | 724 | 0.535 | Easy | 11,890 |
https://leetcode.com/problems/find-pivot-index/discuss/2814027/My-Solution | class Solution:
def pivotIndex(self, nums: List[int]) -> int:
rightSum = sum(nums) - nums[0]
leftSum = 0
if leftSum == rightSum: return 0
for i in range(1, len(nums)):
leftSum += nums[i-1]
rightSum -= nums[i]
if leftSum == rightSum: return i
return -1 | find-pivot-index | My Solution | phuocnguyenquang34 | 0 | 4 | find pivot index | 724 | 0.535 | Easy | 11,891 |
https://leetcode.com/problems/find-pivot-index/discuss/2811631/recursive-sol | class Solution:
def pivotIndex(self, nums: List[int]) -> int:
left = 0
right = sum(nums)
for i in range(0,len(nums)):
right -= nums[i]
if left == right:
return i
left += nums[i]
return -1 | find-pivot-index | recursive sol | roger880327 | 0 | 4 | find pivot index | 724 | 0.535 | Easy | 11,892 |
https://leetcode.com/problems/find-pivot-index/discuss/2810362/Python3-368-ms-28 | class Solution:
def pivotIndex(self, nums: List[int]) -> int:
left_sum = 0
right_sum = sum(nums)
for i, val in enumerate(nums):
if left_sum == right_sum - val:
return i
left_sum += val
right_sum -= val
return -1 | find-pivot-index | Python3 368 ms 28% | ajrs | 0 | 2 | find pivot index | 724 | 0.535 | Easy | 11,893 |
https://leetcode.com/problems/find-pivot-index/discuss/2798102/Pivot-entry-in-an-Array-My-Solution | class Solution:
def pivotIndex(self, nums: List[int]) -> int:
initial_right = sum(nums[1:])
left, right = 0, initial_right
if len(nums) == 1 or initial_right == 0:
return 0
for i in range(1,len(nums)):
left += nums[i-1]
right -= nums[i]
if left == right:
return i
return -1 | find-pivot-index | Pivot entry in an Array - My Solution | marked01one | 0 | 3 | find pivot index | 724 | 0.535 | Easy | 11,894 |
https://leetcode.com/problems/find-pivot-index/discuss/2795632/PythonGo-O(n)-balance-scale-solution | class Solution:
def pivotIndex(self, nums: List[int]) -> int:
left_sum = sum(nums)
right_sum = 0
for idx, num in enumerate(nums):
left_sum -= num
if left_sum == right_sum:
return idx
right_sum += num
return -1 | find-pivot-index | Python/Go O(n) balance scale solution | rocketb | 0 | 9 | find pivot index | 724 | 0.535 | Easy | 11,895 |
https://leetcode.com/problems/find-pivot-index/discuss/2793485/SUM-code | class Solution:
def pivotIndex(self, nums: List[int]) -> int:
suml = sum(nums)
left_sum = 0
for i in range(len(nums)):
if left_sum == (suml - (nums[i] + left_sum)):
return i
left_sum += nums[i]
return -1 | find-pivot-index | SUM code | Julierv | 0 | 1 | find pivot index | 724 | 0.535 | Easy | 11,896 |
https://leetcode.com/problems/find-pivot-index/discuss/2793483/SUM-code | class Solution:
def pivotIndex(self, nums: List[int]) -> int:
suml = sum(nums)
left_sum = 0
for i in range(len(nums)):
if left_sum == (suml - (nums[i] + left_sum)):
return i
left_sum += nums[i]
return -1 | find-pivot-index | SUM code | Julierv | 0 | 1 | find pivot index | 724 | 0.535 | Easy | 11,897 |
https://leetcode.com/problems/find-pivot-index/discuss/2792312/Python3-%3A-Using-Two-Pass-HashTable | class Solution:
def pivotIndex(self, nums: List[int]) -> int:
# using Two Pass Hashtable
# Time Complexity : O(n~2n)
# Space Complexity : O(n)
if len(nums) < 2:
return 0 if nums[0] == 0 else -1
postfix_sum = nums[:]
for i in range(2, len(nums) + 1):
postfix_sum[-i] += postfix_sum[-i+1]
if postfix_sum[1] == 0:
return 0
indx = 0
prefix_sum = nums[0]
for j in range(2, len(nums)):
if prefix_sum == postfix_sum[j]:
return j - 1
else:
indx += 1
prefix_sum += nums[indx]
if len(nums) - (indx+1) == 1 and prefix_sum == 0:
return indx+1
return -1 | find-pivot-index | Python3 : Using Two Pass HashTable | boming05292 | 0 | 2 | find pivot index | 724 | 0.535 | Easy | 11,898 |
https://leetcode.com/problems/find-pivot-index/discuss/2791396/Basic-Approach | class Solution:
def pivotIndex(self, nums: List[int]) -> int:
tot_sum = sum(nums)
lsum = 0
for i in range(len(nums)):
if lsum == (tot_sum - nums[i]- lsum):
return i
else:
lsum = lsum + nums[i]
return -1 | find-pivot-index | Basic Approach | siddwho819 | 0 | 2 | find pivot index | 724 | 0.535 | Easy | 11,899 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.