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/greatest-common-divisor-of-strings/discuss/1832646/Python-Solution | class Solution:
def gcdOfStrings(self, str1: str, str2: str) -> str:
l1 = len(str1)
l2 = len(str2)
l = min(l1,l2)
for i in range(l,0,-1):
if l1 % i == 0 and l2 % i == 0:
n1 = (l1//i)
n2 = (l2//i)
if str1[0:i] * n1 == str1 and str1[0:i] * n2 == str2:
return str1[0:i]
elif str2[0:i] * n1 == str1 and str2[0:i] * n2 == str2:
return str2[0:i]
break
return "" | greatest-common-divisor-of-strings | Python Solution | MS1301 | 0 | 362 | greatest common divisor of strings | 1,071 | 0.511 | Easy | 17,200 |
https://leetcode.com/problems/greatest-common-divisor-of-strings/discuss/638335/Python-20ms-beat-98-solution-euclidean-algorithm | class Solution:
def gcdOfStrings(self, s1: str, s2: str) -> str:
n = len(s1)
m = len(s2)
if n < m:
n, m = m, n
s1, s2 = s2, s1
print(s1, s2)
if m <= 1:
return s1
i = -1
while i <= n//m:
i += 1
if s2 != s1[i*m:(i+1)*m]:
break
if i == 0:
return ''
s1, s2 = s2, s1[i*m:]
return self.gcdOfStrings(s1, s2) | greatest-common-divisor-of-strings | Python 20ms beat 98% solution euclidean algorithm | usualwitch | 0 | 446 | greatest common divisor of strings | 1,071 | 0.511 | Easy | 17,201 |
https://leetcode.com/problems/greatest-common-divisor-of-strings/discuss/622654/Intuitive-approach-by-pick-up-smaller-string-and-trim-it-down-to-last-character-to-look-for-GCD | class Solution:
def gcdOfStrings(self, str1: str, str2: str) -> str:
# 1) Look for shorter string
if len(str2) < len(str1):
tstr = str2
else:
tstr = str1
# 2) Cut it down to last character to look for GCD
str1_size = len(str1)
str2_size = len(str2)
while tstr:
tstr_size = len(tstr)
if str1_size % tstr_size == 0 and str2_size % tstr_size == 0:
if tstr * (str1_size // tstr_size) == str1 and \
tstr * (str2_size // tstr_size) == str2:
return tstr
tstr = tstr[:-1]
return '' | greatest-common-divisor-of-strings | Intuitive approach by pick up smaller string and trim it down to last character to look for GCD | puremonkey2001 | 0 | 148 | greatest common divisor of strings | 1,071 | 0.511 | Easy | 17,202 |
https://leetcode.com/problems/greatest-common-divisor-of-strings/discuss/474563/Python3-90.78-(24-ms)100.00-(12.7-MB) | class Solution:
def gcdOfStrings(self, str1: str, str2: str) -> str:
strings = [str1, str2] if len(str1) > len(str2) else [str2, str1]
for length in range(len(strings[1]), 0, -1):
if (not len(strings[0]) % length and not len(strings[1]) % length):
substring = strings[1][:length]
number_substrings_1 = len(strings[0]) // length
number_substrings_2 = len(strings[1]) // length
if (number_substrings_1 == strings[0].count(substring) and
number_substrings_2 == strings[1].count(substring)):
return substring
return "" | greatest-common-divisor-of-strings | Python3 90.78% (24 ms)/100.00% (12.7 MB) | numiek_p | 0 | 177 | greatest common divisor of strings | 1,071 | 0.511 | Easy | 17,203 |
https://leetcode.com/problems/flip-columns-for-maximum-number-of-equal-rows/discuss/1440662/97-faster-oror-Well-Explained-with-example-oror-Easy-Approach | class Solution:
def maxEqualRowsAfterFlips(self, matrix: List[List[int]]) -> int:
dic = defaultdict(int)
for row in matrix:
local=[]
for c in row:
local.append(c^row[0])
dic[tuple(local)]+=1
return max(dic.values()) | flip-columns-for-maximum-number-of-equal-rows | 🐍 97% faster || Well-Explained with example || Easy-Approach 📌📌 | abhi9Rai | 1 | 199 | flip columns for maximum number of equal rows | 1,072 | 0.63 | Medium | 17,204 |
https://leetcode.com/problems/flip-columns-for-maximum-number-of-equal-rows/discuss/1412756/Python3-solution-beats-90 | class Solution:
def maxEqualRowsAfterFlips(self, matrix: List[List[int]]) -> int:
d = {}
for row in matrix:
if row[0] == 0:
d[tuple(row)] = d.get(tuple(row),0)+1
else:
x = []
for i in row:
if i == 0:
x.append(1)
else:
x.append(0)
d[tuple(x)] = d.get(tuple(x),0)+1
return max(d.values()) | flip-columns-for-maximum-number-of-equal-rows | Python3 solution beats 90% | EklavyaJoshi | 0 | 85 | flip columns for maximum number of equal rows | 1,072 | 0.63 | Medium | 17,205 |
https://leetcode.com/problems/flip-columns-for-maximum-number-of-equal-rows/discuss/1015726/Python3-score-each-row | class Solution:
def maxEqualRowsAfterFlips(self, matrix: List[List[int]]) -> int:
m, n = len(matrix), len(matrix[0]) # dimensions
score = [0]*m
for j in range(1, n):
for i in range(m):
score[i] *= 2
if matrix[i][0] != matrix[i][j]: score[i] += 1
freq = {}
for x in score: freq[x] = 1 + freq.get(x, 0)
return max(freq.values()) | flip-columns-for-maximum-number-of-equal-rows | [Python3] score each row | ye15 | 0 | 113 | flip columns for maximum number of equal rows | 1,072 | 0.63 | Medium | 17,206 |
https://leetcode.com/problems/flip-columns-for-maximum-number-of-equal-rows/discuss/953007/Intuitive-approach-by-grouping-row-with-its-complementary-row-together | class Solution:
def maxEqualRowsAfterFlips(self, matrix: List[List[int]]) -> int:
def flip(alist):
olist = []
for v in alist:
olist.append(0 if v else 1)
return tuple(olist)
complementary_row_dict = {}
for row in matrix:
if not row[0]:
row = flip(row)
else:
row = tuple(row)
complementary_row_dict[row] = complementary_row_dict.get(row, 0) + 1
return max(complementary_row_dict.values()) | flip-columns-for-maximum-number-of-equal-rows | Intuitive approach by grouping row with its complementary row together | puremonkey2001 | 0 | 82 | flip columns for maximum number of equal rows | 1,072 | 0.63 | Medium | 17,207 |
https://leetcode.com/problems/flip-columns-for-maximum-number-of-equal-rows/discuss/1477844/Python-3-or-Bitmask-Clean-O(M*N)-or-Explanation | class Solution:
def maxEqualRowsAfterFlips(self, matrix: List[List[int]]) -> int:
d = collections.defaultdict(int) # hashmap for counting
m, n = len(matrix), len(matrix[0])
for i in range(m):
reverse = not matrix[i][0] # decide whether need to reverse bit
cur = ''.join(['0' if matrix[i][j] ^ reverse else '1' for j in range(n)]) # see below solution for expanded code
d[cur] += 1 # count frequency
return max(d.values()) | flip-columns-for-maximum-number-of-equal-rows | Python 3 | Bitmask, Clean, O(M*N) | Explanation | idontknoooo | -1 | 168 | flip columns for maximum number of equal rows | 1,072 | 0.63 | Medium | 17,208 |
https://leetcode.com/problems/flip-columns-for-maximum-number-of-equal-rows/discuss/1477844/Python-3-or-Bitmask-Clean-O(M*N)-or-Explanation | class Solution:
def maxEqualRowsAfterFlips(self, matrix: List[List[int]]) -> int:
d = collections.defaultdict(int) # hashmap for counting
m, n = len(matrix), len(matrix[0])
for i in range(m):
reverse = not matrix[i][0] # decide whether need to reverse bit
cur = '' # expanded version of above 1 liner
for j in range(n):
if reverse:
cur += '0' if matrix[i][j] else '1'
else:
cur += '1' if matrix[i][j] else '0'
d[cur] += 1 # count frequency
return max(d.values()) | flip-columns-for-maximum-number-of-equal-rows | Python 3 | Bitmask, Clean, O(M*N) | Explanation | idontknoooo | -1 | 168 | flip columns for maximum number of equal rows | 1,072 | 0.63 | Medium | 17,209 |
https://leetcode.com/problems/adding-two-negabinary-numbers/discuss/1384126/Python-3-or-Math-Two-Pointers-or-Explanation | class Solution:
def addNegabinary(self, arr1: List[int], arr2: List[int]) -> List[int]:
ans = list()
m, n = len(arr1), len(arr2)
i, j = m-1, n-1
def add(a, b): # A helper function to add -2 based numbers
if a == 1 and b == 1:
cur, carry = 0, -1
elif (a == -1 and b == 0) or (a == 0 and b == -1):
cur = carry = 1
else:
cur, carry = a+b, 0
return cur, carry # Return current value and carry
carry = 0
while i >= 0 or j >= 0: # Two pointers from right side
cur, carry_1, carry_2 = carry, 0, 0
if i >= 0:
cur, carry_1 = add(cur, arr1[i])
if j >= 0:
cur, carry_2 = add(cur, arr2[j])
carry = carry_1 + carry_2
ans.append(cur)
i, j = i-1, j-1
ans = [1,1] + ans[::-1] if carry == -1 else ans[::-1] # Add [1, 1] if there is a carry -1 leftover
for i, v in enumerate(ans): # Remove leading zero and return
if v == 1:
return ans[i:]
else:
return [0] | adding-two-negabinary-numbers | Python 3 | Math, Two Pointers | Explanation | idontknoooo | 2 | 558 | adding two negabinary numbers | 1,073 | 0.364 | Medium | 17,210 |
https://leetcode.com/problems/adding-two-negabinary-numbers/discuss/2242476/Python-3-simple-solution-with-explanation | class Solution(object):
def addNegabinary(self, arr1, arr2):
"""
to add two "-2" based numbers up
we can simply do the calculation per bit
and map out all the possible cases with carry
in "-2" based numbers, because the values of bits
alter between negative and positive, so the carry/borrow
will be reversed to -1/1
so when the sum on one bit >= 2, the carry can be -1 to
the higher bit
and if the higher bit with carry sum to -1, it needs to
borrow from the even higher bit, resulting in a carry of 1
# 12 possible cases in 5 categories in total
# case (| case) -> bit sum -> (bit, carry)
# 0,0,-1 -> -1 -> (1, 1)
# 0,0,0 | 1,0,-1 | 0,1,-1 -> 0 -> (0, 0)
# 0,0,1 | 1,0,0 | 0,1,0 | 1,1,-1 -> 1 -> (1, 0)
# 1,1,0 | 1,0,1 | 0,1,1 -> 2 -> (0, -1)
# 1,1,1 -> 3 -> (1, -1)
the 2nd catogery can produce leading zeros
"""
CASE_MAPS = {
-1: (1, 1),
0: (0, 0),
1: (1, 0),
2: (0, -1),
3: (1, -1),
}
res, carry = [], 0
while arr1 or arr2 or carry:
bit = carry
if arr1: bit += arr1.pop()
if arr2: bit += arr2.pop()
bit, carry = CASE_MAPS[bit]
res += [bit]
while len(res) > 1 and res[-1] == 0:
res.pop()
return res[::-1] | adding-two-negabinary-numbers | Python 3 simple solution with explanation | zhenyulin | 0 | 97 | adding two negabinary numbers | 1,073 | 0.364 | Medium | 17,211 |
https://leetcode.com/problems/adding-two-negabinary-numbers/discuss/2106647/PYTHON-SOL-or-SIMPLE-or-EXPLAINED-or-FAST-or-ITERATION-or | class Solution:
def addNegabinary(self, arr1: List[int], arr2: List[int]) -> List[int]:
# find the sum of both binary number in decimal form
ans = 0
start = 1
for i in arr1[::-1]:
if i == 1:ans += start
start *= -2
start = 1
for i in arr2[::-1]:
if i == 1:ans += start
start *= -2
res = []
# convert decimal to negative 2 base
while ans:
rem = ans % -2
ans = ans // -2
if rem < 0: ans += 1
res.append(abs(rem))
res = res[::-1]
`` return res if res != [] else [0] | adding-two-negabinary-numbers | PYTHON SOL | SIMPLE | EXPLAINED | FAST | ITERATION | | reaper_27 | 0 | 134 | adding two negabinary numbers | 1,073 | 0.364 | Medium | 17,212 |
https://leetcode.com/problems/adding-two-negabinary-numbers/discuss/1015483/Python3-directly-and-indirectly | class Solution:
def addNegabinary(self, arr1: List[int], arr2: List[int]) -> List[int]:
ans = []
carry, i1, i2 = 0, len(arr1), len(arr2)
while i1 or i2 or carry:
if i1: carry += arr1[(i1 := i1-1)]
if i2: carry += arr2[(i2 := i2-1)]
ans.append(carry & 1)
carry = -(carry >> 1)
while ans and not ans[-1]: ans.pop() # remove leading 0s
return ans[::-1] or [0] | adding-two-negabinary-numbers | [Python3] directly & indirectly | ye15 | 0 | 149 | adding two negabinary numbers | 1,073 | 0.364 | Medium | 17,213 |
https://leetcode.com/problems/adding-two-negabinary-numbers/discuss/1015483/Python3-directly-and-indirectly | class Solution:
def addNegabinary(self, arr1: List[int], arr2: List[int]) -> List[int]:
x = reduce(lambda x, y: x*(-2) + y, arr1)
x += reduce(lambda x, y: x*(-2) + y, arr2)
ans = []
while x:
ans.append(x & 1)
x = -(x >> 1)
return ans[::-1] or [0] | adding-two-negabinary-numbers | [Python3] directly & indirectly | ye15 | 0 | 149 | adding two negabinary numbers | 1,073 | 0.364 | Medium | 17,214 |
https://leetcode.com/problems/number-of-submatrices-that-sum-to-target/discuss/2118388/or-PYTHON-SOL-or-EASY-or-EXPLAINED-or-VERY-SIMPLE-or-COMMENTED-or | class Solution:
def numSubmatrixSumTarget(self, matrix: List[List[int]], target: int) -> int:
# find the rows and columns of the matrix
n,m = len(matrix) , len(matrix[0])
# find the prefix sum for each row
for i in range(n):
for j in range(1,m):
matrix[i][j] += matrix[i][j-1]
ans = 0
# fix the left boundary of the column
for start in range(m):
# fix the right boundary of the column
for end in range(start,m):
# a dictionary to map data
d = defaultdict(lambda:0)
d[0] = 1
summ = 0
# now we do check at each row
for i in range(n):
curr = matrix[i][end]
if start > 0: curr -= matrix[i][start-1]
summ += curr
ans += d[summ - target]
d[summ] += 1
return ans | number-of-submatrices-that-sum-to-target | | PYTHON SOL | EASY | EXPLAINED | VERY SIMPLE | COMMENTED | | reaper_27 | 1 | 203 | number of submatrices that sum to target | 1,074 | 0.698 | Hard | 17,215 |
https://leetcode.com/problems/number-of-submatrices-that-sum-to-target/discuss/1165850/Python3-prefix-sum | class Solution:
def numSubmatrixSumTarget(self, matrix: List[List[int]], target: int) -> int:
m, n = len(matrix), len(matrix[0]) # dimensions
ans = 0
freq = defaultdict(int)
prefix = [[0]*(n+1) for _ in range(m+1)]
for i in range(m):
for j in range(n):
prefix[i+1][j+1] = matrix[i][j] + prefix[i+1][j] + prefix[i][j+1] - prefix[i][j]
for jj in range(-1, j):
diff = prefix[i+1][j+1] - prefix[i+1][jj+1]
ans += freq[jj, j, diff - target]
if diff == target: ans += 1
freq[jj, j, diff] += 1
return ans | number-of-submatrices-that-sum-to-target | [Python3] prefix sum | ye15 | 1 | 135 | number of submatrices that sum to target | 1,074 | 0.698 | Hard | 17,216 |
https://leetcode.com/problems/number-of-submatrices-that-sum-to-target/discuss/1165850/Python3-prefix-sum | class Solution:
def numSubmatrixSumTarget(self, matrix: List[List[int]], target: int) -> int:
ans = 0
m, n = len(matrix), len(matrix[0]) # dimensions
prefix = [[0]*(n+1) for _ in range(m+1)]
for i in range(m):
for j in range(n):
prefix[i+1][j+1] = matrix[i][j] + prefix[i+1][j] + prefix[i][j+1] - prefix[i][j]
for ii in range(i+1):
freq = {0: 1}
for j in range(n):
diff = prefix[i+1][j+1] - prefix[ii][j+1]
ans += freq.get(diff - target, 0)
freq[diff] = 1 + freq.get(diff, 0)
return ans | number-of-submatrices-that-sum-to-target | [Python3] prefix sum | ye15 | 1 | 135 | number of submatrices that sum to target | 1,074 | 0.698 | Hard | 17,217 |
https://leetcode.com/problems/number-of-submatrices-that-sum-to-target/discuss/2839842/Prefix-Sum-sub-array-with-sub-array-sums-to-target-as-a-sub-routine-oror-deep-explanation | class Solution:
def numSubmatrixSumTarget(self, matrix: List[List[int]], target: int) -> int:
# get your rows and cols of the matrix
rows = len(matrix)
cols = len(matrix[0])
# check for transpose needs
if rows > (cols*cols) :
temp = [[matrix[j][i] for j in range(len(matrix))] for i in range(len(matrix[0]))]
matrix = temp
rows = len(matrix)
cols = len(matrix[0])
# matrix prefix sums of size rows + 1 x cols + 1
# outside row and cols will be zero. This allows for augment to consider those cases that would fall outside our array set up
matrix_prefix_sums = [[0 for _ in range(cols + 1)] for _ in range(rows+1)]
# loop your matrix to get your prefix sums
for row in range(1, rows+1) :
for col in range(1, cols+1) :
# each prefix sum is the sum of value up, value back, and value current (using 1 offset) and value up and back
value_up = matrix_prefix_sums[row-1][col]
value_back = matrix_prefix_sums[row][col-1]
value_up_and_back = matrix_prefix_sums[row-1][col-1]
matrix_prefix_sums[row][col] = matrix[row-1][col-1] + value_up + value_back - value_up_and_back
# end for loop
# final answer format
number_of_sub_arrays = 0
# need to loop again, this time considering our sub array of prefixes as a sub array sum instance problem
# for the sub array sum equal to target, this is a combination of a cumulative sum with a hashmap
# the hashmap tracks the number of sub arrays up to this point that have been of value target
# we let our hashmap row index 1 loop all of our rows for our prefix sums considerations
# incidentally, for a standard one line array, we can use much of lines 29-51
# we'd just really need to implement our sum outside the col loop as zero and start with our answers above the col loop
# then you could just add the sum as you go along instead of switching to a new prefix sum
for row_index_1 in range(1, rows+1) :
# our second hashmap row index 2 will loop from row index 1 to rows + 1 due to that augment at the top
for row_index_2 in range(row_index_1, rows+1) :
# at each instance of our sub array of prefix sums, we need a hashmap
# dictionary originally only containing 0 and 1
prefix_subarray_sums = {0:1}
# now we can loop over the column indices in our prefix sums
for col_index in range(1, cols+1) :
# get our stored prefix sum with offset for the row index 1 valuation. This is why we want bounding 0 lines
# if we end up at a spot where the row back is out of bounds, that's a zero value
# but that's okay, as that's what we used already!
prefix_sum = matrix_prefix_sums[row_index_2][col_index] - matrix_prefix_sums[row_index_1 - 1][col_index]
# check if we have already found this valuation
# we can do this with a hash key equal to our prefix_sum - target
hash_key = prefix_sum - target
# if we have found the value of prefix_sum - target in our prefix_subarray_sums, we can increment our answer by that
if hash_key in prefix_subarray_sums :
number_of_sub_arrays += prefix_subarray_sums[hash_key]
# if we have never had this prefix sum, add it as a new key
if prefix_sum not in prefix_subarray_sums :
prefix_subarray_sums[prefix_sum] = 0
# increment our prefix sub array sum by 1 at this prefix sum as it has been reached now
# each new time it is reached, we are noting the number of times this sum occurred on our path over the columns
# now, if we end up having prefix_sum - target in their, we either have a value that is 0
# or we have a value that is prefix sum a - target = prefix sum b
# this means we have a sub array combination that would work, and why we update on line 41 for our answer
prefix_subarray_sums[prefix_sum] += 1
# end col for loop
# end row 2 for loop
# end row 1 for loop
# return the number of sub arrays found
return number_of_sub_arrays | number-of-submatrices-that-sum-to-target | Prefix-Sum sub array with sub array sums to target as a sub routine || deep explanation | laichbr | 0 | 1 | number of submatrices that sum to target | 1,074 | 0.698 | Hard | 17,218 |
https://leetcode.com/problems/number-of-submatrices-that-sum-to-target/discuss/2512026/Python-easy-to-read-and-understand-or-prefix-sum | class Solution:
def solve(self, matrix, target):
m, n = len(matrix), len(matrix[0])
t = [[0 for _ in range(n+1)] for _ in range(m+1)]
for i in range(1, m+1):
for j in range(1, n+1):
t[i][j] = t[i][j-1] + matrix[i-1][j-1]
ans = 0
for j in range(1, n+1):
for k in range(j, n+1):
d = {0:1}
sums = 0
for i in range(1, m+1):
sums += t[i][k] - t[i][j-1]
ans += d.get(sums-target, 0)
d[sums] = d.get(sums, 0) + 1
return ans | number-of-submatrices-that-sum-to-target | Python easy to read and understand | prefix-sum | sanial2001 | 0 | 66 | number of submatrices that sum to target | 1,074 | 0.698 | Hard | 17,219 |
https://leetcode.com/problems/number-of-submatrices-that-sum-to-target/discuss/2305230/Python-T%3A-767-ms-oror-Memory%3A-15.1-MB-oror-Easy-Understanding | class Solution:
def numSubmatrixSumTarget(self, matrix: List[List[int]], target: int) -> int:
if len(matrix) == 0: return 0
rows = len(matrix)
cols = len(matrix[0])
count = 0
for i in range(rows):
for j in range(1,cols):
matrix[i][j] += matrix[i][j-1]
for j in range(cols):
for cj in range(j,cols):
dict = {}
sum = 0
dict[0] = 1
for i in range(rows):
sum += matrix[i][cj] - (matrix[i][j-1] if j > 0 else 0)
count += dict.get(sum-target, 0)
dict[sum] = dict.get(sum, 0) + 1
return count | number-of-submatrices-that-sum-to-target | [Python] T: 767 ms || Memory: 15.1 MB || Easy Understanding | Buntynara | 0 | 27 | number of submatrices that sum to target | 1,074 | 0.698 | Hard | 17,220 |
https://leetcode.com/problems/number-of-submatrices-that-sum-to-target/discuss/2298126/100-C%2B%2B-Java-and-Python-Optimal-Solution | class Solution:
def numSubmatrixSumTarget(self, matrix: List[List[int]], target: int) -> int:
m = len(matrix)
n = len(matrix[0])
ans = 0
# transfer each row of matrix to prefix sum
for row in matrix:
for i in range(1, n):
row[i] += row[i - 1]
for baseCol in range(n):
for j in range(baseCol, n):
prefixCount = Counter({0: 1})
summ = 0
for i in range(m):
if baseCol > 0:
summ -= matrix[i][baseCol - 1]
summ += matrix[i][j]
ans += prefixCount[summ - target]
prefixCount[summ] += 1
return ans | number-of-submatrices-that-sum-to-target | ✔️ 100% - C++, Java and Python Optimal Solution | Theashishgavade | 0 | 59 | number of submatrices that sum to target | 1,074 | 0.698 | Hard | 17,221 |
https://leetcode.com/problems/number-of-submatrices-that-sum-to-target/discuss/2297729/easy-to-understand-Number-of-Submatrices-That-Sum-to-Target-SOLUTION-oror-98-faster-oror-efficient | class Solution:
def numSubmatrixSumTarget(self, matrix: List[List[int]], target: int) -> int:
if not matrix:
return 0
def num_for_one_row(nums):
prev = {}
prev[0] = 1
cur_sum = 0
ans = 0
for num in nums:
cur_sum += num
if cur_sum - target in prev:
ans += prev[cur_sum - target]
if cur_sum not in prev:
prev[cur_sum] = 1
else:
prev[cur_sum] += 1
return ans
res = 0
m = len(matrix)
n = len(matrix[0])
for i in range(m):
nums = [0]*n
for j in range(i,m):
for k in range(n):
nums[k]+=matrix[j][k]
res += num_for_one_row(nums)
return res | number-of-submatrices-that-sum-to-target | easy to understand - Number of Submatrices That Sum to Target SOLUTION || 98% faster || efficient | adithya_s_k | 0 | 59 | number of submatrices that sum to target | 1,074 | 0.698 | Hard | 17,222 |
https://leetcode.com/problems/occurrences-after-bigram/discuss/1443810/Using-stack-for-words-93-speed | class Solution:
def findOcurrences(self, text: str, first: str, second: str) -> List[str]:
ans, stack = [], []
for w in text.split():
if len(stack) > 1 and stack[-2] == first and stack[-1] == second:
ans.append(w)
stack.append(w)
return ans | occurrences-after-bigram | Using stack for words, 93% speed | EvgenySH | 2 | 99 | occurrences after bigram | 1,078 | 0.638 | Easy | 17,223 |
https://leetcode.com/problems/occurrences-after-bigram/discuss/2334555/Python3-Runtime%3A-43ms-59.41-oror-Memory%3A-13.9mb-73.25-O(n)-oror-O(1) | class Solution:
# Runtime: 43ms 59.41% || Memory: 13.9mb 73.25%
# O(n) || O(1) if you dont count return result as a extra space
def findOcurrences(self, string: str, first: str, second: str) -> List[str]:
result = []
string = string.split()
for i in range(len(string) - 2):
currStr = string[i]
secNxtStr = string[i + 1]
thirdNxtStr = string[i + 2]
if currStr == first and secNxtStr == second:
result.append(thirdNxtStr)
return result | occurrences-after-bigram | Python3 Runtime: 43ms 59.41% || Memory: 13.9mb 73.25% O(n) || O(1) | arshergon | 1 | 49 | occurrences after bigram | 1,078 | 0.638 | Easy | 17,224 |
https://leetcode.com/problems/occurrences-after-bigram/discuss/882631/Python-simple-solution | class Solution:
def findOcurrences(self, text: str, first: str, second: str) -> List[str]:
result = []
words = text.split()
for i in range(2, len(words)):
if words[i-2] == first and words[i-1] == second:
result.append(words[i])
return result | occurrences-after-bigram | Python simple solution | stom1407 | 1 | 73 | occurrences after bigram | 1,078 | 0.638 | Easy | 17,225 |
https://leetcode.com/problems/occurrences-after-bigram/discuss/2466681/PYTHON-Easy-solution-with-List-Comprehension-(Feedbacks-are-appreciated) | class Solution:
def findOcurrences(self, text: str, first: str, second: str) -> List[str]:
word_list = text.split()
return [word_list[sec+1] for sec, word in enumerate(word_list[:-2], 1) if word == first and word_list[sec] == second] | occurrences-after-bigram | [PYTHON] Easy solution with List Comprehension (Feedbacks are appreciated) | Eli47 | 0 | 26 | occurrences after bigram | 1,078 | 0.638 | Easy | 17,226 |
https://leetcode.com/problems/occurrences-after-bigram/discuss/2121807/Python-simple-solution | class Solution:
def findOcurrences(self, text: str, first: str, second: str) -> List[str]:
arr = text.split()
if len(arr) < 3: return []
ans = []
for i in range(2, len(arr)):
if arr[i-2] == first and arr[i-1] == second:
ans.append(arr[i])
return ans | occurrences-after-bigram | Python simple solution | StikS32 | 0 | 40 | occurrences after bigram | 1,078 | 0.638 | Easy | 17,227 |
https://leetcode.com/problems/occurrences-after-bigram/discuss/2027191/Python-2-Lines-Clean-and-Concise! | class Solution:
def findOcurrences(self, text, first, second):
words = text.split(" ")
return [words[i] for i in range(2,len(words)) if words[i-2]==first and words[i-1]==second] | occurrences-after-bigram | Python - 2 Lines - Clean and Concise! | domthedeveloper | 0 | 53 | occurrences after bigram | 1,078 | 0.638 | Easy | 17,228 |
https://leetcode.com/problems/occurrences-after-bigram/discuss/1979877/simple-python | class Solution:
def findOcurrences(self, text: str, first: str, second: str) -> List[str]:
text = text.split()
output = []
for i in range(2,len(text)):
if text[i-2] == first and text[i-1] == second:
output.append(text[i])
return output | occurrences-after-bigram | simple python | user4774i | 0 | 33 | occurrences after bigram | 1,078 | 0.638 | Easy | 17,229 |
https://leetcode.com/problems/occurrences-after-bigram/discuss/1893686/Python-beginner-friendly-solution | class Solution:
def findOcurrences(self, text: str, first: str, second: str) -> List[str]:
text_split = text.split()
res = []
for i in range(len(text_split)-2):
if text_split[i] == first and text_split[i+1] == second:
res.append(text_split[i+2])
return res | occurrences-after-bigram | Python beginner friendly solution | alishak1999 | 0 | 38 | occurrences after bigram | 1,078 | 0.638 | Easy | 17,230 |
https://leetcode.com/problems/occurrences-after-bigram/discuss/1800959/4-Lines-Python-Solution-oror-90-Faster-(28ms)-oror-Memory-less-than-70 | class Solution:
def findOcurrences(self, text: str, first: str, second: str) -> List[str]:
words, ans = text.split(), []
for i in range(len(words)-2):
if words[i]==first and words[i+1]==second: ans.append(words[i+2])
return ans | occurrences-after-bigram | 4-Lines Python Solution || 90% Faster (28ms) || Memory less than 70% | Taha-C | 0 | 45 | occurrences after bigram | 1,078 | 0.638 | Easy | 17,231 |
https://leetcode.com/problems/occurrences-after-bigram/discuss/1726575/Python3-solution | class Solution:
def findOcurrences(self, text: str, first: str, second: str) -> List[str]:
words = text.split()
result = []
start = 0
while start < len(words) - 2:
if words[start] == first and words[start + 1] == second:
result.append(words[start + 2])
start += 1
return result | occurrences-after-bigram | Python3 solution | khalidhassan3011 | 0 | 19 | occurrences after bigram | 1,078 | 0.638 | Easy | 17,232 |
https://leetcode.com/problems/occurrences-after-bigram/discuss/1596369/Pyhton3-Split-String-using-prev(Easy-for-beginner!) | class Solution:
def findOcurrences(self, text: str, first: str, second: str) -> List[str]:
newstr = text.split(" ") #split element by space
prev = newstr[0] #get the first element
result = []
correct = False
for i in range(1,len(newstr)): #start range in 1, since we have prev
#if correct is True from below if condition
if correct:
result.append(newstr[i]) #append the current element
correct = False #reset corret to False
#if both i and i+1 elements are equal to first and second
if prev == first and newstr[i] == second:
#we set correct as True so in the next loop, it can get into above if condition and append the element.
correct = True
#set prev to current element so we can move on
prev = newstr[i]
return result | occurrences-after-bigram | [Pyhton3] Split String using prev(Easy for beginner!) | yugo9081 | 0 | 27 | occurrences after bigram | 1,078 | 0.638 | Easy | 17,233 |
https://leetcode.com/problems/occurrences-after-bigram/discuss/1168601/Python3-two-liner-faster-than-99.21 | class Solution:
def findOcurrences(self, text: str, first: str, second: str) -> List[str]:
x = text.split()
return [x[i] for i in range(2, len(x)) if x[i - 1] == second and x[i - 2] == first] | occurrences-after-bigram | Python3 two-liner faster than 99.21% | adarsh__kn | 0 | 36 | occurrences after bigram | 1,078 | 0.638 | Easy | 17,234 |
https://leetcode.com/problems/occurrences-after-bigram/discuss/1158998/python-simple-solution | class Solution:
def findOcurrences(self, text: str, first: str, second: str) -> List[str]:
res = list()
lst = text.split(' ')
for i in range(len(lst)-2):
if lst[i] == first and lst[i+1] == second:
res.append(lst[i+2])
return res | occurrences-after-bigram | python simple solution | keewook2 | 0 | 41 | occurrences after bigram | 1,078 | 0.638 | Easy | 17,235 |
https://leetcode.com/problems/occurrences-after-bigram/discuss/1067779/Python3-simple-solution | class Solution:
def findOcurrences(self, text: str, first: str, second: str) -> List[str]:
text = text.split()
ans = []
for i in range(len(text)-2):
if text[i] == first and text[i+1] == second:
ans.append(text[i+2])
return ans | occurrences-after-bigram | Python3 simple solution | EklavyaJoshi | 0 | 42 | occurrences after bigram | 1,078 | 0.638 | Easy | 17,236 |
https://leetcode.com/problems/occurrences-after-bigram/discuss/952257/Python-fast-and-clear-solution-O(n)-time-O(n)-memory | class Solution:
def findOcurrences(self, text: str, first: str, second: str) -> List[str]:
s = text.split(' ')
sol = []
w1, w2 = 0, 1
while w2 <= len(s)-2:
if s[w1] == first and s[w2] == second:
sol.append(s[w2+1])
w1 += 1
w2 += 1
return sol | occurrences-after-bigram | Python fast and clear solution O(n) time, O(n) memory | modusV | 0 | 46 | occurrences after bigram | 1,078 | 0.638 | Easy | 17,237 |
https://leetcode.com/problems/occurrences-after-bigram/discuss/413790/Python3-2-flags | class Solution:
def findOcurrences(self, text: str, first: str, second: str) -> List[str]:
ans = []
f0 = f1 = False
for word in text.split():
if f1: ans.append(word)
f1 = f0 and word == second
f0 = word == first
return ans | occurrences-after-bigram | [Python3] 2 flags | ye15 | 0 | 58 | occurrences after bigram | 1,078 | 0.638 | Easy | 17,238 |
https://leetcode.com/problems/occurrences-after-bigram/discuss/405312/Most-memory-efficient-Beats-70-in-time-complexity | class Solution:
def findOcurrences(self, text: str, first: str, second: str) -> List[str]:
text = text.split(' ')
m = []
while first in text:
text = text[text.index(first)+1:]
try:
if text[0]==second:
m.append(text[1])
except:
pass
return m | occurrences-after-bigram | Most memory efficient Beats 70% in time complexity | saffi | 0 | 76 | occurrences after bigram | 1,078 | 0.638 | Easy | 17,239 |
https://leetcode.com/problems/letter-tile-possibilities/discuss/774815/Python-3-Backtracking-(no-set-no-itertools-simple-DFS-count)-with-explanation | class Solution:
def numTilePossibilities(self, tiles: str) -> int:
record = [0] * 26
for tile in tiles: record[ord(tile)-ord('A')] += 1
def dfs(record):
s = 0
for i in range(26):
if not record[i]: continue
record[i] -= 1
s += dfs(record) + 1
record[i] += 1
return s
return dfs(record) | letter-tile-possibilities | Python 3 Backtracking (no set, no itertools, simple DFS count) with explanation | idontknoooo | 21 | 1,500 | letter tile possibilities | 1,079 | 0.761 | Medium | 17,240 |
https://leetcode.com/problems/letter-tile-possibilities/discuss/1375847/Python3-or-Hashset%2BBacktracking | class Solution:
def numTilePossibilities(self, tiles: str) -> int:
ds=[]
self.ans=set()
self.solve(tiles,ds)
return len(self.ans)
def solve(self,tiles,ds):
for i in range(len(tiles)):
ds.append(tiles[i])
self.ans.add("".join(ds[:]))
self.solve(tiles[:i]+tiles[i+1:],ds)
ds.pop()
return | letter-tile-possibilities | Python3 | Hashset+Backtracking | swapnilsingh421 | 3 | 309 | letter tile possibilities | 1,079 | 0.761 | Medium | 17,241 |
https://leetcode.com/problems/letter-tile-possibilities/discuss/308437/Rolling-Set-Python-BFS-very-concise | class Solution:
def numTilePossibilities(self, tiles: str) -> int:
cur = set([''])
for tile in tiles:
nex = cur.copy()
for word in cur:
for j in range(len(word)+1):
nex.add(word[:j]+ tile +word[j:])
cur = nex
return len(cur)-1 | letter-tile-possibilities | Rolling Set Python BFS, very concise | jjliao | 2 | 320 | letter tile possibilities | 1,079 | 0.761 | Medium | 17,242 |
https://leetcode.com/problems/letter-tile-possibilities/discuss/2835609/ONE-LINERoror-USING-BUILT-IN-FUNCTION-ororSIMPLEororEASY-TO-UNDERSTANDoror-PYTHON | class Solution:
def numTilePossibilities(self, tiles: str) -> int:
return len(set(sum([list(itertools.permutations(tiles, i)) for i in range(1, len(tiles) + 1)], []))) | letter-tile-possibilities | ONE LINER|| USING BUILT-IN FUNCTION ||SIMPLE||EASY TO UNDERSTAND|| PYTHON | thezealott | 1 | 18 | letter tile possibilities | 1,079 | 0.761 | Medium | 17,243 |
https://leetcode.com/problems/letter-tile-possibilities/discuss/2835607/SIMPLE-oror-4-LINESoror-BEGINNER-FRIENDLY-SOLUTION | class Solution:
def numTilePossibilities(self, tiles: str) -> int:
n= len(tiles)
tiles=list(tiles)
s1=set()
for i in range(1,n+1):
s1.update(permutations(tiles,i))
return len(s1) | letter-tile-possibilities | SIMPLE || 4 LINES|| BEGINNER FRIENDLY SOLUTION | thezealott | 1 | 19 | letter tile possibilities | 1,079 | 0.761 | Medium | 17,244 |
https://leetcode.com/problems/letter-tile-possibilities/discuss/2147108/PYTHON-SOL-or-EASY-or-BACKTRACKING-or-WITHOUT-HASHMAP-or-EXPLAINED | class Solution:
def backtracking(self, index , tiles , string):
# if string is not empty we got one unique permutation
if string != "":
self.ans += 1
# if index == len(tiles) we cannot add any new character
if index == len(tiles):
return
# we use done so that we avoid repeatition of permutations
done = {}
for i in range(index,len(tiles)):
# choose i as the index
if tiles[i] in done:
continue
done[tiles[i]] = True
# creates the new tiles string for us
new_tiles = tiles[:index] + tiles[i] + tiles[index+1:i] + tiles[index] + tiles[i+1:] if i != index else tiles
self.backtracking(index + 1 , new_tiles , string + new_tiles[index])
def numTilePossibilities(self, tiles: str) -> int:
self.ans = 0
self.backtracking(0,tiles,"")
return self.ans | letter-tile-possibilities | PYTHON SOL | EASY | BACKTRACKING | WITHOUT HASHMAP | EXPLAINED } | reaper_27 | 1 | 230 | letter tile possibilities | 1,079 | 0.761 | Medium | 17,245 |
https://leetcode.com/problems/letter-tile-possibilities/discuss/1760849/Python3-solution | class Solution:
def numTilePossibilities(self, tiles: str) -> int:
def dfs(string,st):
s.add(st)
for i in range(len(string)):
dfs(string[:i]+string[i+1:],st+string[i])
s=set()
dfs(tiles,"")
return len(s)-1 | letter-tile-possibilities | Python3 solution | Karna61814 | 1 | 121 | letter tile possibilities | 1,079 | 0.761 | Medium | 17,246 |
https://leetcode.com/problems/letter-tile-possibilities/discuss/2804010/Easy-Python-with-explanation-(using-sets) | class Solution:
def numTilePossibilities(self, tiles):
sequences = set(tiles[0])
for i in range(1,len(tiles)):
sequences2 = sequences.copy()
sequences.add(tiles[i])
for word in sequences2:
for j in range(len(word)+1):
sequences.add(word[:j] + tiles[i] + word[j:])
return len(sequences) | letter-tile-possibilities | Easy Python with explanation (using sets) | Pirmil | 0 | 6 | letter tile possibilities | 1,079 | 0.761 | Medium | 17,247 |
https://leetcode.com/problems/letter-tile-possibilities/discuss/2711446/Python-O(26N)-O(1) | class Solution:
def numTilePossibilities(self, tiles: str) -> int:
counter = collections.Counter(tiles)
def backtrack():
total = 1
for char in counter:
if counter[char] > 0:
counter[char] -= 1
total += backtrack()
counter[char] += 1
return total
return backtrack() - 1 | letter-tile-possibilities | Python - O(26^N), O(1) | Teecha13 | 0 | 10 | letter tile possibilities | 1,079 | 0.761 | Medium | 17,248 |
https://leetcode.com/problems/letter-tile-possibilities/discuss/2446403/Python3-or-Recursion-%2B-Backtracking | class Solution:
#Time-Complexity: O(n^n), since branching factor of rec. is at most n and height of tree is n!
#Space-Complexity: O(n + n), since boolean array is size n and rec. takes up
#call stack of at most n frames! -> O(n)
def numTilePossibilities(self, tiles: str) -> int:
#Approach: Start with empty sequence string and pass it by ref across
#multiple recursive calls! On every recursive call, we should add it to the
#answer to make sure that I take account of every possible sequence we can form
#using the tiles given!
#I can use boolean flag array that corresponds to each index position
#to indicate whether we already used the tile that corresponds to particular
#index or not! At every decision making node in rec. tree, we can only
#recurse along paths that will add new unused character!
# I need to make answer a set so it only stores unique sequence elements!
ans = set()
n = len(tiles)
#paramters
#1. fa = flag array that contains 0 at index i if tiles[i] is not used
#or 1 otherwise!
#2. cur = sequence which is a string that we are building up!
def helper(fa, cur):
nonlocal n, ans, tiles
ans.add(cur[::])
#base case: if len(cur) == n, then we used all characters!
if(len(cur) == n):
return
#we will run a for loop for indices i = 0 to i=n-1 so we consider
#recursing and adding every unused character in next corresponding position
#in current string!
for i in range(0, n, 1):
#check if current tiles[i] is unused tile!
if(fa[i] == 0):
#set the flag to indicate we can't use tiles[i] for further
#sequence generation resulting from further re
fa[i] = 1
cur += tiles[i]
helper(fa, cur)
#now once recursion ends along particular path, we need to
#restore the fa and current built up sequence string for backtracking!
#turn the flag off!
fa[i] = 0
#take all characters beside last one!
cur = cur[:len(cur)-1]
#if flag is set for tiles[i], we can't recurse along the path!
else:
continue
#intiialize boolean array, which is all turned off for indices 0 to n-1!
boolean_arr = [0 for _ in range(n)]
helper(boolean_arr, "")
#we only want to return non-empty distinct sequences!
return len(ans) - 1 | letter-tile-possibilities | Python3 | Recursion + Backtracking | JOON1234 | 0 | 74 | letter tile possibilities | 1,079 | 0.761 | Medium | 17,249 |
https://leetcode.com/problems/letter-tile-possibilities/discuss/2406652/Python-1-liner-94-speed | class Solution:
def numTilePossibilities(self, tiles: str) -> int:
return len(set(sum([list(itertools.permutations(tiles, i)) for i in range(1, len(tiles) + 1)], []))) | letter-tile-possibilities | Python 1-liner, 94 % speed | amaargiru | 0 | 135 | letter tile possibilities | 1,079 | 0.761 | Medium | 17,250 |
https://leetcode.com/problems/letter-tile-possibilities/discuss/1899390/Python-solution-faster-than-95 | class Solution:
def numTilePossibilities(self, tiles: str) -> int:
tile_list = list(tiles)
count = 0
for i in range(1, len(tiles)+1):
count += len(set(permutations(tile_list, i)))
return count | letter-tile-possibilities | Python solution faster than 95% | alishak1999 | 0 | 185 | letter tile possibilities | 1,079 | 0.761 | Medium | 17,251 |
https://leetcode.com/problems/letter-tile-possibilities/discuss/1187798/Python-fast-pythonic-1-line | class Solution:
def numTilePossibilities(self, tiles: str) -> int:
from itertools import permutations
return len({x for i in range(1, len(tiles)+1) for x in permutations(tiles, i)}) | letter-tile-possibilities | [Python] fast pythonic 1-line | cruim | 0 | 306 | letter tile possibilities | 1,079 | 0.761 | Medium | 17,252 |
https://leetcode.com/problems/letter-tile-possibilities/discuss/1130373/Python-Backstracking | class Solution:
def numTilePossibilities(self, tiles: str) -> int:
path = []
visited = [False] * len(tiles)
result = set()
self.dfs(tiles, path, visited, result)
return len(result)
def dfs(self, tiles, path, visited, result):
if path:
p = "".join(path)
result.add(p)
for i in range(len(tiles)):
if not visited[i]:
path.append(tiles[i])
visited[i] = True
self.dfs(tiles, path, visited, result)
path.pop()
visited[i] = False | letter-tile-possibilities | Python Backstracking | joyzheng | 0 | 234 | letter tile possibilities | 1,079 | 0.761 | Medium | 17,253 |
https://leetcode.com/problems/letter-tile-possibilities/discuss/972031/python3-solution | class Solution:
def __init__(self):
self.ans = 0
def numTilePossibilities(self, tiles: str) -> int:
self.freq = collections.Counter(tiles)
def backtrack():
for key in self.freq.keys():
if self.freq[key]>0:
self.ans += 1
self.freq[key] -= 1
backtrack()
self.freq[key] += 1
backtrack()
return self.ans | letter-tile-possibilities | python3 solution | swap2001 | 0 | 227 | letter tile possibilities | 1,079 | 0.761 | Medium | 17,254 |
https://leetcode.com/problems/letter-tile-possibilities/discuss/343913/Python-3-solution-using-backtracking | class Solution:
def numTilePossibilities(self, tiles: str) -> int:
res=[]
def rec(t,now,k):
nonlocal res
if k==1:
for i in t:
res.append(now+i)
return
for i in range(len(t)):
rec(t[:i]+t[i+1:],now+t[i],k-1)
for i in range(1,len(tiles)+1):
rec(tiles,'',i)
return(len(set(res))) | letter-tile-possibilities | Python 3 solution using backtracking | ketan35 | 0 | 482 | letter tile possibilities | 1,079 | 0.761 | Medium | 17,255 |
https://leetcode.com/problems/insufficient-nodes-in-root-to-leaf-paths/discuss/1350913/Simple-Python-Solution-or-O(N)-or-DFS | class Solution:
def sufficientSubset(self, root: TreeNode, limit: int, pathSum = 0) -> TreeNode:
if not root: return None
if not root.left and not root.right:
if pathSum + root.val < limit:
return None
return root
root.left = self.sufficientSubset(root.left, limit, pathSum + root.val)
root.right = self.sufficientSubset(root.right, limit, pathSum + root.val)
if not root.left and not root.right:
return None
return root | insufficient-nodes-in-root-to-leaf-paths | Simple Python Solution | O(N) | DFS | Astomak | 2 | 192 | insufficient nodes in root to leaf paths | 1,080 | 0.53 | Medium | 17,256 |
https://leetcode.com/problems/insufficient-nodes-in-root-to-leaf-paths/discuss/1788539/Python-or-Simple-and-Concise-solution-(Easy-to-Understand) | class Solution:
def sufficientSubset(self, root: Optional[TreeNode], limit: int) -> Optional[TreeNode]:
def traverse(node, pathSum):
#For non-leaf nodes return invalid path sum
if(node is None): return limit - 1, None
pathSumWithCurrentNode = pathSum + node.val
#For leaf node return the path sum
if(node.left is None and node.right is None):
leftPathSum = rightPathSum = pathSumWithCurrentNode
else:
leftPathSum, node.left = traverse(node.left, pathSumWithCurrentNode)
rightPathSum, node.right = traverse(node.right, pathSumWithCurrentNode)
if(leftPathSum >= limit or rightPathSum >= limit):
#including the current node
return max(leftPathSum, rightPathSum), node
#Removing the current node
return min(leftPathSum, rightPathSum), None
_, newRoot = traverse(root, 0)
return newRoot | insufficient-nodes-in-root-to-leaf-paths | Python | Simple and Concise solution (Easy to Understand) | thoufic | 1 | 111 | insufficient nodes in root to leaf paths | 1,080 | 0.53 | Medium | 17,257 |
https://leetcode.com/problems/insufficient-nodes-in-root-to-leaf-paths/discuss/1015873/Python3-post-order-dfs | class Solution:
def sufficientSubset(self, root: TreeNode, limit: int) -> TreeNode:
def fn(node, prefix):
"""Return updated node (possibly None) and max sum passing it."""
if not node: return None, -inf # boundary condition
prefix += node.val # prefix sum
suffix = 0
if node.left or node.right: # non-leaf
node.left, lsuf= fn(node.left, prefix)
node.right, rsuf = fn(node.right, prefix)
suffix = max(lsuf, rsuf) # max suffix sum
return None if prefix + suffix < limit else node, node.val + suffix
return fn(root, 0)[0] | insufficient-nodes-in-root-to-leaf-paths | [Python3] post-order dfs | ye15 | 0 | 87 | insufficient nodes in root to leaf paths | 1,080 | 0.53 | Medium | 17,258 |
https://leetcode.com/problems/insufficient-nodes-in-root-to-leaf-paths/discuss/1015873/Python3-post-order-dfs | class Solution:
def sufficientSubset(self, root: TreeNode, limit: int) -> TreeNode:
def fn(node, x):
"""Return updated node."""
if not node: return
x -= node.val
if node.left is node.right: return None if x > 0 else node # leaf
node.left = fn(node.left, x)
node.right = fn(node.right, x)
return node if node.left or node.right else None
return fn(root, limit) | insufficient-nodes-in-root-to-leaf-paths | [Python3] post-order dfs | ye15 | 0 | 87 | insufficient nodes in root to leaf paths | 1,080 | 0.53 | Medium | 17,259 |
https://leetcode.com/problems/insufficient-nodes-in-root-to-leaf-paths/discuss/983812/python3-path-sum-and-pruning | class Solution:
def sufficientSubset(self, root: TreeNode, limit: int) -> TreeNode:
# recursive dfs
# helper function takes node, path sum, returns node
# if leaf (no kids), check if over limit; if not return null
# else, rcrs into kids; and reassign with their return call
# if at one point you had kids, but now do not, return None (purge me)
# (kids to no kids implies no root to leaf path exists over limit)
# O(N) time, O(H) tree height call space
def rcrs(node: TreeNode, path: int) -> TreeNode:
if not node: return None
if not node.left and not node.right:
return None if (path + node.val) < limit else node
node.left = rcrs(node.left, path + node.val)
node.right = rcrs(node.right, path + node.val)
return None if not node.left and not node.right else node
# setup and call
return rcrs(root, 0) | insufficient-nodes-in-root-to-leaf-paths | python3 - path sum and pruning | dachwadachwa | 0 | 57 | insufficient nodes in root to leaf paths | 1,080 | 0.53 | Medium | 17,260 |
https://leetcode.com/problems/insufficient-nodes-in-root-to-leaf-paths/discuss/308278/Why-my-solution-got-WA | class Solution:
def sufficientSubset(self, root: TreeNode, limit: int) -> TreeNode:
cands = set()
def dfs(node, s):
if node.left is None and node.right is None:
if (s + node.val) < limit:
return True
else:
return False
else:
if node.left:
left = dfs(node.left, s + node.val)
if left:
node.left = None
else:
left = True
if node.right:
right = dfs(node.right, s + node.val)
if right:
node.right = None
else:
right = True
return left and right
if dfs(root, 0):
return None
return root | insufficient-nodes-in-root-to-leaf-paths | Why my solution got WA? | jinjiren | 0 | 26 | insufficient nodes in root to leaf paths | 1,080 | 0.53 | Medium | 17,261 |
https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/discuss/894588/Python3-stack-O(N) | class Solution:
def smallestSubsequence(self, s: str) -> str:
loc = {x: i for i, x in enumerate(s)}
stack = []
for i, x in enumerate(s):
if x not in stack:
while stack and x < stack[-1] and i < loc[stack[-1]]: stack.pop()
stack.append(x)
return "".join(stack) | smallest-subsequence-of-distinct-characters | [Python3] stack O(N) | ye15 | 2 | 246 | smallest subsequence of distinct characters | 1,081 | 0.575 | Medium | 17,262 |
https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/discuss/2151348/PYTHON-SOL-or-EXPLAINED-or-VERY-EASY-or-FAST-or-SIMPLE-or-BINARY-SEARCH-%2B-ITERATION-or | class Solution:
def smallestSubsequence(self, s: str) -> str:
d = defaultdict(list)
for index,character in enumerate(s):
d[character].append(index)
unique = sorted([ x for x in d])
# what should be the character at index = 1
size = len(unique)
ans = ""
used = {}
left = 0
for i in range(size):
for character in unique:
if character in used:continue
if d[character][-1] < left: continue
# find the new left
idx = bisect.bisect_left(d[character],left)
new_left = d[character][idx]
# check if current character can be used
flag = True
for character2 in unique:
if character2 in used or character2 == character: continue
if d[character2][-1] < new_left:
flag = False
break
if flag == True:
left = new_left
ans += character
used[character] = True
break
return ans | smallest-subsequence-of-distinct-characters | PYTHON SOL | EXPLAINED | VERY EASY | FAST | SIMPLE | BINARY SEARCH + ITERATION | | reaper_27 | 1 | 181 | smallest subsequence of distinct characters | 1,081 | 0.575 | Medium | 17,263 |
https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/discuss/2799094/Easy-Python-Solutionor-O(N) | class Solution:
def smallestSubsequence(self, s: str) -> str:
d=Counter(s)
vis=[False]*26
stack=[]
n=len(s)
for i in range(n):
while stack and s[i]<stack[-1] and d[stack[-1]]>0 and not vis[ord(s[i])-97]:
vis[ord(stack[-1])-97]=False
stack.pop()
d[s[i]]-=1
if not vis[ord(s[i])-97]:
vis[ord(s[i])-97]=True
stack.append(s[i])
print(stack)
return "".join(stack) | smallest-subsequence-of-distinct-characters | Easy Python Solution| O(N) | praveen0906 | 0 | 3 | smallest subsequence of distinct characters | 1,081 | 0.575 | Medium | 17,264 |
https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/discuss/2792581/Easy-Python-Solution | class Solution:
def smallestSubsequence(self, s: str) -> str:
d={v:k for k,v in enumerate(s)}
stack=[]
for k,v in enumerate(s):
if v not in stack:
while stack and stack[-1]>v and d[stack[-1]]>k:
stack.pop()
stack.append(v)
return "".join(stack) | smallest-subsequence-of-distinct-characters | Easy Python Solution | RajatGanguly | 0 | 4 | smallest subsequence of distinct characters | 1,081 | 0.575 | Medium | 17,265 |
https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/discuss/2666365/Python-Easy-Monotonic-Stack | class Solution:
def smallestSubsequence(self, s: str) -> str:
count = Counter(s)
stack = deque()
result = set()
for i in s:
if i in result:
count[i] -= 1
continue
while(stack and stack[-1] > i and count[stack[-1]] > 1):
count[stack[-1]] -= 1
result.remove(stack[-1])
stack.pop()
stack.append(i)
result.add(i)
return "".join(stack) | smallest-subsequence-of-distinct-characters | Python Easy Monotonic Stack | anu1rag | 0 | 3 | smallest subsequence of distinct characters | 1,081 | 0.575 | Medium | 17,266 |
https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/discuss/2663994/PYTHON-SOLUTION-oror-Stack-implementation | class Solution:
def smallestSubsequence(self, s: str) -> str:
d={}
for i in range(len(s)):
d[s[i]]=i
ans=set()
stack=[]
for i in range(len(s)):
if s[i] in ans:
continue
if len(stack)!=0 and stack[-1]<s[i]:
stack.append(s[i])
ans.add(s[i])
else:
while len(stack)!=0 and stack[-1]>s[i] and d[stack[-1]]>i:
a=stack.pop()
ans.remove(a)
stack.append(s[i])
ans.add(s[i])
return "".join(stack) | smallest-subsequence-of-distinct-characters | PYTHON SOLUTION || Stack implementation | utsa_gupta | 0 | 10 | smallest subsequence of distinct characters | 1,081 | 0.575 | Medium | 17,267 |
https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/discuss/2662979/Smallest-Subsequence-of-Distinct-Characters-oror-Python3-oror-Stack | class Solution:
def smallestSubsequence(self, s: str) -> str:
d={}
for i in range (len(s)):
d[s[i]]=i
print(d)
st=set()
stack=[]
for i in range(len(s)):
if s[i] in st:
continue
if len(stack)!=0 and stack[-1]<s[i]:
stack.append(s[i])
st.add(s[i])
else:
while len(stack)!=0 and stack[-1]>s[i] and d[stack[-1]]>i:
a=stack.pop()
st.remove(a)
if s[i] not in st:
st.add(s[i])
stack.append(s[i])
#print(stack)
return ''.join(stack) | smallest-subsequence-of-distinct-characters | Smallest Subsequence of Distinct Characters || Python3 || Stack | shagun_pandey | 0 | 1 | smallest subsequence of distinct characters | 1,081 | 0.575 | Medium | 17,268 |
https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/discuss/2657282/python-easy-solu-with-explaination-using-monotonic-stack-and-dict | class Solution:
def smallestSubsequence(self, s: str) -> str:
d={}
for i,j in enumerate (s): #making dictionary
d[j]=i
print(d)
stack=[]
for i in range (len(s)):
if s[i] not in stack:
while stack and stack[-1]>s[i] and d[stack[-1]]>i: #if --there is stack and --stack of last element is greater than s[i]
#and-- if last element of stack present in dict then that value is greater than i ... then we should perform pop operation
stack.pop()
stack.append(s[i]) #otherwise push
return ''.join(stack) | smallest-subsequence-of-distinct-characters | python easy solu with explaination using monotonic stack & dict | tush18 | 0 | 14 | smallest subsequence of distinct characters | 1,081 | 0.575 | Medium | 17,269 |
https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/discuss/1028830/Python3-Stack-greater-Beats-98 | class Solution:
def smallestSubsequence(self, s: str) -> str:
stack = []
for i, c in enumerate(s):
if c in stack:
continue
while stack and stack[-1] in s[i:] and c < stack[-1]:
stack.pop()
if c not in stack:
stack.append(c)
return ''.join(stack) | smallest-subsequence-of-distinct-characters | [Python3] Stack -> Beats 98% | charlie11 | 0 | 69 | smallest subsequence of distinct characters | 1,081 | 0.575 | Medium | 17,270 |
https://leetcode.com/problems/duplicate-zeros/discuss/408059/Python-Simple-Solution | class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
i = 0
n = len(arr)
while(i<n):
if arr[i]==0:
arr.pop()
arr.insert(i,0)
i+=1
i+=1 | duplicate-zeros | Python Simple Solution | saffi | 19 | 3,100 | duplicate zeros | 1,089 | 0.515 | Easy | 17,271 |
https://leetcode.com/problems/duplicate-zeros/discuss/1051352/Python3-In-place-simple-short-solution.-Explained. | class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
cnt = arr.count(0)
for i in reversed(range(len(arr))):
if i + cnt < len(arr): arr[i + cnt] = arr[i] # copy the number over to correct position
if arr[i] == 0:
cnt -= 1
if i + cnt < len(arr): arr[i + cnt] = arr[i] # copy again if the number is 0 | duplicate-zeros | [Python3] In place, simple, short solution. Explained. | vudinhhung942k | 9 | 333 | duplicate zeros | 1,089 | 0.515 | Easy | 17,272 |
https://leetcode.com/problems/duplicate-zeros/discuss/2496025/Simple-Python-solution- | class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
"""
Do not return anything, modify arr in-place instead.
"""
i = 0
while i < len(arr):
if arr[i] == 0:
arr.pop()
arr.insert(i, 0)
i += 2
else:
i += 1 | duplicate-zeros | Simple Python solution - | gkarthik923 | 4 | 187 | duplicate zeros | 1,089 | 0.515 | Easy | 17,273 |
https://leetcode.com/problems/duplicate-zeros/discuss/313118/Simple-python-solution | class Solution(object):
def duplicateZeros(self, arr):
x = 0
while x < len(arr):
if arr[x] == 0:
arr.insert(x, 0)
arr.pop(-1)
x+=1
x += 1 | duplicate-zeros | Simple python solution | webpiero | 4 | 551 | duplicate zeros | 1,089 | 0.515 | Easy | 17,274 |
https://leetcode.com/problems/duplicate-zeros/discuss/1332592/Easy-Python-Solution | class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
"""
Do not return anything, modify arr in-place instead.
"""
i=0
while i<len(arr):
if arr[i] ==0:
arr.pop()
arr.insert(i+1,0)
i=i+2
else:
i=i+1 | duplicate-zeros | Easy Python Solution | sangam92 | 2 | 222 | duplicate zeros | 1,089 | 0.515 | Easy | 17,275 |
https://leetcode.com/problems/duplicate-zeros/discuss/1172179/Python3-simple-and-easy-to-understand-solution-using-while-loop | class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
"""
Do not return anything, modify arr in-place instead.
"""
i = 0
while i < len(arr):
if arr[i] == 0:
arr.insert(i+1,0)
arr.pop()
i += 2
else:
i += 1 | duplicate-zeros | Python3 simple and easy to understand solution using while loop | EklavyaJoshi | 2 | 144 | duplicate zeros | 1,089 | 0.515 | Easy | 17,276 |
https://leetcode.com/problems/duplicate-zeros/discuss/2838928/Python-one-pass-with-O(n)-space-easy-understanding! | class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
"""
Do not return anything, modify arr in-place instead.
"""
j = 0
for n in arr[:]:
if n == 0:
arr[j] = 0
j += 1
if j == len(arr):
break
arr[j] = 0
else:
arr[j] = n
j += 1
if j == len(arr):
break | duplicate-zeros | Python one pass with O(n) space, easy understanding! | coderZ | 1 | 47 | duplicate zeros | 1,089 | 0.515 | Easy | 17,277 |
https://leetcode.com/problems/duplicate-zeros/discuss/2705763/Python-Two-Pointers | class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
"""
Do not return anything, modify arr in-place instead.
"""
oldLen = len(arr)
i = 0
j = len(arr)
while i < j :
if arr[i] == 0 :
arr.insert(i+1 , 0)
i += 1
i += 1
arr[:] = arr[:oldLen] | duplicate-zeros | Python Two Pointers | mohamedWalid | 1 | 193 | duplicate zeros | 1,089 | 0.515 | Easy | 17,278 |
https://leetcode.com/problems/duplicate-zeros/discuss/2319878/Python-O(n)-Solution | class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
count = 0
while count < len(arr):
if arr[count] == 0:
arr.insert(count, 0)
arr.pop()
count += 2
else:
count += 1 | duplicate-zeros | Python - O(n) Solution | Balance-Coffee | 1 | 93 | duplicate zeros | 1,089 | 0.515 | Easy | 17,279 |
https://leetcode.com/problems/duplicate-zeros/discuss/2039940/Python-Simpler-solution-with-inline-comment-Time-O(N)-Space-O(1) | class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
left = -1 # the rightmost end upto which elements are not dropped
capacity = len(arr)
right = capacity - 1 # the right pointer used to populate array in right-to-left order
while capacity > 0:
capacity -=1
left += 1
if arr[left] == 0:
# capacity becomes negative iff we reached a last zero with no space for replication
capacity -= 1
# check if last zero with no space for replication
if arr[left] == 0 and capacity < 0:
arr[right] = arr[left]
left -= 1
right -= 1
while right > -1:
arr[right] = arr[left]
right -= 1
if arr[left] == 0 and right > -1 and left > -1 and right >= left:
arr[right] = arr[left]
right -= 1
left -= 1 | duplicate-zeros | Python - Simpler solution with inline comment - Time O(N), Space O(1) | tushar-rishav | 1 | 287 | duplicate zeros | 1,089 | 0.515 | Easy | 17,280 |
https://leetcode.com/problems/duplicate-zeros/discuss/1607810/Python3-Solution-56ms-(98)-O(n)-timeO(1)-space-(inserting-and-pop-solution-is-O(n2) | class Solution(object):
def duplicateZeros(self, nums):
if len(nums) == 1:
if nums[0] == 0:
return [0,0]
else:
return nums
index = 0
last_element_index = len(nums) - 1
flag = 0
while index <= last_element_index:
if nums[index] == 0:
if index == last_element_index:
index +=1
flag = 1
break
last_element_index -= 1
index += 1
pointer = index-1
last = len(nums) - 1
if nums[pointer] == 0 and flag :
nums[last] = 0
pointer -= 1
last -= 1
while pointer >= 0:
if nums[pointer] != 0:
nums[last] = nums[pointer]
pointer -= 1
last -= 1
else:
nums[last] = 0
nums[last-1] = 0
last -= 2
pointer -= 1 | duplicate-zeros | Python3 Solution, 56ms (98%) O(n) time/O(1) space (inserting and pop solution is O(n^2) | galethegreat | 1 | 130 | duplicate zeros | 1,089 | 0.515 | Easy | 17,281 |
https://leetcode.com/problems/duplicate-zeros/discuss/1575544/Python-simple-with-detailed-explanation | class Solution:
def duplicateZeros(self, nums: List[int]) -> None:
i = 0
while i < len(nums):
if nums[i] == 0:
self.helper(nums, i + 1)
i += 2
else:
i += 1
def helper(self, nums, idx):
for i in reversed(range(idx, len(nums))):
nums[i] = nums[i-1] | duplicate-zeros | Python simple with detailed explanation | SleeplessChallenger | 1 | 154 | duplicate zeros | 1,089 | 0.515 | Easy | 17,282 |
https://leetcode.com/problems/duplicate-zeros/discuss/2847336/Python | class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
skip = 0
for i in range(len(arr)):
if skip > 0:
skip -= 1
continue
if arr[i] == 0:
arr.insert(i + 1, 0)
del arr[-1]
skip += 1 | duplicate-zeros | Python | yijiun | 0 | 1 | duplicate zeros | 1,089 | 0.515 | Easy | 17,283 |
https://leetcode.com/problems/duplicate-zeros/discuss/2834867/Easy-understand-python-answer | class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
"""
Do not return anything, modify arr in-place instead.
"""
i = 0
while i < len(arr):
if arr[i] == 0:
arr.insert(i+1, 0)
arr.pop()
i += 2
else:
i += 1 | duplicate-zeros | Easy understand python answer | jianan1104 | 0 | 1 | duplicate zeros | 1,089 | 0.515 | Easy | 17,284 |
https://leetcode.com/problems/duplicate-zeros/discuss/2825766/Easy-way | class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
"""
Do not return anything, modify arr in-place instead.
"""
x=0
n=len(arr)
while x<n:
if arr[x]==0:
arr.insert(x,0)
arr.pop(-1)
x+=1
x=x+1 | duplicate-zeros | Easy way | nishithakonuganti | 0 | 1 | duplicate zeros | 1,089 | 0.515 | Easy | 17,285 |
https://leetcode.com/problems/duplicate-zeros/discuss/2825031/Python-Solution%3A-O(n)-time-complexity-and-O(1)-space-complexity | class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
"""
Do not return anything, modify arr in-place instead.
"""
i=0
n=len(arr)
while(i<n):
if arr[i]==0:
arr.insert(i,0)
arr.pop()
i+=1
i+=1 | duplicate-zeros | Python Solution: O(n) time complexity and O(1) space complexity | CharuArora_ | 0 | 3 | duplicate zeros | 1,089 | 0.515 | Easy | 17,286 |
https://leetcode.com/problems/duplicate-zeros/discuss/2793981/Most-simple-and-easy-to-understand-solutions | class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
i = 0
size = len(arr)
while i < size:
if arr[i] == 0:
arr.pop()
arr.insert(i, 0)
i += 2
else:
i += 1 | duplicate-zeros | Most simple and easy to understand solutions | namanjawaliya | 0 | 1 | duplicate zeros | 1,089 | 0.515 | Easy | 17,287 |
https://leetcode.com/problems/duplicate-zeros/discuss/2733381/Only-index-referencing-and-slices-no-list-methods-beats-66. | class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
"""
Do not return anything, modify arr in-place instead.
"""
flag = False
for i in range(len(arr)):
if flag == True:
flag = False
arr[i+1:len(arr)] = arr[i:len(arr)-1]
arr[i] = 0
continue
if arr[i] == 0:
flag = True
continue
return arr | duplicate-zeros | Only index referencing and slices; no list methods; beats 66%. | mwalle | 0 | 1 | duplicate zeros | 1,089 | 0.515 | Easy | 17,288 |
https://leetcode.com/problems/duplicate-zeros/discuss/2687892/Another-Python-solution-indexing-the-zeroes-first | class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
"""
Do not return anything, modify arr in-place instead.
"""
# Preserve initial list length
l = len(arr)
# Collect locations of zeroes
pos = []
for i, n in enumerate(arr):
if n == 0:
pos.append(i)
# Use location list to double zeroes
for i, n in enumerate(pos):
arr.insert(n + i, 0)
# Remove excess elements
del arr[l:]
``` | duplicate-zeros | Another Python solution - indexing the zeroes first | fodonogogo | 0 | 8 | duplicate zeros | 1,089 | 0.515 | Easy | 17,289 |
https://leetcode.com/problems/duplicate-zeros/discuss/2655342/Python-%2BNumPy%2Bstring-operations | class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
"""
Do not return anything, modify arr in-place instead.
"""
import numpy as np
arr=np.array(arr)
zeros=np.where(arr==0)[0]
arr=np.insert(arr,zeros,[0]*len(zeros))[:len(arr)] | duplicate-zeros | Python +NumPy+string operations | Leox2022 | 0 | 2 | duplicate zeros | 1,089 | 0.515 | Easy | 17,290 |
https://leetcode.com/problems/duplicate-zeros/discuss/2648060/Python-Solution-with-O(n)-time-and-O(n)-space | class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
"""
Do not return anything, modify arr in-place instead.
"""
zero_count = 0
arrLen = len(arr) - 1
## -- Find number of zeros in the array
for i in range(arrLen + 1):
if i > arrLen - zero_count:
break
if arr[i] == 0:
## -- If we encounter zero at the last position in array, we don't duplicate it. We just copy a single zero as it is and decrement arrLen by 1 and break out of the loop.
## -- This essentially helps us by ensuring that we do not duplicate zeros which will be removed from the array, as they will eventually fall out of array index range.
if i == arrLen - zero_count:
arr[i] = 0
arrLen -= 1
break
zero_count += 1
## -- Now, we have to determine the position of last element in the array which will be preserved in the modified array. This can be found by subtracting zero_count from arrLen
last = arrLen - zero_count
## -- Now that we know the position of the last element in the array, we will traverse the array backwards and copy two zeroes for every single zero or else, copy/shift the element to the new position
## -- This for loop shows how decrement operation is implemented in Python. For better understanding, please visit: https://www.pythonpool.com/python-for-loop-decrement/
for i in (range(last, -1, -1)):
if arr[i] == 0:
arr[i + zero_count] = 0
zero_count -= 1 ## -- Decrement zero_count Because we copied one zero and we now need to copy the duplicate zero next to it
arr[i + zero_count] = 0
else:
arr[i + zero_count] = arr[i] | duplicate-zeros | Python Solution with O(n) time and O(n) space | arpitpatil2016 | 0 | 54 | duplicate zeros | 1,089 | 0.515 | Easy | 17,291 |
https://leetcode.com/problems/duplicate-zeros/discuss/2634790/Python-Two-Pointer-approach | class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
i=0
j=len(arr)-1
while i<j:
if arr[i]==0:
arr.insert(i+1,0)
arr.pop()
i+=2
else:
i+=1
return arr | duplicate-zeros | Python-Two Pointer approach | utsa_gupta | 0 | 11 | duplicate zeros | 1,089 | 0.515 | Easy | 17,292 |
https://leetcode.com/problems/duplicate-zeros/discuss/2469341/Solution-using-PythonFaster-Then-96.99-percent | class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
"""
Do not return anything, modify arr in-place instead.
"""
i=0
temp=len(arr)
while i<len(arr):
if arr[i]==0:
arr.insert(i+1,0)
i+=2
else:
i+=1
del arr[temp:] | duplicate-zeros | Solution using Python[Faster Then 96.99 percent] | deepanshu704281 | 0 | 53 | duplicate zeros | 1,089 | 0.515 | Easy | 17,293 |
https://leetcode.com/problems/duplicate-zeros/discuss/2400000/Think-it-through | class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
"""
Do not return anything, modify arr in-place instead.
"""
possible_duplicates = 0
length = len(arr) - 1
# going left to right
# and counting zeros to be considered for duplication
# why considering whole length of array and not leaving last element?
# Ans:=> in this case last element could be zero and if we don't iterate over the whole array we would end up duplicating it in the next iteration as we would miss not considering the last element for no-duplication
for left in range(length + 1):
# left goes beyond allowed elements, stop iteration
if left > length - possible_duplicates:
break
# count zeros
if arr[left] == 0:
# edge case: don't include the last element which can not be duplicated due to no more space available in the array
if left == length - possible_duplicates:
# move this zero to the end of the array
arr[length] = arr[left] # or 0
length -= 1 # we don't have to consider placing this element to its correct position because we already did so
break # break out of the loop, we have already visited and seen all the elements that could be part of resulting arr, we don't have to calculate this 0 too.
possible_duplicates += 1
last_index = length - possible_duplicates
# going right to left and placing elements at their correct index
# also, duplicating zeros
for right in range(last_index, -1, -1):
if arr[right] == 0:
arr[right + possible_duplicates] = arr[right] # or 0
# decrement zero
possible_duplicates -= 1
arr[right + possible_duplicates] = arr[right] # or 0, duplicating zero
else:
arr[right + possible_duplicates] = arr[right] | duplicate-zeros | Think it through | satyamsinha93 | 0 | 51 | duplicate zeros | 1,089 | 0.515 | Easy | 17,294 |
https://leetcode.com/problems/duplicate-zeros/discuss/1851144/Easy-to-understand-python-solution | class Solution(object):
def duplicateZeros(self, arr):
i=0
while(i<len(arr)):
if(arr[i] != 0):
i+=1
else:
arr.insert(i+1, 0)
i+=2
arr.pop() | duplicate-zeros | Easy to understand python solution | arvindrao | 0 | 132 | duplicate zeros | 1,089 | 0.515 | Easy | 17,295 |
https://leetcode.com/problems/duplicate-zeros/discuss/1809454/4-Lines-Python-Solution-oror-82-Faster-oror-Memory-less-than-70 | class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
i = 0
while i < len(arr)-1:
if arr[i]==0: arr.insert(i+1,0) ; arr.pop() ; i+=1
i+=1 | duplicate-zeros | 4-Lines Python Solution || 82% Faster || Memory less than 70% | Taha-C | 0 | 185 | duplicate zeros | 1,089 | 0.515 | Easy | 17,296 |
https://leetcode.com/problems/duplicate-zeros/discuss/1658568/Python-dollarolution | class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
"""
Do not return anything, modify arr in-place instead.
"""
i = 0
while i < len(arr):
if arr[i] == 0:
arr.pop()
arr.insert(i,0)
i += 2
continue
i += 1 | duplicate-zeros | Python $olution | AakRay | 0 | 167 | duplicate zeros | 1,089 | 0.515 | Easy | 17,297 |
https://leetcode.com/problems/duplicate-zeros/discuss/1650341/Python-or-Faster-than-93.7 | class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
"""
Do not return anything, modify arr in-place instead.
"""
n = len(arr)
x = 0
if n > 0 and 0 in arr and arr.count(0) != n:
while x<n :
if arr[x] == 0:
arr.insert(x+1,0)
arr.pop()
x=x+2
else:
x=x+1 | duplicate-zeros | Python | Faster than 93.7% | karthike043 | 0 | 147 | duplicate zeros | 1,089 | 0.515 | Easy | 17,298 |
https://leetcode.com/problems/duplicate-zeros/discuss/1620652/python-solution | class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
i=0
while i < len(arr):
if arr[i] == 0:
arr.insert(i, 0)
arr.pop()
i+=1
i+=1 | duplicate-zeros | python solution | cacacola | 0 | 111 | duplicate zeros | 1,089 | 0.515 | Easy | 17,299 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.