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/long-pressed-name/discuss/1378643/Python3-dollarolution-(97-better-memory-usage) | class Solution:
def isLongPressedName(self, name: str, typed: str) -> bool:
c, v = name[0], []
if name[-1] != typed[-1]:
return False
for i in name[1:]:
if i == c[0]:
c += i
else:
v.append(c)
c = i
v.append(c)
c, j = typed[0], 0
for i in typed[1:]:
if i == c[0]:
c += i
else:
try:
if v[j] not in c:
return False
j += 1
c = i
except:
return False
if v[j] not in c:
return False
if j < len(v)-1:
return False
return True | long-pressed-name | Python3 $olution (97% better memory usage) | AakRay | -1 | 228 | long pressed name | 925 | 0.337 | Easy | 15,000 |
https://leetcode.com/problems/long-pressed-name/discuss/336550/Solution-in-Python-3-(~beats-100) | class Solution:
def isLongPressedName(self, name: str, typed: str) -> bool:
name, typed, c, N = name+'0', typed+'0', 1, []
for s in [name,typed]:
for i in range(len(s)-1):
if s[i] == s[i+1]:
c += 1
else:
N.append([s[i],c])
c = 1
return all([N[i][0] == N[i+len(N)//2][0] and N[i][1] <= N[i+len(N)//2][1] for i in range(len(N)//2)])
- Python 3
- Junaid Mansuri | long-pressed-name | Solution in Python 3 (~beats 100%) | junaidmansuri | -2 | 649 | long pressed name | 925 | 0.337 | Easy | 15,001 |
https://leetcode.com/problems/flip-string-to-monotone-increasing/discuss/1535758/Python3 | class Solution:
def minFlipsMonoIncr(self, s: str) -> int:
"""
0 0 1 1 0
oneCount: 0 0 1 2 2
zeroCount: 1 1 0 0 1
flipCount: 0 0 0 0 1
0 1 0 1 0
oneCount: 0 1 1 2 2
zeroCount: 1 0 1 1 2
flipCount: 0 0 1 1 2
0 0 0 1 1 0 0 0
oneCount: 0 0 0 1 2 2 2 2
zeroCount: 1 1 1 0 0 1 2 3
flipCount: 0 0 0 0 0 1 2 2
"""
oneCount = 0
zeroCount = 0
flipCount = 0
for c in s:
if c == "1":
oneCount += 1
if c == "0":
zeroCount += 1
flipCount = min(zeroCount,oneCount)
zeroCount = flipCount
return flipCount | flip-string-to-monotone-increasing | [Python3] | zhanweiting | 2 | 165 | flip string to monotone increasing | 926 | 0.596 | Medium | 15,002 |
https://leetcode.com/problems/flip-string-to-monotone-increasing/discuss/1395710/Python-3-or-PrefixSuffix-Two-Pass-or-Explanation | class Solution:
def minFlipsMonoIncr(self, s: str) -> int:
n = len(s)
zero, one = [0] * n, [0] * n
prefix = suffix = 0
for i in range(n):
if s[i] == '1':
prefix += 1
zero[i] = prefix # flip '1' to '0'
if s[n-1-i] == '0':
suffix += 1
one[n-1-i] = suffix # flip '0' to '1' (from right to left)
ans = sys.maxsize
for i in range(n-1):
ans = min(ans, zero[i] + one[i+1]) # `i` and its left are all '0', and '1's are on its right
else:
ans = min(ans, zero[n-1], one[0]) # zero[n-1] -> all zeros, one[0] -> all ones
return ans | flip-string-to-monotone-increasing | Python 3 | Prefix/Suffix Two Pass | Explanation | idontknoooo | 2 | 246 | flip string to monotone increasing | 926 | 0.596 | Medium | 15,003 |
https://leetcode.com/problems/flip-string-to-monotone-increasing/discuss/491581/Python-Five-Liner | class Solution:
def minFlipsMonoIncr(self, S: str) -> int:
n, prefix, total, res = len(S), 0, S.count('1'), sys.maxsize
for i in range(n + 1):
res = min(res, prefix + len(S) - i - total + prefix)
if i < n: prefix += 1 if S[i] == '1' else 0
return res | flip-string-to-monotone-increasing | Python - Five Liner | mmbhatk | 2 | 302 | flip string to monotone increasing | 926 | 0.596 | Medium | 15,004 |
https://leetcode.com/problems/flip-string-to-monotone-increasing/discuss/2150170/python-3-oror-very-simple-solution-oror-O(n)O(1) | class Solution:
def minFlipsMonoIncr(self, s: str) -> int:
minFlips = flips = s.count('0')
for c in s:
if c == '0':
flips -= 1
else:
flips += 1
minFlips = min(minFlips, flips)
return minFlips | flip-string-to-monotone-increasing | python 3 || very simple solution || O(n)/O(1) | dereky4 | 1 | 155 | flip string to monotone increasing | 926 | 0.596 | Medium | 15,005 |
https://leetcode.com/problems/flip-string-to-monotone-increasing/discuss/2078055/prefixsum-with-example-python-easy-understanding | class Solution:
def minFlipsMonoIncr(self, s: str) -> int:
def get_prefix(nums):
res = []
cur_sum = 0
for num in nums:
cur_sum += num
res.append(cur_sum)
return res
def get_suffix(nums):
res = []
cur_sum = 0
for num in reversed(nums):
cur_sum += 1 - num
res.append(cur_sum)
return list(reversed(res))
nums = [int(i) for i in s]
print(nums) # [0, 0, 1, 1, 0]
prefix_sum = [0] + get_prefix(nums)
print(prefix_sum) # [0, 0, 0, 1, 2, 2]
suffix_sum = get_suffix(nums) + [0]
print(suffix_sum) # [3, 2, 1, 1, 1, 0]
# [0, 0, 0, 1, 2, 2]
# + + + + + +
# [3, 2, 1, 1, 1, 0]
#
# return min([3, 2, 1, 2, 3, 2])
return min([pre + suf for pre, suf in zip(prefix_sum, suffix_sum)]) | flip-string-to-monotone-increasing | prefixsum, with example, python, easy understanding | yzhao156 | 1 | 55 | flip string to monotone increasing | 926 | 0.596 | Medium | 15,006 |
https://leetcode.com/problems/flip-string-to-monotone-increasing/discuss/957595/Python3-dp-O(N) | class Solution:
def minFlipsMonoIncr(self, S: str) -> int:
ones = flip = 0
for ch in S:
if ch == "1": ones += 1
else: flip = min(ones, flip + 1)
return flip | flip-string-to-monotone-increasing | [Python3] dp O(N) | ye15 | 1 | 103 | flip string to monotone increasing | 926 | 0.596 | Medium | 15,007 |
https://leetcode.com/problems/flip-string-to-monotone-increasing/discuss/957595/Python3-dp-O(N) | class Solution:
def minFlipsMonoIncr(self, S: str) -> int:
ans = one = zero = 0
for i in range(len(S)):
if S[i] == "1":
if i and S[i-1] == "0":
if one <= zero:
ans += one # change 1s to 0s
one = zero = 0 # reset counters
one += 1
else: zero += 1
return ans + min(zero, one) | flip-string-to-monotone-increasing | [Python3] dp O(N) | ye15 | 1 | 103 | flip string to monotone increasing | 926 | 0.596 | Medium | 15,008 |
https://leetcode.com/problems/flip-string-to-monotone-increasing/discuss/2421558/Python-Explanation-Simple-Math-No-DP-O(n)-Time-and-O(1)-space-complexity | class Solution:
def minFlipsMonoIncr(self, s: str) -> int:
n = len(s)
ones = sum([1 if s[i] == '1' else 0 for i in range(n)])
ones_till_now = 0
ans = float('inf')
for i in range(n):
ones_till_now += (1 if s[i] == '1' else 0)
zeros = i+1-ones_till_now
zeros_later = n-i-1 - (ones-ones_till_now)
ones_later = ones-ones_till_now
# zero till ith position
ans = min(ans, ones_till_now + zeros_later)
# one from this position
ans = min(ans, ones_till_now + zeros_later - (1 if s[i] == "1" else 0))
#all ones
ans = min(ans, zeros+zeros_later)
#all zeros
ans = min(ans, ones_till_now+ones_later)
return ans | flip-string-to-monotone-increasing | [Python] Explanation, Simple Math, No DP, O(n) Time and O(1) space complexity | jcbbigcrane | 0 | 60 | flip string to monotone increasing | 926 | 0.596 | Medium | 15,009 |
https://leetcode.com/problems/flip-string-to-monotone-increasing/discuss/2394908/Python3-or-DP-With-Intuition-or-O(1)-Space | class Solution:
def minFlipsMonoIncr(self, s: str) -> int:
cnt_1=int(s[0]=='1')
dp=[0 for i in range(len(s))]
dp[0]=0
for ind in range(1,len(s)):
if s[ind]=='1':
cnt_1+=1
dp[ind]=dp[ind-1]
else:
dp[ind]=min(dp[ind-1]+1,cnt_1)
return dp[-1] | flip-string-to-monotone-increasing | [Python3] | DP With Intuition | O(1) Space | swapnilsingh421 | 0 | 25 | flip string to monotone increasing | 926 | 0.596 | Medium | 15,010 |
https://leetcode.com/problems/flip-string-to-monotone-increasing/discuss/2394908/Python3-or-DP-With-Intuition-or-O(1)-Space | class Solution:
def minFlipsMonoIncr(self, s: str) -> int:
cnt_1=int(s[0]=='1')
prev=0
for ind in range(1,len(s)):
if s[ind]=='1':
cnt_1+=1
else:
prev=min(prev+1,cnt_1)
return prev | flip-string-to-monotone-increasing | [Python3] | DP With Intuition | O(1) Space | swapnilsingh421 | 0 | 25 | flip string to monotone increasing | 926 | 0.596 | Medium | 15,011 |
https://leetcode.com/problems/flip-string-to-monotone-increasing/discuss/2275920/Python3-Solution-with-using-dp | class Solution:
def minFlipsMonoIncr(self, s: str) -> int:
flip_count = 0 # 0 to 1
ones = 0 # 1 counter
for c in s:
if c == '1':
ones += 1
else:
flip_count = min(flip_count + 1, ones)
return flip_count | flip-string-to-monotone-increasing | [Python3] Solution with using dp | maosipov11 | 0 | 18 | flip string to monotone increasing | 926 | 0.596 | Medium | 15,012 |
https://leetcode.com/problems/flip-string-to-monotone-increasing/discuss/1840938/Simple-Prefix-sum-with-python-code | class Solution:
def minFlipsMonoIncr(self, s: str) -> int:
sums = 0
for st in s:
sums += int(st)
lens = len(s)
pre = 0
mini = float('inf')
for i in range(len(s)):
if s[i] == '1':
pre += 1
mini = min(mini, pre + (lens - i - 1) - (sums-pre))
return min(mini, lens - sums) | flip-string-to-monotone-increasing | Simple Prefix sum with python code | houtarou | 0 | 137 | flip string to monotone increasing | 926 | 0.596 | Medium | 15,013 |
https://leetcode.com/problems/flip-string-to-monotone-increasing/discuss/1812944/Easy-python-solution-with-comment | class Solution:
def minFlipsMonoIncr(self, s: str) -> int:
num_0 = 0
for i in range(len(s)):
if s[i] == "0":
num_0 += 1
res = num_0 # At first, we assume that we flip every "0" into "1".
left_1, right_0 = 0, num_0 # When we are at the first idx, no "1" on our left, every "0" on our right
for i in range(len(s)): # The number we need to flip equals to (left_1 + right_0)
if s[i] == "0": # So as we walk step by step, if is is "0" --> right_0 -= 1
right_0 -= 1
elif s[i] == "1": # If it is "1" --> left_1 += 1
left_1 += 1
res = min(res, right_0 + left_1) # Update the res
return res | flip-string-to-monotone-increasing | Easy python solution with comment | byroncharly3 | 0 | 115 | flip string to monotone increasing | 926 | 0.596 | Medium | 15,014 |
https://leetcode.com/problems/flip-string-to-monotone-increasing/discuss/1395750/Greedy-oror-Clean-and-Concise-oror-98-faster | class Solution:
def minFlipsMonoIncr(self, s: str) -> int:
o,z = 0,0
res = 0
for i in s:
if i=="1":
o+=1
else:
if o:
z+=1
if o==z:
res += z
z,o = 0,0
res+=z
return res | flip-string-to-monotone-increasing | 📌 Greedy || Clean & Concise || 98% faster 🐍 | abhi9Rai | 0 | 124 | flip string to monotone increasing | 926 | 0.596 | Medium | 15,015 |
https://leetcode.com/problems/flip-string-to-monotone-increasing/discuss/1395397/python-3-solution-oror-easy-oror-clean-oror-beginners | class Solution:
def minFlipsMonoIncr(self, s: str) -> int:
zero_to_1s=0
no_of_1s=0
i=0
while(i<len(s) and s[i]==0):
i+=1
for i in range(len(s)):
if s[i]=='0':
zero_to_1s+=1
else:
no_of_1s+=1
if zero_to_1s>no_of_1s:
zero_to_1s=no_of_1s
return zero_to_1s | flip-string-to-monotone-increasing | python 3 solution || easy || clean || beginners | minato_namikaze | 0 | 70 | flip string to monotone increasing | 926 | 0.596 | Medium | 15,016 |
https://leetcode.com/problems/flip-string-to-monotone-increasing/discuss/1190263/EASIESTIntuitive-O(n)-time-O(1)-space-or-Explained-or-DP-or-Python-3 | class Solution:
def minFlipsMonoIncr(self, S: str) -> int:
# DP approach: iterate through all of the input chars
# maintain min number of flips to end with 0 or with 1
flips_0 = 0
flips_1 = 0
for i, c in enumerate(S):
if c == '0':
# flips_0 stays the same
flips_1 = min(flips_0, flips_1) + 1
elif c == '1':
flips_1 = min(flips_0, flips_1) # update flips_1 first!
flips_0 += 1
return min(flips_0, flips_1) | flip-string-to-monotone-increasing | EASIEST/Intuitive O(n) time O(1) space | Explained | DP | Python 3 | EddyLin | 0 | 186 | flip string to monotone increasing | 926 | 0.596 | Medium | 15,017 |
https://leetcode.com/problems/flip-string-to-monotone-increasing/discuss/795912/Python3-group-by-0s-and-1s-Flip-String-to-Monotone-Increasing | class Solution:
def minFlipsMonoIncr(self, S: str) -> int:
counts = [[k, len(list(g))] for k, g in itertools.groupby(S)]
if not counts or len(counts) == 1 or len(counts) == 2 and counts[1][0] == '1':
return 0
zero_left = sum(b for a, b in counts if a == '0')
one_seen = 0
ans = float('inf')
for c, cnt in counts:
if c == '1':
ans = min(ans, zero_left + one_seen)
one_seen += cnt
else:
zero_left -= cnt
ans = min(ans, zero_left + one_seen)
return ans | flip-string-to-monotone-increasing | Python3 group by 0s and 1s - Flip String to Monotone Increasing | r0bertz | 0 | 119 | flip string to monotone increasing | 926 | 0.596 | Medium | 15,018 |
https://leetcode.com/problems/flip-string-to-monotone-increasing/discuss/391665/Solution-in-Python-3-(-O(n)-time-)-(-O(1)-space-)-(one-line) | class Solution:
def minFlipsMonoIncr(self, S: str) -> int:
L, S, m, s = len(S), [0]+[int(i) for i in S], math.inf, 0
for i,j in enumerate(S):
s += j
m = min(2*s-i,m)
return L-s+m | flip-string-to-monotone-increasing | Solution in Python 3 ( O(n) time ) ( O(1) space ) (one line) | junaidmansuri | -1 | 196 | flip string to monotone increasing | 926 | 0.596 | Medium | 15,019 |
https://leetcode.com/problems/flip-string-to-monotone-increasing/discuss/391665/Solution-in-Python-3-(-O(n)-time-)-(-O(1)-space-)-(one-line) | class Solution:
def minFlipsMonoIncr(self, S: str) -> int:
return min(2*j-i for i,j in enumerate([0]+list(itertools.accumulate([int(i) for i in S]))))+len(S)-S.count('1')
- Junaid Mansuri
(LeetCode ID)@hotmail.com | flip-string-to-monotone-increasing | Solution in Python 3 ( O(n) time ) ( O(1) space ) (one line) | junaidmansuri | -1 | 196 | flip string to monotone increasing | 926 | 0.596 | Medium | 15,020 |
https://leetcode.com/problems/three-equal-parts/discuss/1343709/2-clean-Python-linear-solutions | class Solution:
def threeEqualParts(self, arr: List[int]) -> List[int]:
# count number of ones
ones = sum(arr)
if ones % 3 != 0:
return [-1, -1]
elif ones == 0: # special case: all zeros
return [0, 2]
# find the start index of each group of ones
c = 0
starts = []
for i, d in enumerate(arr):
if d == 1:
if c % (ones // 3) == 0:
starts.append(i)
c += 1
# scan the groups in parallel to compare digits
i, j, k = starts
while k < len(arr): # note that the last/rightmost group must include all digits till the end
if arr[i] == arr[j] == arr[k]:
i += 1
j += 1
k += 1
else:
return [-1, -1]
return [i-1, j] | three-equal-parts | 2 clean Python linear solutions | cthlo | 7 | 265 | three equal parts | 927 | 0.396 | Hard | 15,021 |
https://leetcode.com/problems/three-equal-parts/discuss/1343709/2-clean-Python-linear-solutions | class Solution:
def threeEqualParts(self, arr: List[int]) -> List[int]:
# gather the indices of the ones
ones = [i for i, d in enumerate(arr) if d == 1]
if not ones:
return [0, 2]
elif len(ones) % 3 != 0:
return [-1, -1]
# get the start indices of the 3 groups
i, j, k = ones[0], ones[len(ones)//3], ones[len(ones)//3*2]
# calculate the size/length of what each group should be
length = len(arr) - k # note that the last/rightmost group must include all digits till the end
# so we know that the size of each group is `len(arr) - k` (where `k` is start of third group)
# compare the three groups
if arr[i:i+length] == arr[j:j+length] == arr[k:k+length]:
return [i+length-1, j+length]
return [-1, -1] | three-equal-parts | 2 clean Python linear solutions | cthlo | 7 | 265 | three equal parts | 927 | 0.396 | Hard | 15,022 |
https://leetcode.com/problems/three-equal-parts/discuss/481365/Python-intuitive-solution-less-than-100-memory-usage | class Solution(object):
def threeEqualParts(self, A):
"""
:type A: List[int]
:rtype: List[int]
"""
N = len(A)
if N < 3:
return [-1, -1]
count_of_one = A.count(1)
if count_of_one == 0:
return [0, N-1]
if count_of_one % 3 != 0:
return [-1, -1]
pattern = ''
count = 0
reversed_str = ''.join(map(str, A[::-1]))
for i, digit in enumerate(A[::-1]):
if digit == 1:
count += 1
if count == count_of_one/3:
break
pattern = reversed_str[:i+1]
length = len(reversed_str)
len_pattern = len(pattern)
'''matching'''
index = reversed_str.find(pattern, len_pattern)
if index == -1:
return [-1, -1]
j = length - index
index = reversed_str.find(pattern, len_pattern + index)
if index == -1:
return [-1, -1]
i = length - index - 1
return [i, j] | three-equal-parts | [Python] intuitive solution, less than 100% memory usage | llJll | 1 | 164 | three equal parts | 927 | 0.396 | Hard | 15,023 |
https://leetcode.com/problems/three-equal-parts/discuss/1344936/Python3-prefix-sum-O(N) | class Solution:
def threeEqualParts(self, arr: List[int]) -> List[int]:
MOD = 1_000_000_007
total = 0
p2 = [1]
for x in arr:
total = (2*total + x) % MOD
p2.append((p2[-1] << 1) % MOD)
seen = {}
prefix = 0
for j, x in enumerate(arr):
prefix = (2*prefix + x) % MOD
diff = (total - prefix * p2[len(arr)-1-j]) % MOD
if diff in seen:
i = seen[diff]
if diff == (prefix - diff * p2[j - i]) % MOD: return [i, j+1]
seen[prefix] = j
return [-1, -1] | three-equal-parts | [Python3] prefix sum O(N) | ye15 | 0 | 31 | three equal parts | 927 | 0.396 | Hard | 15,024 |
https://leetcode.com/problems/three-equal-parts/discuss/1344809/python3-compare-lengths-of-three-chunks-sol-for-reference | class Solution:
def threeEqualParts(self, arr: List[int]) -> List[int]:
indices = deque([])
N = len(arr)
ans = [-1,-1]
## collect all indices of 1
for idx, val in enumerate(arr):
if val:
indices.append(idx)
if not indices:
return [0, N-1]
if len(indices) %3 != 0:
return [-1, -1]
start = 0
end = len(indices)-1
s = indices[start]
# if ending in zero, the right most part of 3 parts, should always be from end of middle chunk-until end of array
endsInZero = (arr[-1] == 0)
# s....index[start]...index[end]....#
# chunk1 - starts with the first 1
# chunk2 - start with chunk1 end + 1 or 1st one after chunk1
# chunk3 - start with chunk2+1 until end
## if the array ends in zero, then the calcuation should be from chunk1+len(last_chunk), chunk2+len(last_chunk) and its edge cases.
while start < end:
if endsInZero:
edge_len = N-1-indices[end]
medge_index = min(indices[end], indices[start+1]+edge_len+1)
## Edge case, if between middle index edge and end if there are 1s
medge_index = max(medge_index, indices[end-1])
## check if the lengths are equal, chunk1 and chunk3 have edge_len, hence only compare with middle.
if medge_index - indices[start+1] == edge_len+1:
if arr[s:s+edge_len+1] == arr[indices[end]:] == arr[indices[start+1]: medge_index]:
return (s+edge_len,medge_index)
else:
## check if the lengths are equal
if indices[start]-s == N-indices[end]-1 == indices[end-1]-indices[start+1]:
if arr[s:indices[start]+1] == arr[indices[end]:] == arr[indices[start+1]:indices[end-1]+1]:
return (indices[start],indices[end-1]+1)
start += 1
end -= 1
return ans | three-equal-parts | [python3] compare lengths of three chunks sol for reference | vadhri_venkat | 0 | 53 | three equal parts | 927 | 0.396 | Hard | 15,025 |
https://leetcode.com/problems/three-equal-parts/discuss/1344534/Python-11-lines-332-ms-(beats-100) | class Solution:
def threeEqualParts(self, arr: List[int]) -> List[int]:
ones = [i for i, x in enumerate(arr) if x]
n, r = divmod(len(ones), 3)
if r: return -1, -1
if not n: return 0, 2
a, b, c = ones[0], ones[n], ones[2*n]
r = len(arr) - c
if r > max(b-a, c-b) or not arr[a+1:a+r] == arr[b+1:b+r] == arr[c+1:]:
return -1, -1
return a + r - 1, b + r | three-equal-parts | [Python] 11 lines, 332 ms (beats 100%) | adidenkov | 0 | 29 | three equal parts | 927 | 0.396 | Hard | 15,026 |
https://leetcode.com/problems/minimize-malware-spread-ii/discuss/2845885/Python-9-lines-O(kn2)-BFS | class Solution:
# the key observation for me is the fact that we don't need to
# really delete the initial in the graph. We can simply ignore
# the deleted initial while we are doing BFS. So basically we
# do BFS with each deleted value on initial, and we get the
# minimal count of the connected graph. Note if two deleted
# values give same count of connected graph, then we choose
# smaller value. that's why I used a tuple, (BFS(a), a) this
# will first compare BFS(a), if they are equal then it compares
# a.
def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:
def BFS(delval):
seen, lst = set(), list(initial)
while lst:
node = lst.pop()
if node == delval or node in seen: continue
seen.add(node)
lst += [i for i, val in enumerate(graph[node]) if val]
return len(seen)
return min(initial, key=lambda a: (BFS(a), a)) | minimize-malware-spread-ii | Python 9 lines O(kn^2) BFS | tinmanSimon | 0 | 2 | minimize malware spread ii | 928 | 0.426 | Hard | 15,027 |
https://leetcode.com/problems/minimize-malware-spread-ii/discuss/1934662/Simple-Python-DFS | class Solution:
def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:
initial = set(initial)
def dfs(i):
for j, conn in enumerate(graph[i]):
if conn and j not in initial and j not in nodes:
nodes.add(j)
dfs(j)
sourceDict = defaultdict(list)
for node in initial:
nodes = set()
dfs(node)
for i in nodes:
sourceDict[i].append(node)
counter = defaultdict(int)
maxVal, minNode = -1, float('inf')
for infected, sources in sourceDict.items():
if len(sources) == 1:
src = sources[0]
counter[src] += 1
if counter[src] > maxVal or (counter[src] == maxVal and src < minNode):
minNode = src
maxVal = counter[src]
return minNode if maxVal > -1 else min(initial) | minimize-malware-spread-ii | Simple Python DFS | totoslg | 0 | 23 | minimize malware spread ii | 928 | 0.426 | Hard | 15,028 |
https://leetcode.com/problems/unique-email-addresses/discuss/261959/Easy-understanding-python-solution-(44ms-faster-than-99.3) | class Solution:
def numUniqueEmails(self, emails: List[str]) -> int:
def parse(email):
local, domain = email.split('@')
local = local.split('+')[0].replace('.',"")
return f"{local}@{domain}"
return len(set(map(parse, emails))) | unique-email-addresses | Easy-understanding python solution (44ms, faster than 99.3%) | ShaneTsui | 19 | 1,300 | unique email addresses | 929 | 0.672 | Easy | 15,029 |
https://leetcode.com/problems/unique-email-addresses/discuss/1488791/Easy-and-Simple-oror-Well-Defined-Code-oror-For-Beginners | class Solution:
def numUniqueEmails(self, emails: List[str]) -> int:
res = set()
for email in emails:
local,domain = email.split('@')
tmp = ""
for c in local:
if c==".": continue
elif c=="+": break
else: tmp+=c
res.add(tmp+"@"+domain)
return len(res) | unique-email-addresses | 📌📌 Easy & Simple || Well-Defined Code || For Beginners 🐍 | abhi9Rai | 12 | 361 | unique email addresses | 929 | 0.672 | Easy | 15,030 |
https://leetcode.com/problems/unique-email-addresses/discuss/254862/Python-~10-lines-~-easy-to-understand | class Solution:
def numUniqueEmails(self, emails):
uniques = set() # A set can not contain duplicates
for email in emails:
name, domain = email.split("@")
if "+" in name:
name = name.split("+")[0].replace(".", "") # grab everything before "+", remove "."
else:
name = name.replace('.', "") # remove "."
cleanEmail = name + "@" + domain # reassemble emails
uniques.add(cleanEmail) # add cleanEmail to set, which will not accept duplicates
return len(uniques) # return length of uniques to get number of uniques | unique-email-addresses | Python ~10 lines ~ easy to understand | nicolime | 4 | 544 | unique email addresses | 929 | 0.672 | Easy | 15,031 |
https://leetcode.com/problems/unique-email-addresses/discuss/1047458/Python3-simple-solution-using-set | class Solution:
def numUniqueEmails(self, emails):
s = set()
for i in emails:
a, b = i.split('@')
if '+' in a:
a = a[:a.index('+')]
s.add(a.replace('.','') + '@' + b)
return len(s) | unique-email-addresses | Python3 simple solution using set | EklavyaJoshi | 2 | 103 | unique email addresses | 929 | 0.672 | Easy | 15,032 |
https://leetcode.com/problems/unique-email-addresses/discuss/2555449/Simple-Python-Solution-or-Faster-than-98.7 | class Solution:
def numUniqueEmails(self, emails: List[str]) -> int:
set_ = set()
for i in emails:
final_email = ""
email = i.split("@")
email[0] = email[0].replace(".","")
if "+" in email[0]:
index= email[0].index("+")
email[0] = email[0][:index]
final_email+=email[0]+"@"+email[1]
set_.add(final_email)
return len(set_) | unique-email-addresses | Simple Python Solution | Faster than 98.7% | aniketbhamani | 1 | 83 | unique email addresses | 929 | 0.672 | Easy | 15,033 |
https://leetcode.com/problems/unique-email-addresses/discuss/2087355/Python3-O(N)-oror-O(N)-61ms-72.55 | class Solution:
# O(N) || O(N) 61ms 72.55%
def numUniqueEmails(self, emails: List[str]) -> int:
if not emails:
return 0
seen = set()
for email in emails:
name, domain = email.split('@')
local = name.split('+')[0].replace('.', '')
seen.add(local + '@' + domain)
return len(seen) | unique-email-addresses | Python3 O(N) || O(N) 61ms 72.55% | arshergon | 1 | 73 | unique email addresses | 929 | 0.672 | Easy | 15,034 |
https://leetcode.com/problems/unique-email-addresses/discuss/1904639/Python-Two-Solutions | class Solution:
def numUniqueEmails(self, emails: List[str]) -> int:
def convertEmail(s):
local,domain = s.split("@")
local = local.split("+")[0]
local = local.replace(".","")
return local+"@"+domain
return len( set( [ convertEmail(email) for email in emails ] ) ) | unique-email-addresses | Python Two Solutions | haydarevren | 1 | 46 | unique email addresses | 929 | 0.672 | Easy | 15,035 |
https://leetcode.com/problems/unique-email-addresses/discuss/1904639/Python-Two-Solutions | class Solution:
def numUniqueEmails(self, emails: List[str]) -> int:
def convertEmail(s):
return re.sub(r'\.(?=.*@)|\+.*(?=@)', '', s)
return len( set( [ convertEmail(email) for email in emails ] ) ) | unique-email-addresses | Python Two Solutions | haydarevren | 1 | 46 | unique email addresses | 929 | 0.672 | Easy | 15,036 |
https://leetcode.com/problems/unique-email-addresses/discuss/1355851/Faster-than-95-Solution-Using-set-and-find-function | class Solution:
def numUniqueEmails(self, emails: List[str]) -> int:
s = set()
for mail in emails:
a,b = mail.split('@')
a = a.replace(".","")
idx = a.find('+')
if idx != - 1:
a = a[:idx]
a = a + '@' + b
s.add(a)
return len(s) | unique-email-addresses | Faster than 95% Solution Using set and find function | leggasick | 1 | 106 | unique email addresses | 929 | 0.672 | Easy | 15,037 |
https://leetcode.com/problems/unique-email-addresses/discuss/2841770/Python-or-Easy-or-Beginner-friendly | class Solution:
def numUniqueEmails(self, emails: List[str]) -> int:
d = []
for email in emails:
name, domain = email.split('@')
name = name.replace(".", '')
if '+' in name:
name = name.split('+')[0]
email = name + '@' + domain
if email not in d:
d.append(email)
return len(d) | unique-email-addresses | Python | Easy | Beginner friendly | pawangupta | 0 | 1 | unique email addresses | 929 | 0.672 | Easy | 15,038 |
https://leetcode.com/problems/unique-email-addresses/discuss/2815358/Easy-Python | class Solution:
def numUniqueEmails(self, emails: List[str]) -> int:
email_list = []
for email in emails:
local, domain = email.split("@")
local = local.replace('.', '')
plusIndex = local.find('+')
if plusIndex > -1:
local = local[:plusIndex]
if(local+"@"+domain not in email_list):
print("here")
email_list.append(local+"@"+domain)
return len(email_list) | unique-email-addresses | Easy Python | asiffmahmudd | 0 | 2 | unique email addresses | 929 | 0.672 | Easy | 15,039 |
https://leetcode.com/problems/unique-email-addresses/discuss/2793890/50ms-Fast-Solution-(One-Liner-ish) | class Solution:
def numUniqueEmails(self, emails: List[str]) -> int:
if len(emails) < 2: return 1 # base case : return 1 if there's only one email
return len(set(map(self.stripMail, emails)))
def stripMail(self, mail: str):
# split by domain and unpack everything before the domain
*localName, domain = mail.split("@")
# 1. split + and discard everything after
# 2. split . and join to empty str
localName = ["".join(n.split("+")[0].split(".")) for n in localName]
return domain, localName[0] | unique-email-addresses | 50ms Fast Solution (One Liner-ish) | keshan-spec | 0 | 2 | unique email addresses | 929 | 0.672 | Easy | 15,040 |
https://leetcode.com/problems/unique-email-addresses/discuss/2772826/Simple-Python-Solution | class Solution:
def numUniqueEmails(self, emails):
d = Counter()
for mail in emails:
local, domain = mail.split("@")
local = local.replace(".", "")
if "+" in local: local = local[:local.index("+")]
d[local + "@" + domain] += 1
return len(d) | unique-email-addresses | Simple Python Solution | dnvavinash | 0 | 2 | unique email addresses | 929 | 0.672 | Easy | 15,041 |
https://leetcode.com/problems/unique-email-addresses/discuss/2757136/Regex-and-string-concatenation | class Solution:
def numUniqueEmails(self, emails: List[str]) -> int:
import re
regex = re.compile(r"^[a-z0-9.+]+@([a-z0-9-+]+\.)+[a-z0-9-]{2,4}$")
def verify(email):
if re.fullmatch(regex, email.lower()):
local, domain = email.split("@")
if "+" in local:
local = local[:int(local.index("+"))]
email = local.replace(".", "")+"@"+domain
return email
return len(set([result for result in map(verify, emails) if result is not None])) | unique-email-addresses | Regex and string concatenation | DavidCastillo | 0 | 3 | unique email addresses | 929 | 0.672 | Easy | 15,042 |
https://leetcode.com/problems/unique-email-addresses/discuss/2728435/Easy-Python-solution | class Solution:
def numUniqueEmails(self, emails: List[str]) -> int:
temp = []
for email in emails:
temp_mail = ""
splitted = email.split("@")
name = splitted[0].replace(".","")
name = name.split("+")[0]
temp_mail = name+"@"+splitted[1]
temp.append(temp_mail)
print(temp)
return len(set(temp)) | unique-email-addresses | Easy Python solution | hemantsah18 | 0 | 2 | unique email addresses | 929 | 0.672 | Easy | 15,043 |
https://leetcode.com/problems/unique-email-addresses/discuss/2712178/Python-Easy-solution-with-Set | class Solution:
def getBaseEmail(self, email: str) -> str:
atIndex = email.find('@')
localName = email[:atIndex]
domainName = email[atIndex:]
#Remove dot from name
localName = localName.replace('.', '')
#Remove '+' part
if '+' in email:
localName = localName[:localName.find('+')]
return localName+domainName
def numUniqueEmails(self, emails: List[str]) -> int:
emailSet = set([self.getBaseEmail(email) for email in emails])
return len(emailSet) | unique-email-addresses | Python Easy solution with Set | abrarjahin | 0 | 8 | unique email addresses | 929 | 0.672 | Easy | 15,044 |
https://leetcode.com/problems/unique-email-addresses/discuss/2673873/Python-not-simple | class Solution:
def numUniqueEmails(self, emails: List[str]) -> int:
unique_emails = set()
for e in emails:
local = None
temp = ""
for i, c in enumerate(e):
if local is None:
if c == "+":
local = temp
elif c != ".":
temp += c
if c == "@":
unique_emails.add((temp[:-1] if local is None else local) + e[i:])
break
return len(unique_emails) | unique-email-addresses | Python - not simple | phantran197 | 0 | 6 | unique email addresses | 929 | 0.672 | Easy | 15,045 |
https://leetcode.com/problems/unique-email-addresses/discuss/2555285/Python-~-solution-using-set-~-easy-to-understand | class Solution:
def numUniqueEmails(self, emails: List[str]) -> int:
lst=[]
for data in emails:
if "+" in data:
local_name=data.split('+')[0].replace('.','')
else:
local_name=data.split('@')[0].replace('.','')
domain=concat('@',data.split('@')[1])
lst.append(concat(local_name,domain))
return(len(set(lst))) | unique-email-addresses | Python ~ solution using set ~ easy to understand | muniyappanmani | 0 | 27 | unique email addresses | 929 | 0.672 | Easy | 15,046 |
https://leetcode.com/problems/unique-email-addresses/discuss/2551367/Python-simple-solution | class Solution:
def numUniqueEmails(self, emails: List[str]) -> int:
ans = set()
for em in emails:
tmp = ''
for lt in em:
if lt == '@' or lt == '+':
break
elif lt == '.':
continue
else:
tmp += lt
tmp += '@' + em.split('@')[1]
ans.add(tmp)
return len(ans) | unique-email-addresses | Python simple solution | StikS32 | 0 | 26 | unique email addresses | 929 | 0.672 | Easy | 15,047 |
https://leetcode.com/problems/unique-email-addresses/discuss/2417679/Python-98-Faster-solution | class Solution:
def numUniqueEmails(self, emails: List[str]) -> int:
mailbox = set()
for email in emails:
localName = email.split('@')[0]
domainName = email.replace(localName, '')
if localName.find('+') != -1:
localName = localName[:localName.find('+')]
localName = localName.replace('.', '')
emailName = localName + domainName
mailbox.add(emailName)
return len(mailbox) | unique-email-addresses | [Python] 98% Faster solution | jiarow | 0 | 48 | unique email addresses | 929 | 0.672 | Easy | 15,048 |
https://leetcode.com/problems/unique-email-addresses/discuss/2337128/Python-solution-Beats-95 | class Solution:
def numUniqueEmails(self, emails: List[str]) -> int:
def ets(email):
s, domain = email[:email.index('@')], email[email.index('@'):]
s = s.replace(".", "")
s = s[:s.index('+')] if '+' in s else s
return s+domain
dict = {}
for i in emails:
dict[ets(i)] = 1
return len(dict) | unique-email-addresses | Python solution [Beats 95%] | CasualTrash | 0 | 95 | unique email addresses | 929 | 0.672 | Easy | 15,049 |
https://leetcode.com/problems/unique-email-addresses/discuss/1980931/Easiest-and-simplest-Python-3-Solution-or-Beginner-friendly-or-100-Faster | class Solution:
def numUniqueEmails(self, emails: List[str]) -> int:
temp=[]
for i in emails:
domain=i.split('@')
if '+' in domain[0]:
ind=domain[0].index('+')
ss=domain[0][0:ind]
ss=ss.replace('.','')+'@'+domain[1]
if ss not in temp:
temp.append(ss)
else:
ss=domain[0]
ss=ss.replace('.','')+'@'+domain[1]
if ss not in temp:
temp.append(ss)
return (len(temp)) | unique-email-addresses | Easiest & simplest Python 3 Solution | Beginner-friendly | 100% Faster | RatnaPriya | 0 | 54 | unique email addresses | 929 | 0.672 | Easy | 15,050 |
https://leetcode.com/problems/unique-email-addresses/discuss/1939053/Python-3-Easy-to-understand-for-absolute-beginners. | class Solution:
def numUniqueEmails(self, emails: List[str]) -> int:
d = {}
for email in emails:
s = email.split('@')
domain = s[1]
name = s[0]
correctName = ''
for i in name:
if i == '.':
continue
elif i == '+':
break
else:
correctName += str(i)
if d.get(domain, 0) == 0:
d[domain] = [correctName]
else:
if(correctName in d[domain]):
continue
else:
d[domain].append(correctName)
count = 0
for element in d:
count += len(d[element])
return count | unique-email-addresses | [Python 3] Easy to understand, for absolute beginners. | Amogh23 | 0 | 23 | unique email addresses | 929 | 0.672 | Easy | 15,051 |
https://leetcode.com/problems/unique-email-addresses/discuss/1895995/Python-simple-and-easy-to-understand | class Solution:
def numUniqueEmails(self, emails: List[str]) -> int:
ans = {}
for i in range(len(emails)):
local_name = emails[i][:emails[i].index('@')].replace(".", "")
if local_name.find('+') != -1:
local_name = local_name[:local_name.index('+')] + emails[i][emails[i].index('@'):]
else:
local_name += emails[i][emails[i].index('@'):]
ans[local_name] = 1
return len(ans) | unique-email-addresses | Python simple and easy to understand | Ploypaphat | 0 | 59 | unique email addresses | 929 | 0.672 | Easy | 15,052 |
https://leetcode.com/problems/unique-email-addresses/discuss/1854023/Python-Solution | class Solution:
def numUniqueEmails(self, emails: List[str]) -> int:
# According to the question, an email is basically 'localName@domainName'
actualEmailSet = set()
for email in emails:
# Get the actual local name
# Get the raw domain name
# | Get only the part before any "+"
# V V Replace any "." with ""
actualLocalName = email.split("@")[0].split("+")[0].replace(".", "")
# Get the actual domain name
actualDomainName = email.split("@")[1]
actualEmail = actualLocalName + "@" + actualDomainName
if actualEmail not in actualEmailSet:
actualEmailSet.add(actualEmail)
else:
pass
# Set does not allow duplicates, so theoretically speaking the if condition above is not necessary
return len(actualEmailSet) | unique-email-addresses | Python Solution | White_Frost1984 | 0 | 25 | unique email addresses | 929 | 0.672 | Easy | 15,053 |
https://leetcode.com/problems/unique-email-addresses/discuss/1688705/Beats-96.15-of-python3-submissions-about-runtime. | class Solution:
def numUniqueEmails(self, emails: List[str]) -> int:
unique_email_list = []
for email in emails:
tmp_list = []
tmp_list = email.split('@')
tmp_list[0] = tmp_list[0].replace('.', '')
if '+' in tmp_list[0]:
tmp_list[0] = tmp_list[0][:tmp_list[0].index('+')]
fixed_email = '@'.join(tmp_list)
if fixed_email not in unique_email_list:
unique_email_list.append(fixed_email)
return len(unique_email_list) | unique-email-addresses | Beats 96.15% of python3 submissions about runtime. | daiki98 | 0 | 41 | unique email addresses | 929 | 0.672 | Easy | 15,054 |
https://leetcode.com/problems/unique-email-addresses/discuss/1490546/Unique-Email-Addresses-or-Python3-or-Simple | class Solution:
def numUniqueEmails(self, emails):
domainnames = [] # array for domain names
i = 0 # keep count of which email I'm on
while i < len(emails):
for j in range(len(emails[i])-1,0,-1):
if emails[i][j] == '@': # finding where the @ is to find the domain name
domainnames.append(emails[i][j+1:]) # add domain name to array
break # break out of loop
i += 1 # go to next email
for j in emails: # go through every email
index = emails.index(j) # record index of the email
j = j.split('.') # remove periods
j = ''.join(j) # turn back to str from list
j = j.split('+') # remove +'s
emails[index] = ''.join(j[0]) # insert back into emails
for j in range(len(emails)): # go through every email
emails[j] += '@' # add in the
emails[j] += domainnames[j] # domain names
return len(set(emails)) # use set to avoid overcounting emails | unique-email-addresses | Unique Email Addresses | Python3 | Simple? | StarStalkX827 | 0 | 39 | unique email addresses | 929 | 0.672 | Easy | 15,055 |
https://leetcode.com/problems/unique-email-addresses/discuss/1490546/Unique-Email-Addresses-or-Python3-or-Simple | class Solution:
def numUniqueEmails(self, emails):
domainnames = [] #array for domain names
for i in emails: # go through every email
for j in range(len(i)-1, 0, -1): # go backwards through the email (idk could go from front)
if i[j] == '@': # find the @
domainnames.append(i[j:]) # add everything on the right of the @ (and the @) to the domain name array
for j in emails: # go through every email
index = emails.index(j) # record index
j = j.split('.') # remove periods
j = ''.join(j) # turn back into str from list
if '+' in j: # if there is a + (otherwise entire email with domain name with be left over because we want to add domain name back)
j = j.split('+') # remove +'s and everything to the right because we'll add the domain name back later
emails[index] = ''.join(j[0]) # turn back into string
else: # if there isn't a +
j = j.split('@') # remove @'s and everything to the right
emails[index] = ''.join(j[0]) # turn back into string
for j in range(len(emails)): # go through all of the emails
emails[j] += domainnames[j] # add the domain names back into the emails without .'s or +'s
return len(set(emails)) # use set to avoid overcounting emails | unique-email-addresses | Unique Email Addresses | Python3 | Simple? | StarStalkX827 | 0 | 39 | unique email addresses | 929 | 0.672 | Easy | 15,056 |
https://leetcode.com/problems/unique-email-addresses/discuss/1489920/Simple-Clean-Python-Solution | class Solution:
def numUniqueEmails(self, emails: List[str]) -> int:
res=set()
for e in emails:
local,domain=e.split("@") #Finding the local name and domain name by splitting at @
plus=local.find("+") #Finding the first plus sign
if plus!=-1:
local=local[:plus] #Ignoring the text after first plus sign in local name
local=local.replace(".","") #Ignoring the dots in local name
res.add(local+"@"+domain)
return len(res) | unique-email-addresses | Simple Clean Python Solution | Umadevi_R | 0 | 31 | unique email addresses | 929 | 0.672 | Easy | 15,057 |
https://leetcode.com/problems/unique-email-addresses/discuss/1489841/Python3-string-ops | class Solution:
def numUniqueEmails(self, emails: List[str]) -> int:
seen = set()
for email in emails:
local, domain = email.split("@")
local = local.split("+")[0].replace(".", "")
seen.add("@".join((local, domain)))
return len(seen) | unique-email-addresses | [Python3] string ops | ye15 | 0 | 17 | unique email addresses | 929 | 0.672 | Easy | 15,058 |
https://leetcode.com/problems/unique-email-addresses/discuss/1489802/python3-ez-solution | class Solution:
def numUniqueEmails(self, emails: List[str]) -> int:
if not emails:
return 0
output = set()
for email in emails:
[name,domain] = email.split('@')
new_name = ''
for i in range(len(name)):
if name[i] == '+':
break
elif name[i] == '.':
pass
else:
new_name += name[i]
output.add(new_name + '@' + domain)
return len(output) | unique-email-addresses | python3 ez solution | yingziqing123 | 0 | 16 | unique email addresses | 929 | 0.672 | Easy | 15,059 |
https://leetcode.com/problems/unique-email-addresses/discuss/1489244/Unique-Emails-or-Python-3-or-Quadratic-Time | class Solution:
def numUniqueEmails(self, emails: List[str]) -> int:
unique_emails = set()
for email in emails:
index_rate = email.index("@")
domain = email[index_rate:len(email)]
local = ""
for j in range(index_rate):
if email[j] == "+":
break
elif email[j]==".":
continue
else:
local += email[j]
address = local + domain
unique_emails.add(address)
return len(unique_emails) | unique-email-addresses | Unique Emails | Python 3 | Quadratic Time | Hassaan-Raheem | 0 | 49 | unique email addresses | 929 | 0.672 | Easy | 15,060 |
https://leetcode.com/problems/unique-email-addresses/discuss/1412021/Python-Set-oror-Dictionary | class Solution:
def numUniqueEmails(self, emails: List[str]) -> int:
mem = {}
for email in emails:
email_split = email.split("@")
local_name = email_split[0].split("+")[0].replace(".", "")
domain_name = email_split[1]
if domain_name not in mem:
mem[domain_name] = set([local_name])
else:
mem[domain_name].add(local_name)
result = 0
for _, lns in mem.items():
result += len(lns)
return result | unique-email-addresses | Python - Set || Dictionary | ankush-sinha | 0 | 43 | unique email addresses | 929 | 0.672 | Easy | 15,061 |
https://leetcode.com/problems/unique-email-addresses/discuss/1378771/Python3-dollarolution | class Solution:
def numUniqueEmails(self, emails: List[str]) -> int:
v = []
for i in emails:
x = i.index('@')
s, y = i[0:x], i[x:]
s = s.replace('.','')
if '+' in s:
j = 0
while j < len(s):
if s[j] == '+':
s = s[0:j]
break
j += 1
v.append(s+y)
return(len(set(v))) | unique-email-addresses | Python3 $olution | AakRay | 0 | 112 | unique email addresses | 929 | 0.672 | Easy | 15,062 |
https://leetcode.com/problems/unique-email-addresses/discuss/1304074/python-easy-to-understand-On | class Solution:
def numUniqueEmails(self, emails: List[str]) -> int:
valid_emails = set()
for email in emails:
first_half , second_half = email.split('@')
if '+' in email:
first_half = first_half[:first_half.index('+')]
first_half = first_half.replace('.','')
unique_email=first_half+'@'+second_half
valid_emails.add(unique_email)
return len(valid_emails) | unique-email-addresses | python easy to understand On | moonchild_1 | 0 | 90 | unique email addresses | 929 | 0.672 | Easy | 15,063 |
https://leetcode.com/problems/unique-email-addresses/discuss/1198889/Easy-Python3-code-using-replace | class Solution:
def numUniqueEmails(self, emails: List[str]) -> int:
l=[]
for i in emails:
x=i[i.index('@'):]
y=i[:i.index('@')]
if('+' in y):
y=y.replace(y[y.index('+'):],'')
if('.' in y):
y=y.replace('.','')
l.append(y+x)
res=len(list(set(l)))
return res | unique-email-addresses | Easy Python3 code using replace | aish_621 | 0 | 89 | unique email addresses | 929 | 0.672 | Easy | 15,064 |
https://leetcode.com/problems/unique-email-addresses/discuss/1146856/Python3-easy-and-short-solution-beats-99.54-in-memory | class Solution:
def numUniqueEmails(self, emails: List[str]) -> int:
ans = []
for i in emails :
local = i[:i.index("@")]
if "." in local :
local = local.replace(".", "")
if "+" in local :
local = local[:local.index("+")]
ans.append(local+i[i.index("@") : ])
return len(set(ans)) | unique-email-addresses | Python3 easy and short solution beats 99.54% in memory | adarsh__kn | 0 | 78 | unique email addresses | 929 | 0.672 | Easy | 15,065 |
https://leetcode.com/problems/unique-email-addresses/discuss/463106/python-easy-solution | class Solution:
def numUniqueEmails(self, emails: List[str]) -> int:
for i in range(len(emails)):
e = emails[i].split('@')
if '+' in e[0]:
e[0] = e[0][:e[0].index('+')]
e[0] = e[0].replace('.', '')
emails[i] = e[0] + "@" + e[1]
return len(set(emails)) | unique-email-addresses | python easy solution | AkshaySunku | 0 | 73 | unique email addresses | 929 | 0.672 | Easy | 15,066 |
https://leetcode.com/problems/unique-email-addresses/discuss/457197/Python3-solution-with-set | class Solution:
def numUniqueEmails(self, emails: List[str]) -> int:
'''
Time: O(n)
Space: O(n)
'''
# a set to store unique email address
res = set()
for email in emails:
local, domain = email.split("@")
new_local_name = ""
for char in local:
# ignored everything after the first plus sign
if char == "+":
break
# ignore periods
if char != ".":
new_local_name += char
# create processed email address and add it into result set
new_email = f"{new_local_name}@{domain}"
res.add(new_email)
return len(res) | unique-email-addresses | Python3 solution with set | nightybear | 0 | 76 | unique email addresses | 929 | 0.672 | Easy | 15,067 |
https://leetcode.com/problems/unique-email-addresses/discuss/442069/python-using-hashing-modification-of-rabin-karp | class Solution:
def numUniqueEmails(self, emails: List[str]) -> int:
M = 3
from collections import defaultdict
unique_list = defaultdict(dict)
unique_emails = 0
for email in emails:
ignore_chara = False
is_domain = False
d_hash = 0
ind_hash = 0
hash_place = 0
for chara in email:
if is_domain:
d_hash += (ord(chara) * pow(M, hash_place))
hash_place += 1
else:
if chara == "@":
is_domain = True
continue
if ignore_chara or chara == ".":
continue
if chara == "+":
ignore_chara = True
continue
ind_hash += (ord(chara) * pow(M, hash_place))
if unique_list.get(d_hash):
if unique_list[d_hash].get(ind_hash):
pass
else:
unique_list[d_hash][ind_hash] = 1
unique_emails += 1
else:
unique_list[d_hash] = {ind_hash:1}
unique_emails += 1
return (unique_emails) | unique-email-addresses | python - using hashing modification of rabin karp | kutta | 0 | 35 | unique email addresses | 929 | 0.672 | Easy | 15,068 |
https://leetcode.com/problems/unique-email-addresses/discuss/368309/Python-faster-than-86-easy-to-understand | class Solution2:
def numUniqueEmails(self, emails):
_dict = {}
for email in emails:
tmp = email.split('@')
local_name = tmp[0].split('+')[0].replace('.', '')
if local_name + '@' + tmp[1] not in _dict.keys():
_dict[local_name+'@'+tmp[1]] = 1
return len(_dict.keys()) | unique-email-addresses | [Python] faster than 86%, easy to understand | kuanc | 0 | 123 | unique email addresses | 929 | 0.672 | Easy | 15,069 |
https://leetcode.com/problems/unique-email-addresses/discuss/352668/Python-3-organized-solution | class Solution:
def clean_local_name(self, local_name):
name = local_name.split("+", 1)[0]
return "".join(name.split('.'))
def clean_email(self, email):
local_name, domain_name = email.split('@')
return f'{self.clean_local_name(local_name)}@{domain_name}'
def numUniqueEmails(self, emails: List[str]) -> int:
cleaned_emails = map(lambda email: self.clean_email(email), emails)
return len(set(cleaned_emails)) | unique-email-addresses | Python 3 organized solution | agconti | 0 | 74 | unique email addresses | 929 | 0.672 | Easy | 15,070 |
https://leetcode.com/problems/unique-email-addresses/discuss/350964/Solution-in-Python-3-(beats-~100)-(five-lines) | class Solution:
def numUniqueEmails(self, emails: List[str]) -> int:
E = set()
for e in emails:
a, p = e.index('@'), e.find('+')
E.add(e[:(a if p == -1 else p)].replace('.','') + e[a:])
return len(E)
- Junaid Mansuri | unique-email-addresses | Solution in Python 3 (beats ~100%) (five lines) | junaidmansuri | 0 | 201 | unique email addresses | 929 | 0.672 | Easy | 15,071 |
https://leetcode.com/problems/unique-email-addresses/discuss/192674/Python-3-Yet-Another-Python-solution | class Solution(object):
def numUniqueEmails(self, emails):
"""
:type emails: List[str]
:rtype: int
"""
results = set()
for email in emails:
local, domain = email.split("@")
local = local[:local.index("+")].replace(".", "") if "+" in local else local.replace(".", "")
results.add(local + "@" + domain)
return len(results) | unique-email-addresses | [Python 3] Yet Another Python solution | flatwhite | 0 | 87 | unique email addresses | 929 | 0.672 | Easy | 15,072 |
https://leetcode.com/problems/binary-subarrays-with-sum/discuss/957414/Python3-hash-O(N) | class Solution:
def numSubarraysWithSum(self, A: List[int], S: int) -> int:
ans = prefix = 0
seen = {0: 1}
for x in A:
prefix += x
ans += seen.get(prefix - S, 0)
seen[prefix] = 1 + seen.get(prefix, 0)
return ans | binary-subarrays-with-sum | [Python3] hash O(N) | ye15 | 2 | 167 | binary subarrays with sum | 930 | 0.511 | Medium | 15,073 |
https://leetcode.com/problems/binary-subarrays-with-sum/discuss/957414/Python3-hash-O(N) | class Solution:
def numSubarraysWithSum(self, A: List[int], S: int) -> int:
ans = ii = rsm = val = 0
for i, x in enumerate(A):
rsm += x
if x: val = 0
while ii <= i and rsm >= S:
if rsm == S: val += 1
rsm -= A[ii]
ii += 1
ans += val
return ans | binary-subarrays-with-sum | [Python3] hash O(N) | ye15 | 2 | 167 | binary subarrays with sum | 930 | 0.511 | Medium | 15,074 |
https://leetcode.com/problems/binary-subarrays-with-sum/discuss/957414/Python3-hash-O(N) | class Solution:
def numSubarraysWithSum(self, A: List[int], S: int) -> int:
ans = ii = rsm = val = 0
for i in range(len(A)):
if A[i]:
rsm += A[i] # range sum
val = 0
while ii < len(A) and rsm == S:
rsm -= A[ii]
ii += 1
val += 1
else: val += int(S == 0) # edge case
ans += val
return ans | binary-subarrays-with-sum | [Python3] hash O(N) | ye15 | 2 | 167 | binary subarrays with sum | 930 | 0.511 | Medium | 15,075 |
https://leetcode.com/problems/binary-subarrays-with-sum/discuss/2808601/Python3-faster-than-99.41-online-submissions-for-Binary-Subarrays-With-Sum. | class Solution:
def numSubarraysWithSum(self, nums: List[int], goal: int) -> int:
presum=ans=0
store={}
for n in nums:
if presum in store: store[presum]+=1 #count all presum and store it
else:store[presum]=1
presum+=n
if presum-goal in store: #check if subarray is available in the store
ans+=store[presum-goal]
return ans | binary-subarrays-with-sum | [Python3] faster than 99.41% online submissions for Binary Subarrays With Sum. | shivpaly2 | 0 | 5 | binary subarrays with sum | 930 | 0.511 | Medium | 15,076 |
https://leetcode.com/problems/binary-subarrays-with-sum/discuss/2771451/Python-Sliding-Window | class Solution:
def numSubarraysWithSum(self, nums: List[int], goal: int) -> int:
def atMostGoal(goal):
if goal < 0:
return 0
res, l, s = 0, 0, 0
for r in range(len(nums)):
s += nums[r]
while s > goal:
s -= nums[l]
l += 1
res += r - l + 1
return res
return atMostGoal(goal) - atMostGoal(goal - 1) | binary-subarrays-with-sum | Python Sliding Window | JSTM2022 | 0 | 4 | binary subarrays with sum | 930 | 0.511 | Medium | 15,077 |
https://leetcode.com/problems/binary-subarrays-with-sum/discuss/2698457/Python-2Sum-%2B-prefix-sum | class Solution:
def numSubarraysWithSum(self, nums: List[int], goal: int) -> int:
for i in range(1, len(nums)):
nums[i] += nums[i - 1]
preSum = [0] + nums
d, count = defaultdict(int), 0
for idx, val in enumerate(preSum):
res = val - goal
if res in d:
count += d[res]
d[val] += 1
return count | binary-subarrays-with-sum | Python 2Sum + prefix sum | JasonDecode | 0 | 4 | binary subarrays with sum | 930 | 0.511 | Medium | 15,078 |
https://leetcode.com/problems/binary-subarrays-with-sum/discuss/2652378/Python-Easy-Solution | class Solution:
def numSubarraysWithSum(self, A: List[int], S: int) -> int:
psum = {0 : 1}
curr_sum = 0
res = 0
for i in A:
# acquire
curr_sum += i
# check
if curr_sum - S in psum.keys():
res += psum.get(curr_sum - S)
psum[curr_sum] = psum.get(curr_sum, 0) + 1
return (res) | binary-subarrays-with-sum | Python Easy Solution | user6770yv | 0 | 17 | binary subarrays with sum | 930 | 0.511 | Medium | 15,079 |
https://leetcode.com/problems/binary-subarrays-with-sum/discuss/1882556/PYTHON-SOL-oror-FAST-oror-EASY-oror-PREFIX-SUM-oror-WELL-EXPLAINED-oror-LINEAR-oror | class Solution:
def numSubarraysWithSum(self, nums: List[int], goal: int) -> int:
# Prefix Sum
# [0 , 0 , 1 , 2 , 2 , 2 , 3 , 3 , 4]
count = {0:1,1:0}
count[nums[0]]+=1
ans = 1 if goal == nums[0] else 0
n = len(nums)
for i in range(1,n):
nums[i] += nums[i-1]
if nums[i]-goal in count:ans+=count[nums[i]-goal]
if nums[i] in count:count[nums[i]]+=1
else:count[nums[i]] = 1
return ans | binary-subarrays-with-sum | PYTHON SOL || FAST || EASY || PREFIX SUM || WELL EXPLAINED || LINEAR || | reaper_27 | 0 | 109 | binary subarrays with sum | 930 | 0.511 | Medium | 15,080 |
https://leetcode.com/problems/binary-subarrays-with-sum/discuss/1829207/Python-easy-to-read-and-understand-or-Subarray-sums-equals-k | class Solution:
def numSubarraysWithSum(self, nums: List[int], goal: int) -> int:
d = {0:1}
sums, ans = 0, 0
for i in range(len(nums)):
sums += nums[i]
if sums-goal in d:
ans += d[sums-goal]
d[sums] = d.get(sums, 0) + 1
return ans | binary-subarrays-with-sum | Python easy to read and understand | Subarray sums equals k | sanial2001 | 0 | 170 | binary subarrays with sum | 930 | 0.511 | Medium | 15,081 |
https://leetcode.com/problems/binary-subarrays-with-sum/discuss/884115/python3-clean-three-pointers-solution | class Solution:
def numSubarraysWithSum(self, A: List[int], S: int) -> int:
i, s, res, count = 0, 0, 0, 1
for j in range(len(A)):
s += A[j]
while i < j and (s > S or A[i] == 0):
if A[i]:
s -= A[i]
count = 1
else:
count += 1
i += 1
if s == S:
res += count
return res | binary-subarrays-with-sum | [python3] clean three pointers solution | hwsbjts | 0 | 174 | binary subarrays with sum | 930 | 0.511 | Medium | 15,082 |
https://leetcode.com/problems/binary-subarrays-with-sum/discuss/1083486/Python-or-Beats-99-TimeMemory-or-Zeros-gap-array-or-Easy-to-understand | class Solution:
def numSubarraysWithSum(self, A: List[int], S: int) -> int:
zgaps,gap = [],0
for v in A:
if v:
zgaps+=[gap]
gap=0
else:
gap+=1
zgaps+=[gap]
if S==0:
return sum([(g*(g+1))//2 for g in zgaps])
return sum([(zgaps[i]+1)*(zgaps[i+S]+1) for i in range(len(zgaps)-S)]) | binary-subarrays-with-sum | Python | Beats 99% Time/Memory | Zeros gap array | Easy to understand | rajatrai1206 | -2 | 162 | binary subarrays with sum | 930 | 0.511 | Medium | 15,083 |
https://leetcode.com/problems/minimum-falling-path-sum/discuss/1628101/Easy-and-Simple-Python-solution | class Solution:
def minFallingPathSum(self, matrix: List[List[int]]) -> int:
r=len(matrix)
c=len(matrix[0])
for i in range(1,r):
for j in range(c):
if j==0:
matrix[i][j]+=min(matrix[i-1][j],matrix[i-1][j+1])
elif j==c-1:
matrix[i][j]+=min(matrix[i-1][j],matrix[i-1][j-1])
else:
matrix[i][j]+=min(matrix[i-1][j],matrix[i-1][j-1],matrix[i-1][j+1])
return min(matrix[r-1]) | minimum-falling-path-sum | Easy and Simple Python solution | diksha_choudhary | 2 | 87 | minimum falling path sum | 931 | 0.685 | Medium | 15,084 |
https://leetcode.com/problems/minimum-falling-path-sum/discuss/572100/Python-O(n2)-sol-with-in-place-dp.-75%2B-w-Visualization | class Solution:
def minFallingPathSum(self, A: List[List[int]]) -> int:
size = len(A)
if size == 1:
# Quick response for single row
return A[0][0]
# Update A[y][x] from second row to last row
for y in range( 1, size):
# sacn each column from 0 to size-1
for x in range( size ):
# find falling path of minimal cost with optimal substructure
min_prev = A[y-1][x]
if x > 0:
min_prev = min( min_prev, A[y-1][x-1] )
if x < size-1:
min_prev = min( min_prev, A[y-1][x+1] )
# update the cost of falling path, destination is [y][x], with optimal substructure
A[y][x] = A[y][x] + min_prev
# the cost of minimum falling path is the minimum value of last row
return min( A[size-1] ) | minimum-falling-path-sum | Python O(n^2) sol with in-place dp. 75%+ [w/ Visualization] | brianchiang_tw | 2 | 138 | minimum falling path sum | 931 | 0.685 | Medium | 15,085 |
https://leetcode.com/problems/minimum-falling-path-sum/discuss/572100/Python-O(n2)-sol-with-in-place-dp.-75%2B-w-Visualization | class Solution:
def minFallingPathSum(self, matrix: List[List[int]]) -> int:
h, w = len(matrix), len(matrix[0])
INF = sys.maxsize
@cache
def dp(row, col):
## Base case: top row
if row == 0 and 0 <= col < w:
return matrix[0][col]
## Base case: out-of boundary
if col < 0 or col >= w:
return INF
## General case: current cost + minimal cost of neighbor on previous row
return matrix[row][col] + min( dp(row-1,col+offset) for offset in (-1, 0, 1) )
# ------------------------------------------------
return min( dp(h-1, col) for col in range(w) ) | minimum-falling-path-sum | Python O(n^2) sol with in-place dp. 75%+ [w/ Visualization] | brianchiang_tw | 2 | 138 | minimum falling path sum | 931 | 0.685 | Medium | 15,086 |
https://leetcode.com/problems/minimum-falling-path-sum/discuss/1520343/Python-In-place-DP%3A-Easy-to-understand-w-Explanation | class Solution:
def minFallingPathSum(self, matrix: List[List[int]]) -> int:
n = len(matrix)
for i in range(1, n): # for each row (skipping the first),
for j in range(n): # process each element in the row
matrix[i][j] += min(matrix[i-1][j], # the minimum sum of the element directly above the current one
matrix[i-1][j-(j>0)], # the minimum sum of the element above and to the left of the current one
matrix[i-1][j+(j<n-1)]) # the minimum sum of the element above and to the right of the current one
return min(matrix[-1]) # get the minimum sum from the last row | minimum-falling-path-sum | Python In-place DP: Easy-to-understand w Explanation | zayne-siew | 1 | 116 | minimum falling path sum | 931 | 0.685 | Medium | 15,087 |
https://leetcode.com/problems/minimum-falling-path-sum/discuss/817588/python3%3A-memoization-into-tabulation | class Solution:
def minFallingPathSum1(self, A: List[List[int]]) -> int:
# dp top down: recursive + memos
# from start column c: dc = [-1, 0, 1], if c + dc valid
# get min of rcrs(r+1, c+dc) iterations
# base case when row == max, return A[r][c]
# O(3^M) time, O(3^M) recursive calls
rows, cols = len(A), len(A[0])
def rcrs(r, c):
if (r,c) in self.cache: return self.cache[(r,c)]
if r == rows-1: return A[r][c]
tmp = float("inf")
for dc in [-1, 0, 1]:
if 0 <= c+dc < cols:
tmp = min(tmp, rcrs(r+1, c+dc))
min_sum = A[r][c] + tmp
self.cache[(r,c)] = min_sum
return min_sum
# setup and recursive calls
self.cache = {}
res = float("inf")
for c in range(cols):
res = min(res, rcrs(0, c))
return res
def minFallingPathSum2(self, A: List[List[int]]) -> int:
# dp bottom up: tabulation (remove the recursive call stack)
# recursive solution builds up from 0,0 to rows, cols
# two for loops, both decreasing => answer min of row 0
# O(MN) time, O(MN) space
rows, cols = len(A), len(A[0])
dp = [[float("inf") for _ in range(rows)] for __ in range(cols)]
dp[rows-1] = A[rows-1]
for r in range(rows-2, -1, -1):
for c in range(cols-1, -1, -1):
tmp = float("inf")
for dc in [-1, 0, 1]:
if 0 <= c+dc < cols:
tmp = min(tmp, dp[r+1][c+dc])
min_sum = A[r][c] + tmp
dp[r][c] = min_sum
return min(dp[0])
def minFallingPathSum(self, A: List[List[int]]) -> int:
# same as above, but just reuse the existing grid!
# O(MN) time, O(1) space
rows, cols = len(A), len(A[0])
for r in range(rows-2, -1, -1):
for c in range(cols-1, -1, -1):
tmp = float("inf")
for dc in [-1, 0, 1]:
if 0 <= c+dc < cols:
tmp = min(tmp, A[r+1][c+dc])
A[r][c] += tmp
return min(A[0]) | minimum-falling-path-sum | python3: memoization into tabulation | dachwadachwa | 1 | 57 | minimum falling path sum | 931 | 0.685 | Medium | 15,088 |
https://leetcode.com/problems/minimum-falling-path-sum/discuss/530115/Python3-dp-O(N2) | class Solution:
def minFallingPathSum(self, A: List[List[int]]) -> int:
n = len(A)
@lru_cache(None)
def fn(i, j):
"""Return the minimum falling path ending at (i, j)."""
if not (0 <= i < n and 0 <= j < n): return inf
if i == 0: return A[i][j]
return min(fn(i-1, j-1), fn(i-1, j), fn(i-1, j+1)) + A[i][j]
return min(fn(n-1, j) for j in range(n)) | minimum-falling-path-sum | [Python3] dp O(N^2) | ye15 | 1 | 78 | minimum falling path sum | 931 | 0.685 | Medium | 15,089 |
https://leetcode.com/problems/minimum-falling-path-sum/discuss/530115/Python3-dp-O(N2) | class Solution:
def minFallingPathSum(self, A: List[List[int]]) -> int:
ans = [0]*len(A)
for i in range(len(A)):
temp = [0]*len(A)
for j in range(len(A)):
temp[j] = A[i][j] + min(ans[max(0, j-1): min(len(A), j+2)])
ans = temp
return min(ans) | minimum-falling-path-sum | [Python3] dp O(N^2) | ye15 | 1 | 78 | minimum falling path sum | 931 | 0.685 | Medium | 15,090 |
https://leetcode.com/problems/minimum-falling-path-sum/discuss/530115/Python3-dp-O(N2) | class Solution:
def minFallingPathSum(self, matrix: List[List[int]]) -> int:
for i in range(1, len(matrix)):
for j in range(len(matrix)):
matrix[i][j] += min(matrix[i-1][max(0, j-1):j+2])
return min(matrix[-1]) | minimum-falling-path-sum | [Python3] dp O(N^2) | ye15 | 1 | 78 | minimum falling path sum | 931 | 0.685 | Medium | 15,091 |
https://leetcode.com/problems/minimum-falling-path-sum/discuss/2844474/Bottom-up-DP-python-simple-solution | class Solution:
def minFallingPathSum(self, matrix: List[List[int]]) -> int:
N = len(matrix)
dp = [[math.inf] * N for _ in range(N)]
for i in range(N):
dp[N - 1][i] = matrix[N - 1][i]
for i in reversed(range(N - 1)):
for j in range(N):
for x, y in [(1, -1), (1, 0), (1, 1)]:
if 0 <= i + x < N and 0 <= j + y < N:
dp[i][j] = min(dp[i][j], matrix[i][j] + dp[i + x][j + y])
return min(dp[0]) | minimum-falling-path-sum | Bottom-up DP / python simple solution | Lara_Craft | 0 | 1 | minimum falling path sum | 931 | 0.685 | Medium | 15,092 |
https://leetcode.com/problems/minimum-falling-path-sum/discuss/2777962/Python-solution | class Solution:
def minFallingPathSum(self, matrix: List[List[int]]) -> int:
row = len(matrix)
col = len(matrix[0])
dp = matrix
for i in range(1, row):
for j in range(col):
if j==0: # leftmost
dp[i][j] += min(dp[i-1][j], dp[i-1][j+1])
elif 0<j<col-1:
dp[i][j] += min(dp[i-1][j-1], dp[i-1][j], dp[i-1][j+1])
elif j==col-1: # rightmost
dp[i][j] += min(dp[i-1][j-1], dp[i-1][j])
res = []
for j in range(col):
res.append(dp[row-1][j])
return min(res) | minimum-falling-path-sum | Python solution | gcheng81 | 0 | 2 | minimum falling path sum | 931 | 0.685 | Medium | 15,093 |
https://leetcode.com/problems/minimum-falling-path-sum/discuss/2769771/Pythonor-simple-solution | class Solution:
def minFallingPathSum(self, matrix: List[List[int]]) -> int:
n = len(matrix)
if n == 1:
return matrix[0][0]
sums = [i for i in matrix[0]]
sums1 = [0 for _ in range(n)]
for p in range(1, n):
mins = min(sums[0],sums[1])
sums1[0] = mins+matrix[p][0]
for q in range(1,n-1):
mins = min(sums[q], sums[q+1])
mins = min(mins, sums[q-1])
sums1[q] = mins+matrix[p][q]
mins = min(sums[n-2], sums[n-1])
sums1[n-1] = mins + matrix[p][n-1]
sums = [i for i in sums1]
print(sums)
mins = sums[0]
for i in sums:
if i < mins:
mins = i
return mins | minimum-falling-path-sum | Python| simple solution | lucy_sea | 0 | 3 | minimum falling path sum | 931 | 0.685 | Medium | 15,094 |
https://leetcode.com/problems/minimum-falling-path-sum/discuss/2769063/python3-oror-recursive-oror-memoization-approach | class Solution:
def minFallingPathSum(self, matrix: List[List[int]]) -> int:
n=len(matrix)
dp=[[-1]*n for i in range(n)]
def f(i,j):
if i>n-1 or j>n-1 or j<0:
return float("inf")
if i==n-1:
return matrix[i][j]
if dp[i][j]!=-1:
return dp[i][j]
a=matrix[i][j]+f(i+1,j-1)
b=matrix[i][j]+f(i+1,j)
c=matrix[i][j]+f(i+1,j+1)
dp[i][j]=min(a,b,c)
return min(a,b,c)
minPathSum=float("inf")
for i in range(n):
minPathSum=min(minPathSum,f(0,i))
return minPathSum | minimum-falling-path-sum | python3 || recursive || memoization approach | _soninirav | 0 | 3 | minimum falling path sum | 931 | 0.685 | Medium | 15,095 |
https://leetcode.com/problems/minimum-falling-path-sum/discuss/2764230/Python-Dynamic-Programming-Solution-with-Memory | class Solution:
def minFallingPathSum(self, matrix: List[List[int]]) -> int:
m = len(matrix)
n = len(matrix[0])
memo = [[666 for _ in range(n)] for _ in range(m)]
def DP(i, j):
if not 0<=i<m or not 0<=j<n:
return 9999
if i == 0:
memo[0][j] = matrix[0][j]
return matrix[0][j]
if memo[i][j] != 666:
return memo[i][j]
memo[i][j] = matrix[i][j] + min(DP(i-1, j-1), DP(i-1, j), DP(i-1, j+1))
return memo[i][j]
result = float('inf')
for j in range(n):
result = min(result, DP(m-1, j))
return result | minimum-falling-path-sum | Python Dynamic Programming Solution with Memory | Rui_Liu_Rachel | 0 | 4 | minimum falling path sum | 931 | 0.685 | Medium | 15,096 |
https://leetcode.com/problems/minimum-falling-path-sum/discuss/2717303/Python-DP-Solutionoror-Memoization-oror-Tabulation-oror-Space-Optimization | class Solution:
def minFallingPathSum(self, matrix: List[List[int]]) -> int:
r = len(matrix)
c = len(matrix[0])
# SPACE OPTIMIZATION
if r == 1:
return min(matrix[0])
next_row = matrix[r-1]
current_row = [0 for j in range(c)]
for i in range(r-2, -1, -1):
current_row = [0 for j in range(c)]
for j in range(0, c):
x = float('inf')
y = float('inf')
z = float('inf')
if j > 0:
x = next_row[j-1]
y = next_row[j]
if j+1 < c:
z = next_row[j+1]
current_row[j] = matrix[i][j] + min(x, y, z)
next_row = current_row
return min(current_row)
# TABULATION
dp = [[0 for j in range(c)] for i in range(r)]
dp[r-1] = matrix[r-1]
for i in range(r-2, -1, -1):
for j in range(0, c):
x = float('inf')
y = float('inf')
z = float('inf')
if j > 0:
x = dp[i+1][j-1]
y = dp[i+1][j]
if j+1 < c:
z = dp[i+1][j+1]
dp[i][j] = matrix[i][j] + min(x, y, z)
return min(dp[0])
# MEMOIZATION
dp = [[-1 for j in range(c+1)] for i in range(r+1)]
def helper(i, j):
nonlocal r, c
if i == r-1:
return matrix[i][j]
if dp[i][j] != -1:
return dp[i][j]
if j > 0:
x = matrix[i][j] + helper(i+1, j-1)
else:
x = float('inf')
y = matrix[i][j] + helper(i+1, j)
if j+1 < c:
z = matrix[i][j] + helper(i+1, j+1)
else:
z = float('inf')
dp[i][j] = min(x, y, z)
return min(x, y, z)
ans = float('inf')
for j in range(c):
k = helper(0, j)
# print(k)
ans = min(ans, k)
return ans | minimum-falling-path-sum | Python DP Solution|| Memoization || Tabulation || Space Optimization | shreya_pattewar | 0 | 11 | minimum falling path sum | 931 | 0.685 | Medium | 15,097 |
https://leetcode.com/problems/minimum-falling-path-sum/discuss/2715741/Python-or-Simple-2-d-dynamic-programming-solution | class Solution:
def minFallingPathSum(self, m: List[List[int]]) -> int:
dp = [[0 for _ in range(len(m))] for _ in range(len(m))]
# Initial states for first row
for i in range(len(m)):
dp[0][i] = m[0][i]
for i in range(1, len(m)):
for j in range(len(m)):
# To calculate value we choose minimum dp out of three options and add value from matrix
dp[i][j] = min([dp[i - 1][j], dp[i - 1][max(j - 1, 0)], dp[i - 1][min(j + 1, len(m) - 1)]]) + m[i][j]
# Finally return minimum sum from last row
return min(dp[-1]) | minimum-falling-path-sum | Python | Simple 2-d dynamic programming solution | LordVader1 | 0 | 6 | minimum falling path sum | 931 | 0.685 | Medium | 15,098 |
https://leetcode.com/problems/minimum-falling-path-sum/discuss/2688892/Python-oror-Easy-oror-O(n2)-oror-No-Extra-Space | class Solution:
def minFallingPathSum(self, matrix: List[List[int]]) -> int:
n = len(matrix)
for i in range(n-2, -1, -1):
matrix[i][0] += min(matrix[i+1][0], matrix[i+1][1])
for j in range(1, n-1):
matrix[i][j] += min(matrix[i+1][j], matrix[i+1][j+1], matrix[i+1][j-1])
matrix[i][n-1] += min(matrix[i+1][n-1], matrix[i+1][n-2])
return min(matrix[0]) | minimum-falling-path-sum | Python || Easy || O(n^2) || No Extra Space | vanshkela | 0 | 3 | minimum falling path sum | 931 | 0.685 | Medium | 15,099 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.