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/flipping-an-image/discuss/381193/Solution-in-Python-3-(one-line) | class Solution:
def flipAndInvertImage(self, A: List[List[int]]) -> List[List[int]]:
return [[1 - i for i in i[::-1]] for i in A]
- Junaid Mansuri
(LeetCode ID)@hotmail.com | flipping-an-image | Solution in Python 3 (one line) | junaidmansuri | 1 | 324 | flipping an image | 832 | 0.805 | Easy | 13,500 |
https://leetcode.com/problems/flipping-an-image/discuss/325340/Python3-faster-than-98.47.-Understandable-method | class Solution:
def flipAndInvertImage(self, A: List[List[int]]) -> List[List[int]]:
"""
:type A: List[List[int]]
:rtype : List[List[int]]
"""
output = []
for index, List in enumerate(A):
List.reverse()
targetList = [abs((x-1)) for x in List]
output.append(targetList)
return output | flipping-an-image | Python3, faster than 98.47%. Understandable method | fisherish | 1 | 337 | flipping an image | 832 | 0.805 | Easy | 13,501 |
https://leetcode.com/problems/flipping-an-image/discuss/2848365/Python-Easy-Solution-99.81-Faster | class Solution:
def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
m,n=len(image),len(image[0])
for i in range(m):
image[i]=image[i][-1::-1]
for i in range(m):
for j in range(n):
if image[i][j]==0:
image[i][j]=1
else:
image[i][j]=0
return image | flipping-an-image | Python Easy Solution 99.81% Faster | DareDevil_007 | 0 | 1 | flipping an image | 832 | 0.805 | Easy | 13,502 |
https://leetcode.com/problems/flipping-an-image/discuss/2817560/Python-or-Easy-Solution-or-Loops | class Solution:
def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
for i in range(len(image)):
for j in range(len(image[i])):
if image[i][j] == 0:
image[i][j] = 1
else:
image[i][j] = 0
image[i] = image[i][::-1]
return image | flipping-an-image | Python | Easy Solution | Loops | atharva77 | 0 | 2 | flipping an image | 832 | 0.805 | Easy | 13,503 |
https://leetcode.com/problems/flipping-an-image/discuss/2811622/(-)-Easy-Simple-Commented-Linear-Solution | class Solution(object):
def flipAndInvertImage(self, image):
for row in range(len(image)): #traverse the image
l=0 #for every row initialize left pointer
r=len(image[row])-1 #row pointer
while l<=r: #swap the left and right pointer
if image[row][l]==0:
image[row][l]=1
else:
image[row][l]=0
if l!=r: #to prevent edge case of inverting the same number twice
if image[row][r]==0:
image[row][r]=1
else:
image[row][r]=0
image[row][l], image[row][r]=image[row][r], image[row][l]
l+=1
r-=1
return image | flipping-an-image | ( ͡° ͜ʖ ͡°) Easy Simple Commented Linear Solution | fa19-bcs-016 | 0 | 2 | flipping an image | 832 | 0.805 | Easy | 13,504 |
https://leetcode.com/problems/flipping-an-image/discuss/2781703/Python3-solution-one-liner-using-bitwise-xor | class Solution:
def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
return [[n^1 for n in i][::-1] for i in image] | flipping-an-image | Python3 solution one-liner using bitwise xor | sipi09 | 0 | 3 | flipping an image | 832 | 0.805 | Easy | 13,505 |
https://leetcode.com/problems/flipping-an-image/discuss/2774995/Python-Solution-or-87.66-Faster | class Solution:
def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
n = len(image)
# reversing each row
for i in range(n):
image[i] = image[i][::-1]
# inverting each element
for i in range(n):
for j in range(n):
if image[i][j] == 0:
image[i][j] = 1
else:
image[i][j] = 0
return image | flipping-an-image | Python Solution | 87.66% Faster | u1704093 | 0 | 4 | flipping an image | 832 | 0.805 | Easy | 13,506 |
https://leetcode.com/problems/flipping-an-image/discuss/2763690/Very-simple-solution-using-python | class Solution:
def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
res = []
for i in image:
res.append([x ^ 1 for x in i[::-1]])
return res | flipping-an-image | Very simple solution using python | ankurbhambri | 0 | 5 | flipping an image | 832 | 0.805 | Easy | 13,507 |
https://leetcode.com/problems/flipping-an-image/discuss/2739470/Python3-or-List-Comprehension-or-One-Liner | class Solution:
def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
return [reversed([1 if y==0 else 0 for y in x]) for x in image] | flipping-an-image | Python3 | List Comprehension | One-Liner | keioon | 0 | 2 | flipping an image | 832 | 0.805 | Easy | 13,508 |
https://leetcode.com/problems/flipping-an-image/discuss/2739429/easy-python-iteration-for-each-element-of-list | class Solution:
def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
for x in range(len(image)):
image[x].reverse()
for x in range(len(image)):
for i in range(len(image[x])):
if image[x][i]==1:
image[x][i]=0
else:
image[x][i]=1
return image | flipping-an-image | easy python iteration for each element of list | sahityasetu1996 | 0 | 4 | flipping an image | 832 | 0.805 | Easy | 13,509 |
https://leetcode.com/problems/flipping-an-image/discuss/2715287/Python-3-beats-70.4 | class Solution:
def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
for j in range(len(image)):
image[j].reverse()
for i in range(len(image)):
for j in range(len(image)):
if image[i][j]==1:
image[i][j]=0
else:
image[i][j]=1
return image | flipping-an-image | Python 3 beats 70.4% | rutwikrp | 0 | 2 | flipping an image | 832 | 0.805 | Easy | 13,510 |
https://leetcode.com/problems/flipping-an-image/discuss/2671209/2-ways-or-python-code | class Solution:
def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
for i in image:
i.reverse()
if i==None:
continue
for j in range(len(i)):
i[j]=int(not(i[j]))
return image | flipping-an-image | 2 ways | python code | ayushigupta2409 | 0 | 28 | flipping an image | 832 | 0.805 | Easy | 13,511 |
https://leetcode.com/problems/flipping-an-image/discuss/2671209/2-ways-or-python-code | class Solution:
def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
for i in image:
i.reverse()
if i==None:
continue
for j in range(len(i)):
if i[j] == 0:
i[j]=1
else:
i[j]=0
return image | flipping-an-image | 2 ways | python code | ayushigupta2409 | 0 | 28 | flipping an image | 832 | 0.805 | Easy | 13,512 |
https://leetcode.com/problems/flipping-an-image/discuss/2627071/Pyhton3-Solution-oror-Nested-For-loops-oror-O(N2) | class Solution:
def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
anew = []
new = []
for i in image:
i = i[::-1]
new.append(i)
for i in new:
for j in range(len(i)):
if i[j] == 1:
i[j] = 0
else:
i[j] = 1
anew.append(i)
return(anew) | flipping-an-image | Pyhton3 Solution || Nested For loops || O(N^2) | shashank_shashi | 0 | 6 | flipping an image | 832 | 0.805 | Easy | 13,513 |
https://leetcode.com/problems/flipping-an-image/discuss/2454024/Pythonoror-Easy-to-understandoror-99-faster-sol | class Solution:
def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
for i in range(len(image)):
image[i] = list(reversed(image[i]))
for i in range(len(image)):
for j in range(len(image)):
if image[i][j] == 0:
image[i][j] = 1
else:
image[i][j] = 0
return image | flipping-an-image | Python|| Easy to understand|| 99% faster sol | sk4213 | 0 | 13 | flipping an image | 832 | 0.805 | Easy | 13,514 |
https://leetcode.com/problems/flipping-an-image/discuss/2404810/Python-solution | class Solution:
def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
flipped_inverted_image = []
for i in image:
for j in range(len(list(reversed(i)))):
if i[j] == 0:
i[j] = 1
else:
i[j] = 0
flipped_inverted_image.append(list(reversed(i)))
return flipped_inverted_image | flipping-an-image | Python solution | samanehghafouri | 0 | 10 | flipping an image | 832 | 0.805 | Easy | 13,515 |
https://leetcode.com/problems/flipping-an-image/discuss/2378360/Python-1-liner-98.8-speed-97-mem | class Solution:
def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
return [[(1 - i) for i in row[::-1]] for row in image] | flipping-an-image | Python 1-liner, 98.8 % speed, 97 % mem | amaargiru | 0 | 56 | flipping an image | 832 | 0.805 | Easy | 13,516 |
https://leetcode.com/problems/flipping-an-image/discuss/2237831/PYTHON-SOLUTION | class Solution:
def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
for row in image:
row.reverse()
for i in range(len(row)):
if row[i]==1:
row[i] = 0
else:
row[i] = 1
return image | flipping-an-image | PYTHON SOLUTION | aakarshvermaofficial | 0 | 54 | flipping an image | 832 | 0.805 | Easy | 13,517 |
https://leetcode.com/problems/flipping-an-image/discuss/2163903/basic-solution | class Solution:
def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
# iterate each row in order
# create a start index to see where to play a new "pixel"
# iterate the row from the bottom up setting the position at start index
# to be its opposite, increment start every time you peform this operation
# make sure start is set back to 0 every row iteration
# Time: O(N) Space: O(1)
n = len(image[0])
for row in image:
for i in range(n):
if row[i]:
row[i] = 0
else:
row[i] = 1
row.reverse()
return image | flipping-an-image | basic solution | andrewnerdimo | 0 | 23 | flipping an image | 832 | 0.805 | Easy | 13,518 |
https://leetcode.com/problems/flipping-an-image/discuss/2160654/Simple-Logic-in-python | class Solution:
def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
return [[1-i for i in row[::-1]] for row in image] | flipping-an-image | Simple Logic in python | writemeom | 0 | 33 | flipping an image | 832 | 0.805 | Easy | 13,519 |
https://leetcode.com/problems/flipping-an-image/discuss/2160654/Simple-Logic-in-python | class Solution:
def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
return [[1^ i for i in reversed(row)] for row in image] | flipping-an-image | Simple Logic in python | writemeom | 0 | 33 | flipping an image | 832 | 0.805 | Easy | 13,520 |
https://leetcode.com/problems/flipping-an-image/discuss/2057243/Python-Solution-or-One-Liner-or-Simple-Logic | class Solution:
def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
return [[1 if cell == 0 else 0 for cell in row[::-1]] for row in image] | flipping-an-image | Python Solution | One-Liner | Simple Logic | Gautam_ProMax | 0 | 52 | flipping an image | 832 | 0.805 | Easy | 13,521 |
https://leetcode.com/problems/flipping-an-image/discuss/2031370/Python-solution | class Solution:
def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
ans = []
for i in image:
ans.append(i[::-1])
def invert(arr):
for i in range(len(arr)):
if arr[i] == 1:
arr[i] = 0
else:
arr[i] = 1
for i in ans:
invert(i)
return ans | flipping-an-image | Python solution | StikS32 | 0 | 45 | flipping an image | 832 | 0.805 | Easy | 13,522 |
https://leetcode.com/problems/flipping-an-image/discuss/1888963/python3-solution-faster-96.8 | class Solution:
def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
res = []
for row in image:
row2 = []
for i in row[::-1]:
if i == 1:
row2.append(0)
else:
row2.append(1)
res.append(row2)
return res | flipping-an-image | python3 solution faster 96.8% | azazellooo | 0 | 66 | flipping an image | 832 | 0.805 | Easy | 13,523 |
https://leetcode.com/problems/flipping-an-image/discuss/1885254/Python3-solution-(faster-than-99.3) | class Solution:
def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
for arr in image:
left, right = 0, len(arr) - 1
while left < right:
arr[left], arr[right] = arr[right], arr[left]
left, right = left + 1, right - 1
for idx in range(len(arr)):
arr[idx] ^= 1
return image | flipping-an-image | Python3 solution (faster than 99.3%) | lxnwi3 | 0 | 20 | flipping an image | 832 | 0.805 | Easy | 13,524 |
https://leetcode.com/problems/flipping-an-image/discuss/1881415/Python-solution-faster-than-91 | class Solution:
def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
res = []
for i in image:
rev = i[::-1]
temp = []
for j in rev:
if j == 0:
temp.append(1)
else:
temp.append(0)
res.append(temp)
return res | flipping-an-image | Python solution faster than 91% | alishak1999 | 0 | 37 | flipping an image | 832 | 0.805 | Easy | 13,525 |
https://leetcode.com/problems/flipping-an-image/discuss/1877688/python-3-oror-one-pass-and-in-place | class Solution:
def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
n = len(image)
for row in image:
for i in range((n + 1) // 2):
row[i], row[~i] = row[~i] ^ 1, row[i] ^ 1
return image | flipping-an-image | python 3 || one pass and in place | dereky4 | 0 | 69 | flipping an image | 832 | 0.805 | Easy | 13,526 |
https://leetcode.com/problems/flipping-an-image/discuss/1862057/Python-(Simple-Approach-and-Beginner-Friendly) | class Solution:
def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
output = []
for i in range(len(image)):
for j in range(len(image[i])):
if image[i][j] == 0:
image[i][j] = 1
else:
image[i][j] = 0
for i in range(len(image)):
output.append(image[i][::-1])
return output | flipping-an-image | Python (Simple Approach and Beginner-Friendly) | vishvavariya | 0 | 38 | flipping an image | 832 | 0.805 | Easy | 13,527 |
https://leetcode.com/problems/flipping-an-image/discuss/1848373/Python-Simple-and-Concise!-Map | class Solution(object):
def flipAndInvertImage(self, image):
def flipImage(image):
return map(reversed, image)
def invert(bit):
return int(not bit)
def invertImage(image):
return map(lambda row: map(lambda bit: invert(bit), row), image)
image = flipImage(image)
image = invertImage(image)
return image | flipping-an-image | Python - Simple and Concise! Map | domthedeveloper | 0 | 32 | flipping an image | 832 | 0.805 | Easy | 13,528 |
https://leetcode.com/problems/flipping-an-image/discuss/1848373/Python-Simple-and-Concise!-Map | class Solution(object):
def flipAndInvertImage(self, img):
return map(lambda r: map(lambda b: int(not b), r), map(reversed, img)) | flipping-an-image | Python - Simple and Concise! Map | domthedeveloper | 0 | 32 | flipping an image | 832 | 0.805 | Easy | 13,529 |
https://leetcode.com/problems/flipping-an-image/discuss/1830741/1-Line-Python-Solution-oror-40-Faster-oror-Memory-less-than-80 | class Solution:
def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
return [(str(x).replace("1", "2").replace("0", "1").replace("2", "0")).strip('][').split(', ')[::-1] for x in image] | flipping-an-image | 1-Line Python Solution || 40% Faster || Memory less than 80% | Taha-C | 0 | 46 | flipping an image | 832 | 0.805 | Easy | 13,530 |
https://leetcode.com/problems/flipping-an-image/discuss/1830741/1-Line-Python-Solution-oror-40-Faster-oror-Memory-less-than-80 | class Solution:
def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
return [[0 if x==1 else 1 for x in X][::-1] for X in image] | flipping-an-image | 1-Line Python Solution || 40% Faster || Memory less than 80% | Taha-C | 0 | 46 | flipping an image | 832 | 0.805 | Easy | 13,531 |
https://leetcode.com/problems/flipping-an-image/discuss/1830741/1-Line-Python-Solution-oror-40-Faster-oror-Memory-less-than-80 | class Solution:
def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
return [[abs(x-1) for x in X][::-1] for X in image] | flipping-an-image | 1-Line Python Solution || 40% Faster || Memory less than 80% | Taha-C | 0 | 46 | flipping an image | 832 | 0.805 | Easy | 13,532 |
https://leetcode.com/problems/flipping-an-image/discuss/1788727/Sort-of-fast-one-liner-for-Python | class Solution:
def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
return [[0 if j == 1 else 1 if j == 0 else j for j in i] for i in [i[::-1] for i in image]] | flipping-an-image | Sort-of fast one-liner for Python | y-arjun-y | 0 | 73 | flipping an image | 832 | 0.805 | Easy | 13,533 |
https://leetcode.com/problems/flipping-an-image/discuss/1681595/Python-O(N2)-Solutions-for-beginners | class Solution:
def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
x = []
for i in range(len(image)):
y = image[i][::-1]
x.append(y)
for i in range(len(x)):
for j in range(len(x[i])):
if x[i][j] == 0:
x[i][j] = 1
else:
x[i][j] = 0
return x | flipping-an-image | Python O(N^2) Solutions , for beginners | Ron99 | 0 | 60 | flipping an image | 832 | 0.805 | Easy | 13,534 |
https://leetcode.com/problems/flipping-an-image/discuss/1678686/Python-3-faster-than-83.89-of-Python3-online-submissions | class Solution:
def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
output = []
for row in image:
innerrow =[]
for ele in range(len(row)-1,-1,-1):
innerrow.append(row[ele] ^ 1 )
output.append(innerrow)
return output | flipping-an-image | Python 3 faster than 83.89% of Python3 online submissions | Vnode12 | 0 | 33 | flipping an image | 832 | 0.805 | Easy | 13,535 |
https://leetcode.com/problems/flipping-an-image/discuss/1640439/Python-98 | class Solution:
def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
flip = []
for m in image:
n = []
m.reverse()
for el in m:
n.append(1 if el == 0 else 0)
flip.append(n)
return flip | flipping-an-image | Python 98% | CleverUzbek | 0 | 54 | flipping an image | 832 | 0.805 | Easy | 13,536 |
https://leetcode.com/problems/flipping-an-image/discuss/1394793/Python3-Faster-than-95-of-the-Solutions | class Solution:
def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
output = []
for i in image:
x = []
for j in i[::-1]:
x.append(1-j)
output.append(x)
return output | flipping-an-image | Python3 - Faster than 95% of the Solutions | harshitgupta323 | 0 | 52 | flipping an image | 832 | 0.805 | Easy | 13,537 |
https://leetcode.com/problems/flipping-an-image/discuss/1390089/WEEB-DOES-PYTHON | class Solution:
def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
row, col = len(image), len(image[0])
for i in range(row):
image[i] = image[i][::-1]
for j in range(col):
image[i][j] = abs(image[i][j] - 1)
return image | flipping-an-image | WEEB DOES PYTHON | Skywalker5423 | 0 | 98 | flipping an image | 832 | 0.805 | Easy | 13,538 |
https://leetcode.com/problems/find-and-replace-in-string/discuss/1920198/Python-3-or-simple-or-3-lines-of-code-w-explanation | class Solution:
def findReplaceString(self, s: str, indices: List[int], sources: List[str], targets: List[str]) -> str:
# iterate from the greater index to the smallest
for i, src, tg in sorted(list(zip(indices, sources, targets)), reverse=True):
# if found the pattern matches with the source, replace with the target accordingly
if s[i:i+len(src)] == src: s = s[:i] + tg + s[i+len(src):]
return s | find-and-replace-in-string | Python 3 | simple | 3 lines of code w/ explanation | Ploypaphat | 3 | 327 | find and replace in string | 833 | 0.541 | Medium | 13,539 |
https://leetcode.com/problems/find-and-replace-in-string/discuss/1721047/Python-solution-with-comments-no-slicing-no-startswith-beats-98 | class Solution:
def findReplaceString(self, s: str, indices: List[int], sources: List[str], targets: List[str]) -> str:
res=[]
i=0
replace_map={i:(s,t) for i,s,t in zip( indices, sources, targets ) }
while i<len(s):
if i in replace_map: #check all chars
done,p,sw_ind=0,i,0 #done: to check if all word was seen in s, p:pointer of s, sw_ind:pointer for char is source word
source_word=replace_map[i][0]
target=replace_map[i][1]
while p<len(s) and sw_ind<len(source_word) and s[p]==source_word[sw_ind]:
done+=1
p+=1
sw_ind+=1
if done==len(source_word): #so all source word was found, append target to res and advance i
res.append(target)
i=i+len(source_word)
else: #so not all sourcce-word was found so append (i) to res and continue normally
res.append(s[i])
i+=1
else: #index not to be replaced append to res
res.append(s[i])
i+=1
return "".join(res) | find-and-replace-in-string | Python🐍 solution with comments, no slicing no startswith beats 98% | InjySarhan | 3 | 362 | find and replace in string | 833 | 0.541 | Medium | 13,540 |
https://leetcode.com/problems/find-and-replace-in-string/discuss/1383264/Python-3-or-Sorting-String-Two-Pass-or-Explanation | class Solution:
def findReplaceString(self, s: str, indices: List[int], sources: List[str], targets: List[str]) -> str:
match = sorted([(idx, i, len(sources[i])) for i, idx in enumerate(indices) if s[idx:].startswith(sources[i])])
if not match: return s
ans, cur = '', 0
for idx, i, n in match:
ans += s[cur:idx] + targets[i]
cur = idx + n
else:
ans += s[cur:]
return ans | find-and-replace-in-string | Python 3 | Sorting, String, Two Pass | Explanation | idontknoooo | 2 | 495 | find and replace in string | 833 | 0.541 | Medium | 13,541 |
https://leetcode.com/problems/find-and-replace-in-string/discuss/1993735/Python-soln | class Solution:
def findReplaceString(self, s: str, indices: List[int], sources: List[str], targets: List[str]) -> str:
ans=list(s)
for i in range(len(indices)):
ind=indices[i]
flag=True
for ch in sources[i]:
if ind>=len(s) or ch!=s[ind]:
flag=False
break
ind+=1
if flag:
ans[indices[i]]=targets[i]#Replace the start index value with the target word and keep the rest as ''
for j in range(indices[i]+1,ind):
ans[j]=''
return ''.join(ans) | find-and-replace-in-string | Python soln | heckt27 | 1 | 79 | find and replace in string | 833 | 0.541 | Medium | 13,542 |
https://leetcode.com/problems/find-and-replace-in-string/discuss/2843019/SIMPLE-PYTHON-SOLUTION | class Solution:
def findReplaceString(self, s: str, indices: List[int], sources: List[str], targets: List[str]) -> str:
res = ''
hashMap = {} #current -> mapping
#current string
zip_map = list(zip(indices, sources, targets))
for index, source_string, target in zip_map:
if s[index : index + len(source_string)] == source_string:
hashMap[index] = target
i = 0
indices_to_sources = {}
for ind, source_string in list(zip(indices, sources)):
indices_to_sources[ind] = source_string
while i < len(s):
print(i, res)
if i in hashMap:
res += hashMap[i]
i += len(indices_to_sources[i])
else:
res += s[i]
i += 1
return res | find-and-replace-in-string | SIMPLE PYTHON SOLUTION | PratikGehlot | 0 | 1 | find and replace in string | 833 | 0.541 | Medium | 13,543 |
https://leetcode.com/problems/find-and-replace-in-string/discuss/2524168/Easy-to-understand-or-Python-or-O(N)-or-Explained-with-comments | class Solution:
def findReplaceString(self, s: str, indices: List[int], sources: List[str], targets: List[str]) -> str:
res = list(s) # initialize the string as a char array
for i in range(len(indices)):
start = indices[i]
end = indices[i] + len(sources[i])
# if repalcement condition match
if s[start:end] == sources[i]:
# replace the first index of res to target
res[indices[i]] = targets[i]
# for res[start+1, end], remove other character up until end pointer
for i in range(start+1, end):
res[i] = ''
return ''.join(res) | find-and-replace-in-string | Easy to understand | Python | O(N) | Explained with comments | amany5642 | 0 | 65 | find and replace in string | 833 | 0.541 | Medium | 13,544 |
https://leetcode.com/problems/find-and-replace-in-string/discuss/2247952/Python-easy-and-understandable-solution | class Solution:
def findReplaceString(self, s: str, indices: List[int], sources: List[str], targets: List[str]) -> str:
match=[-1]*len(s)
for i in range(len(indices)):
if s[indices[i]:indices[i]+len(sources[i])] == sources[i]:
match[indices[i]]=i
ans=''
i=0
while(i<len(s)):
if match[i]!=-1:
ans+=targets[match[i]]
i+=len(sources[match[i]])
else:
ans+=s[i]
i+=1
return ans | find-and-replace-in-string | Python easy and understandable solution | coderash1998 | 0 | 85 | find and replace in string | 833 | 0.541 | Medium | 13,545 |
https://leetcode.com/problems/find-and-replace-in-string/discuss/1456572/Python-Sorting-and-Iterative-Solution | class Solution:
def findReplaceString(self, s: str, indices: List[int], sources: List[str], targets: List[str]) -> str:
if not s: return None
ans = []
i = j = 0
z = sorted(zip(indices, sources, targets)) # 0=indices, 1=sources, 2=targets
while i < len(s):
if j < len(z) and i == z[j][0]:
if s[i:].startswith(z[j][1]):
ans.append(z[j][2])
i += len(z[j][1])
j += 1
continue
j += 1
ans.append(s[i])
i += 1
return "".join(ans) | find-and-replace-in-string | Python Sorting and Iterative Solution | syii | 0 | 146 | find and replace in string | 833 | 0.541 | Medium | 13,546 |
https://leetcode.com/problems/find-and-replace-in-string/discuss/1456572/Python-Sorting-and-Iterative-Solution | class Solution:
def findReplaceString(self, s: str, indices: List[int], sources: List[str], targets: List[str]) -> str:
if not s: return None
ans = []
i = j = 0
while i < len(s):
if j < len(indices) and i == indices[j]:
if s[i:].startswith(sources[j]):
ans.append(targets[j])
i += len(sources[j])
j += 1
continue
j += 1
ans.append(s[i])
i += 1
return "".join(ans) | find-and-replace-in-string | Python Sorting and Iterative Solution | syii | 0 | 146 | find and replace in string | 833 | 0.541 | Medium | 13,547 |
https://leetcode.com/problems/find-and-replace-in-string/discuss/993041/Python-solution-with-short-explanation | class Solution:
def findReplaceString(self, S: str, indexes: List[int], sources: List[str], targets: List[str]) -> str:
'''
Keep S_idx, new string, and a map of indexes to source and target.
Iterate over S. If S_idx is in the map, check if S[idx:idx+len(source)] == source.
If so, add target to new string, and advance S_idx by len(source).
If not, add S[S_idx] to new string and add 1 to S_idx.
'''
S_idx = 0
new_string = []
d = {}
for i in range(len(indexes)):
idx, src, target = indexes[i], sources[i], targets[i]
d[idx] = (src, target)
while S_idx < len(S):
if S_idx in d:
source, target = d[S_idx]
if S[S_idx:S_idx+len(source)] == source:
new_string.append(target)
S_idx += len(source)
continue
new_string.append(S[S_idx])
S_idx += 1
return ''.join(new_string) | find-and-replace-in-string | Python solution with short explanation | gins1 | 0 | 169 | find and replace in string | 833 | 0.541 | Medium | 13,548 |
https://leetcode.com/problems/find-and-replace-in-string/discuss/937262/Python3-right-to-left | class Solution:
def findReplaceString(self, S: str, indexes: List[int], sources: List[str], targets: List[str]) -> str:
for i, s, t in sorted(zip(indexes, sources, targets), reverse=True):
if S[i:i+len(s)] == s: S = S[:i] + t + S[i+len(s):]
return S | find-and-replace-in-string | [Python3] right to left | ye15 | 0 | 75 | find and replace in string | 833 | 0.541 | Medium | 13,549 |
https://leetcode.com/problems/sum-of-distances-in-tree/discuss/1311639/Python3-post-order-and-pre-order-dfs | class Solution:
def sumOfDistancesInTree(self, n: int, edges: List[List[int]]) -> List[int]:
graph = {}
for u, v in edges:
graph.setdefault(u, []).append(v)
graph.setdefault(v, []).append(u)
size = [0]*n
def fn(x, par):
"""Return size and sum of distances in sub-tree."""
c = s = 0
for xx in graph.get(x, []):
if xx != par:
cc, ss = fn(xx, x)
c, s = c + cc, s + ss + cc
size[x] = c + 1
return c + 1, s
ans = [0]*n
ans[0] = fn(0, -1)[1]
stack = [0]
while stack:
x = stack.pop()
for xx in graph.get(x, []):
if not ans[xx]:
ans[xx] = ans[x] + n - 2*size[xx]
stack.append(xx)
return ans | sum-of-distances-in-tree | [Python3] post-order & pre-order dfs | ye15 | 2 | 195 | sum of distances in tree | 834 | 0.542 | Hard | 13,550 |
https://leetcode.com/problems/sum-of-distances-in-tree/discuss/2715823/Python-easy-to-read-and-understand-or-graph | class Solution:
def sumOfDistancesInTree(self, n: int, edges: List[List[int]]) -> List[int]:
g = collections.defaultdict(list)
for u, v in edges:
g[u].append(v)
g[v].append(u)
res = [0]*n
for i in range(n):
q = [i]
visit = set()
visit.add(i)
step, cnt = 1, 0
while q:
num = len(q)
for j in range(num):
node = q.pop(0)
for nei in g[node]:
if nei not in visit:
cnt += step
visit.add(nei)
q.append(nei)
if q:step+=1
res[i] = cnt
return res | sum-of-distances-in-tree | Python easy to read and understand | graph | sanial2001 | 0 | 13 | sum of distances in tree | 834 | 0.542 | Hard | 13,551 |
https://leetcode.com/problems/sum-of-distances-in-tree/discuss/2715823/Python-easy-to-read-and-understand-or-graph | class Solution:
def sumOfDistancesInTree(self, n: int, edges: List[List[int]]) -> List[int]:
g = collections.defaultdict(list)
for u, v in edges:
g[u].append(v)
g[v].append(u)
d = {i:[1, 0] for i in range(n)}
def dfs(root, prev):
for nei in g[root]:
if nei != prev:
dfs(nei, root)
d[root][0] += d[nei][0]
d[root][1] += (d[nei][0] + d[nei][1])
def dfs2(root, prev):
for nei in g[root]:
if nei != prev:
d[nei][1] = d[root][1] - d[nei][0] + (n-d[nei][0])
dfs2(nei, root)
dfs(0, -1)
dfs2(0, -1)
res = []
for key in d:
res.append(d[key][1])
return res | sum-of-distances-in-tree | Python easy to read and understand | graph | sanial2001 | 0 | 13 | sum of distances in tree | 834 | 0.542 | Hard | 13,552 |
https://leetcode.com/problems/sum-of-distances-in-tree/discuss/2631779/DFS-twice-in-Python-easy-to-understand | class Solution:
def dfs1(self, v):
self.visited.add(v)
self.results[v] = [0, 0]
for u in self.graph[v]:
if u not in self.visited:
self.dfs1(u)
self.results[v][1] += self.results[u][1] + (self.results[u][0] + 1)
self.results[v][0] += self.results[u][0] + 1
def dfs2(self, v, parent):
self.visited.add(v)
if parent != -1:
self.results[v][1] += self.results[parent][1] - (self.results[v][1] + self.results[v][0] + 1) + (
self.results[parent][0] - (self.results[v][0] + 1) + 1)
self.results[v][0] += self.results[parent][0] - (self.results[v][0] + 1) + 1
for u in self.graph[v]:
if u not in self.visited:
self.dfs2(u, v)
def sumOfDistancesInTree(self, n: int, edges: List[List[int]]) -> List[int]:
self.results = defaultdict(int)
self.graph = defaultdict(set)
for v, u in edges:
self.graph[v].add(u)
self.graph[u].add(v)
self.visited = set()
self.dfs1(0)
self.visited = set()
self.dfs2(0, -1)
return [self.results[k][1] for k in range(n)] | sum-of-distances-in-tree | DFS twice in Python, easy to understand | metaphysicalist | 0 | 10 | sum of distances in tree | 834 | 0.542 | Hard | 13,553 |
https://leetcode.com/problems/sum-of-distances-in-tree/discuss/2532604/python3-fw-and-dfs-sol-for-ref | class Solution:
def sumOfDistancesInTree(self, n: int, edges: List[List[int]]) -> List[int]:
dp = [[float('inf') for _ in range(n)] for _ in range(n)]
for s,e in edges:
dp[s][e] = 1
dp[e][s] = 1
for i in range(n):
dp[i][i] = 0
for k in range(n):
for j in range(n):
for i in range(n):
dp[i][j] = min(dp[i][j], dp[i][k] + dp[k][j])
ans = []
for i in range(n):
s = 0
for j in range(n):
s += dp[i][j] if dp[i][j] != float('inf') else 0
ans.append(s)
return ans | sum-of-distances-in-tree | [python3] fw and dfs sol for ref | vadhri_venkat | 0 | 37 | sum of distances in tree | 834 | 0.542 | Hard | 13,554 |
https://leetcode.com/problems/sum-of-distances-in-tree/discuss/2532604/python3-fw-and-dfs-sol-for-ref | class Solution:
def sumOfDistancesInTree(self, n: int, edges: List[List[int]]) -> List[int]:
count = [1]*n
res = [0]*n
g = defaultdict(list)
for s,e in edges:
g[s].append(e)
g[e].append(s)
visited = set()
def dfs_count_up_to_0(node):
visited.add(node)
for c in g[node]:
if c not in visited:
count[node] += dfs_count_up_to_0(c)
res[node] += res[c] + count[c]
return count[node]
def dfs_fill_up_rest(node):
visited.add(node)
for c in g[node]:
if c not in visited:
res[c] = res[node] - count[c] + n - count[c]
dfs_fill_up_rest(c)
dfs_count_up_to_0(0)
visited.clear()
dfs_fill_up_rest(0)
return res | sum-of-distances-in-tree | [python3] fw and dfs sol for ref | vadhri_venkat | 0 | 37 | sum of distances in tree | 834 | 0.542 | Hard | 13,555 |
https://leetcode.com/problems/image-overlap/discuss/2748733/Python-(Faster-than-82)-or-Brute-force-(Recursive)-and-optimized-using-HashMap | class Solution:
def largestOverlap(self, img1: List[List[int]], img2: List[List[int]]) -> int:
n = len(img1)
bestOverlap = 0
def helper(dr, dc):
overlap = 0
for r in range(n):
for c in range(n):
nr, nc = r + dr, c + dc
if nr in range(n) and nc in range(n) and img1[nr][nc] == 1 and img2[r][c] == 1:
overlap += 1
return overlap
for r in range(-n, n):
for c in range(-n, n):
bestOverlap = max(helper(r, c), bestOverlap)
return bestOverlap | image-overlap | Python (Faster than 82%) | Brute force (Recursive) and optimized using HashMap | KevinJM17 | 1 | 18 | image overlap | 835 | 0.64 | Medium | 13,556 |
https://leetcode.com/problems/image-overlap/discuss/2748733/Python-(Faster-than-82)-or-Brute-force-(Recursive)-and-optimized-using-HashMap | class Solution:
def largestOverlap(self, img1: List[List[int]], img2: List[List[int]]) -> int:
n = len(img1)
bestOverlap = 0
i1, i2 = [], []
for r in range(n):
for c in range(n):
if img1[r][c] == 1:
i1.append((r, c))
if img2[r][c] == 1:
i2.append((r, c))
overlap = {}
for i1_r, i1_c in i1:
for i2_r, i2_c in i2:
shift = (i2_r - i1_r, i2_c - i1_c)
overlap[shift] = overlap.get(shift, 0) + 1
bestOverlap = max(bestOverlap, overlap[shift])
return bestOverlap | image-overlap | Python (Faster than 82%) | Brute force (Recursive) and optimized using HashMap | KevinJM17 | 1 | 18 | image overlap | 835 | 0.64 | Medium | 13,557 |
https://leetcode.com/problems/image-overlap/discuss/1934449/python3-shift-only-1's | class Solution:
def largestOverlap(self, img1: List[List[int]], img2: List[List[int]]) -> int:
n = len(img1)
list1, list2 = [], []
res = 0
for r in range(n):
for c in range(n):
if img1[r][c]:
list1.append((r, c))
if img2[r][c]:
list2.append((r, c))
shiftDict = defaultdict(int)
for x1, y1 in list1:
for x2, y2 in list2:
dx, dy = x2 - x1, y2 - y1
shiftDict[(dx, dy)] += 1
return max(shiftDict.values()) if shiftDict else 0 | image-overlap | python3 shift only 1's | gulugulugulugulu | 1 | 185 | image overlap | 835 | 0.64 | Medium | 13,558 |
https://leetcode.com/problems/image-overlap/discuss/2750369/Python-O(1)-space-solution-beats-98-in-memory | class Solution:
def largestOverlap(self, img1: List[List[int]], img2: List[List[int]]) -> int:
max_p = 0
n = len(img1)
for r in range(n, 0, - 1):
for d in range(n, 0, - 1):
if max_p >= r * d:
break
t1, t2, t3, t4 = 0, 0, 0, 0
moved_r, moved_d = n - r, n - d
for i in range(moved_r, n):
for j in range(moved_d, n):
if img1[i - moved_r][j - moved_d] == img2[i][j] == 1:
t1 += 1
if img1[i - moved_r][j] == img2[i][j - moved_d] == 1:
t2 += 1
if img1[i][j - moved_d] == img2[i - moved_r][j] == 1:
t3 += 1
if img2[i - moved_r][j - moved_d] == img1[i][j] == 1:
t4 += 1
max_p = max(max_p, t1, t2, t3, t4)
return max_p | image-overlap | Python O(1) space solution, beats 98% in memory | wmf410 | 0 | 10 | image overlap | 835 | 0.64 | Medium | 13,559 |
https://leetcode.com/problems/image-overlap/discuss/2750007/Python-linear-transformation-solution | class Solution:
def largestOverlap(self, A: List[List[int]], B: List[List[int]]) -> int:
N = len(A)
Aones = [(x, y) for x in range(N) for y in range(N) if A[x][y]]
Bones = [(x, y) for x in range(N) for y in range(N) if B[x][y]]
transformationCount = defaultdict(int)
for Ax, Ay in Aones:
for Bx, By in Bones:
vector = (Bx - Ax, By - Ay)
transformationCount[vector] += 1
return max(transformationCount.values(), default = 0) | image-overlap | Python linear transformation solution | SmittyWerbenjagermanjensen | 0 | 15 | image overlap | 835 | 0.64 | Medium | 13,560 |
https://leetcode.com/problems/image-overlap/discuss/2749093/python3-bit-operation-97-speed-98-memory | class Solution:
def largestOverlap(self, img1: List[List[int]], img2: List[List[int]]) -> int:
n = len(img1)
bit_img1 = []
bit_img2 = [0 for _ in range(n-1)]
ans = 0
for i in img1:
tmp = ''
for j in i:
tmp += str(j)
bit_img1.append(int(tmp,2))
for i in img2:
tmp = ''
for j in i:
tmp += str(j)
tmp += '0' * (n-1)
bit_img2.append(int(tmp,2))
for i in range(2*n-1):
for k in range(2*n-1):
tmp = 0
for j in range(n):
if j+i < 2*n-1:
tmp += bin((bit_img1[j] << k) & bit_img2[j+i]).count('1')
ans = max(tmp,ans)
return ans | image-overlap | python3, bit operation, 97% speed, 98% memory | pjy953 | 0 | 28 | image overlap | 835 | 0.64 | Medium | 13,561 |
https://leetcode.com/problems/image-overlap/discuss/2748984/Simple-naive-approach | class Solution:
def largestOverlap(self, img1: List[List[int]], img2: List[List[int]]) -> int:
n = len(img1)
totalSum = 0
def checkOneDirection(img1, img2, is_down, is_right):
nonlocal totalSum
for j in range(n):
for i in range(n):
sum0 = 0
for l in range(n - j):
for k in range(n - i):
i1_1, i2_1 = k, i + k
if not is_down: i1_1, i2_1 = i2_1, i1_1
i1_2, i2_2 = l, j + l
if not is_right: i1_2, i2_2 = i2_2, i1_2
if img1[i1_1][i1_2] and img2[i2_1][i2_2]:
sum0 += 1
totalSum = max(totalSum, sum0)
checkOneDirection(img1, img2, True, True)
checkOneDirection(img1, img2, True, False)
checkOneDirection(img1, img2, False, True)
checkOneDirection(img1, img2, False, False)
return totalSum | image-overlap | Simple naive approach | nonchalant-enthusiast | 0 | 11 | image overlap | 835 | 0.64 | Medium | 13,562 |
https://leetcode.com/problems/image-overlap/discuss/2748643/Brute-Force-Numpy-Solution | class Solution:
def largestOverlap(self, img1: List[List[int]], img2: List[List[int]]) -> int:
N = len(img1)
import numpy as np
img1 = np.array(img1)
img2 = np.array(img2)
img1 = np.pad(img1, N-1, 'constant', constant_values = 0)
res = 0
for i in range(img1.shape[0] - N+1):
for j in range(img1.shape[0] - N+1):
temp_arr = img1[i:i+N, j:j+N]
res = max(res, np.sum(np.logical_and(temp_arr, img2)))
return res | image-overlap | Brute Force Numpy Solution | slavaheroes | 0 | 7 | image overlap | 835 | 0.64 | Medium | 13,563 |
https://leetcode.com/problems/image-overlap/discuss/2748478/Python-3-Solution | class Solution:
def largestOverlap(self, img1: List[List[int]], img2: List[List[int]]) -> int:
"""
Number 835
Since we need to check the overlap after number of shifting whole 1 bit area
1. We first record the img1 1 bit index -> row, column (LocalA)
2. Then record the img2 1 bit index as well (LocalB)
3. For each location in LocalA we caluate the different it to each location to LocalB -> (i,j) in A, (x,y) in B -> different is (i-x,j-y) and then include the counter for this different
4. Go through the location different counter return the maximum number of a different occurs and that is the answer if no different is in the counter then return 0
:param img1:
:param img2:
:return:
"""
img1ValidIndex = [(i, j) for i, row in enumerate(img1) for j, num in enumerate(row) if num]
img2ValidIndex = [(i, j) for i, row in enumerate(img2) for j, num in enumerate(row) if num]
indexCounter = collections.Counter((i - x, j - y) for i, j in img1ValidIndex for x, y in img2ValidIndex)
return 0 if not indexCounter else max(indexCounter.values()) | image-overlap | Python 3 Solution | zxia545 | 0 | 22 | image overlap | 835 | 0.64 | Medium | 13,564 |
https://leetcode.com/problems/image-overlap/discuss/2748295/Python3-Brute-Force-with-Bitmap | class Solution:
def largestOverlap(self, img1: List[List[int]], img2: List[List[int]]) -> int:
"""LeetCode 835
Not hard in terms of figuring out a method, but very complicated in
implementation. First turn both images into bitmaps. Then brute force
it by traversing all possible overlap states. At each state, compute
the number of overlapped positions.
The difficulty lies in accurately finding out the correct bitmap from
both images at each overlapped state to perform the AND operation.
O(N^4), 645 ms, faster than 81.87%
"""
n = len(img1)
bitmap1 = [sum(v << (n - i - 1) for i, v in enumerate(row)) for row in img1]
bitmap2 = [sum(v << (n - i - 1) for i, v in enumerate(row)) for row in img2]
res = 0
for i in range(2 * n - 1):
for j in range(2 * n - 1):
cur = 0
if i <= n - 1:
if j <= n - 1:
for ii in range(n - i - 1, n):
ol = ((bitmap1[ii] & ((1 << (j + 1)) - 1)) << (n - j - 1)) & (bitmap2[ii - (n - i - 1)])
cur += bin(ol).count('1')
else:
for ii in range(n - i - 1, n):
ol = (bitmap1[ii] >> (j - n + 1)) & (bitmap2[ii - (n - i - 1)])
cur += bin(ol).count('1')
else:
if j <= n - 1:
for ii in range(2 * n - i - 1):
ol = ((bitmap1[ii] & ((1 << (j + 1)) - 1)) << (n - j - 1)) & (bitmap2[ii + i - n + 1])
cur += bin(ol).count('1')
else:
for ii in range(2 * n - i - 1):
ol = (bitmap1[ii] >> (j - n + 1)) & (bitmap2[ii + i - n + 1])
cur += bin(ol).count('1')
res = max(res, cur)
return res | image-overlap | [Python3] Brute Force with Bitmap | FanchenBao | 0 | 16 | image overlap | 835 | 0.64 | Medium | 13,565 |
https://leetcode.com/problems/image-overlap/discuss/2747941/Faster-than-94-brute-force-solution | class Solution:
def largestOverlap(self, img1: List[List[int]], img2: List[List[int]]) -> int:
n=len(img1)
dct=defaultdict(int)
lst=[(k, l) for k in range(n) for l in range(n) if img2[k][l]]
for i in range(n):
for j in range(n):
if img1[i][j]:
for k, l in lst:
dct[(i-k, j-l)]+=1
return len(dct) and max(dct.values()) | image-overlap | Faster than 94%, brute force solution | mbeceanu | 0 | 16 | image overlap | 835 | 0.64 | Medium | 13,566 |
https://leetcode.com/problems/image-overlap/discuss/2747914/Python-easy-to-read-and-understand | class Solution:
def largestOverlap(self, img1: List[List[int]], img2: List[List[int]]) -> int:
n = len(img1)
d = collections.defaultdict(int)
t1, t2 = [], []
for i in range(n):
for j in range(n):
if img1[i][j] == 1:
t1.append((i, j))
if img2[i][j] == 1:
t2.append((i, j))
res = 0
for x in t1:
for y in t2:
temp = (y[0]-x[0], y[1]-x[1])
d[temp] += 1
res = max(res, d[temp])
return res | image-overlap | Python easy to read and understand | sanial2001 | 0 | 40 | image overlap | 835 | 0.64 | Medium | 13,567 |
https://leetcode.com/problems/image-overlap/discuss/2747831/Fastest-and-Simplest-Python-Solution | class Solution:
def largestOverlap(self, img1: List[List[int]], img2: List[List[int]]) -> int:
import numpy as np
A = np.array(img1)
B = np.array(img2)
dim = len(A)
# extend the matrix to a wider range for the later kernel extraction.
B_padded = np.pad(B, dim-1, mode='constant', constant_values=(0, 0))
max_overlaps = 0
for x_shift in range(dim*2 - 1):
for y_shift in range(dim* 2 - 1):
# extract a kernel from the padded matrix
kernel = B_padded[x_shift:x_shift+dim, y_shift:y_shift+dim]
# convolution between A and kernel
non_zeros = np.sum(A * kernel)
max_overlaps = max(max_overlaps, non_zeros)
return max_overlaps | image-overlap | Fastest & Simplest Python Solution | avs-abhishek123 | 0 | 17 | image overlap | 835 | 0.64 | Medium | 13,568 |
https://leetcode.com/problems/image-overlap/discuss/2747758/Python3-Bit-masking-O(n3)-Time-Complexity | class Solution:
def largestOverlap(self, img1: List[List[int]], img2: List[List[int]]) -> int:
def bit_mask(image, dx, dy):
bm = 0
n = len(image)
for i in range(n):
x = i - dx
for j in range(n):
y = j - dy
bm <<= 1
if 0 <= x < n and 0 <= y < n and image[x][y]:
bm |= 1
return bm
n = len(img1)
bm2s = [0] * (2 * n - 1)
for dy in range(-n + 1, n):
bm2s[dy] = bit_mask(img2, 0, dy)
res = 0
for dx in range(-n + 1, n):
bm1 = bit_mask(img1, dx, 0)
for dy in range(-n + 1, n):
res = max(res, (bm1 & bm2s[dy]).bit_count())
return res | image-overlap | [Python3] Bit masking, O(n^3) Time Complexity | celestez | 0 | 20 | image overlap | 835 | 0.64 | Medium | 13,569 |
https://leetcode.com/problems/image-overlap/discuss/2747711/Easiest-approach-with-pictures | class Solution:
def largestOverlap(self, img1: List[List[int]], img2: List[List[int]]) -> int:
n = len(img1)
need = set()
have = []
max_overlap = 0
for i in range(n):
for j in range(n):
if img1[i][j] == 1: have.append((i,j))
if img2[i][j] == 1: need.add((i,j))
if img1[i][j] == img2[i][j] == 1: max_overlap += 1
for dx in range(-n+1,n):
for dy in range(-n+1,n):
overlap = 0
for x,y in have:
newx,newy = x+dx,y+dy
if (newx,newy) in need: overlap += 1
max_overlap = max(max_overlap,overlap)
return max_overlap | image-overlap | Easiest approach with pictures | shriyansnaik | 0 | 18 | image overlap | 835 | 0.64 | Medium | 13,570 |
https://leetcode.com/problems/image-overlap/discuss/2749369/Python!-7-Lines-solution. | class Solution:
def largestOverlap(self, img1: List[List[int]], img2: List[List[int]]) -> int:
n = len(img1)
reduce_list = lambda lst: sum([1 << i for i,a in enumerate(lst) if a == 1])
img1, img2 = list(map(reduce_list, img1)), list(map(reduce_list, img2))
count_bits = lambda num: sum((num>>i)&1 for i in range(n))
overlap = lambda lst1, lst2, sx1, sx2, sy1, sy2: sum(count_bits((row1>>sx1) & (row2>>sx2)) for row1,row2 in zip(lst1[sy1:], lst2[sy2:]))
overlap_xy = lambda lst1, lst2, dx, dy: overlap(lst1, lst2, dx if dx > 0 else 0, 0 if dx > 0 else -dx, dy if dy > 0 else 0, 0 if dy > 0 else -dy )
return max(overlap_xy(img1, img2, dx, dy) for dx in range(-n+1, n) for dy in range(-n+1, n)) | image-overlap | 😎Python! 7 Lines solution. | aminjun | -1 | 23 | image overlap | 835 | 0.64 | Medium | 13,571 |
https://leetcode.com/problems/rectangle-overlap/discuss/342095/Solution-in-Python-3-(beats-100)-(-2-lines-) | class Solution:
def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool:
[A,B,C,D], [E,F,G,H] = rec1, rec2
return F<D and E<C and B<H and A<G
- Python 3
- Junaid Mansuri | rectangle-overlap | Solution in Python 3 (beats 100%) ( 2 lines ) | junaidmansuri | 2 | 581 | rectangle overlap | 836 | 0.436 | Easy | 13,572 |
https://leetcode.com/problems/rectangle-overlap/discuss/2239115/Python-3%3A-Readable-solution-with-comments | class Solution(object):
def isRectangleOverlap(self, rec1, rec2):
# TIME and SPACE Complexity: O(1)
#Funtion checking if coordinate of Rec2 overlapped Rec1;
def checkOverlapping(rec1_left, rec1_right, rec2_left, rec2_right):
rec2_StartingCoordinate = max(rec1_left, rec2_left)
rec1_EndingCoordinate = min(rec1_right, rec2_right)
isOverlapped = rec2_StartingCoordinate < rec1_EndingCoordinate
return isOverlapped
#All Horizontal coordinates of Rec1 and Rec2;
rec1HozlLeft = rec1[0]
rec1HozlRight = rec1[2]
rec2HozlLeft = rec2[0]
rec2HozlRight = rec2[2]
#All Vertical coordinates of Rec1 and Rec2;
rec1VerBottom = rec1[1]
rec1VerTop = rec1[3]
rec2VerBottom = rec2[1]
rec2VerTop = rec2[3]
# 1st Check the Horizontal coordinates if Rec2 is overlapped Rec1;
## 2nd Check the Vertical coordinates if Rec2 is Overlapped Rec1;
### return True if both Horizontal and Vertical are Overlapped
return checkOverlapping(rec1HozlLeft, rec1HozlRight, rec2HozlLeft, rec2HozlRight) and \
checkOverlapping(rec1VerBottom, rec1VerTop, rec2VerBottom, rec2VerTop) | rectangle-overlap | Python 3: Readable solution with comments | DDaniel-Dev | 1 | 107 | rectangle overlap | 836 | 0.436 | Easy | 13,573 |
https://leetcode.com/problems/rectangle-overlap/discuss/1839401/1-Line-Python-Solution-oror-99-Faster-(24ms)-oror-Memory-less-than-50 | class Solution:
def isRectangleOverlap(self, R1: List[int], R2: List[int]) -> bool:
return not (R1[0]>=R2[2] or R1[1]>=R2[3] or R1[2]<=R2[0] or R1[3]<=R2[1]) | rectangle-overlap | 1-Line Python Solution || 99% Faster (24ms) || Memory less than 50% | Taha-C | 1 | 134 | rectangle overlap | 836 | 0.436 | Easy | 13,574 |
https://leetcode.com/problems/rectangle-overlap/discuss/632825/Intuitive-approach-by-listing-out-all-cases-for-non-overlapping | class Solution:
def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool:
# 0) Make sure rec2 is always on the right of rec1 for simplicity
if rec1[2] > rec2[2]:
rec1, rec2 = rec2, rec1
# 1) All reasons that cause overlap to be impossible
# - The whole rec2 is on the right side of rec1
# - The whole rec2 is on the top side of rec1
# - The whole rec2 is on the bottom side of rec1
if rec2[0] >= rec1[2] or \
rec2[1] >= rec1[3] or \
rec2[3] <= rec1[1]:
return False
return True | rectangle-overlap | Intuitive approach by listing out all cases for non-overlapping | puremonkey2001 | 1 | 123 | rectangle overlap | 836 | 0.436 | Easy | 13,575 |
https://leetcode.com/problems/rectangle-overlap/discuss/2824513/Easy-understanding | class Solution:
def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool:
# a,b,c,d = 0,1,2,3
a1 = (min(rec1[2],rec2[2]) - max(rec1[0],rec2[0]))
a2 = (min(rec1[3],rec2[3]) - max(rec1[1],rec2[1]))
if a1 > 0 and a2 > 0:
return True
return False | rectangle-overlap | Easy understanding | ding4dong | 0 | 1 | rectangle overlap | 836 | 0.436 | Easy | 13,576 |
https://leetcode.com/problems/rectangle-overlap/discuss/2824062/Python3-solution-using-max-and-min. | class Solution:
def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool:
A, B, C, D = rec1[0], rec1[1] ,rec1[2], rec1[3]
E, F, G, H = rec2[0], rec2[1] ,rec2[2], rec2[3]
left = max(A, E)
right = min(G, C)
bottom = max(F, B)
top = min(D, H)
if right > left and top > bottom:
return True
return False | rectangle-overlap | [Python3] solution using max and min. | BLOCKS | 0 | 5 | rectangle overlap | 836 | 0.436 | Easy | 13,577 |
https://leetcode.com/problems/rectangle-overlap/discuss/2823930/Python-1-line-solution-beats-85-time-98-space | class Solution:
def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool:
return (min(rec1[3],rec2[3]) > max(rec1[1], rec2[1]) and min(rec1[2],rec2[2]) > max(rec1[0], rec2[0])) | rectangle-overlap | Python 1 line solution, beats 85% time, 98% space | Sunsetboy | 0 | 2 | rectangle overlap | 836 | 0.436 | Easy | 13,578 |
https://leetcode.com/problems/rectangle-overlap/discuss/2822369/Simple-minmax | class Solution:
def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool:
# overlap in y
oY = min(rec1[3], rec2[3]) - max(rec1[1], rec2[1])
# overlap in x
oX = min(rec1[2], rec2[2]) - max(rec1[0], rec2[0])
# both overlaps in x and y must be positive
return oX > 0 and oY > 0 | rectangle-overlap | Simple min/max | js44lee | 0 | 1 | rectangle overlap | 836 | 0.436 | Easy | 13,579 |
https://leetcode.com/problems/rectangle-overlap/discuss/2461899/Python-Solution | class Solution:
def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool:
#Finding the overlap of the rectangle
#Runtime: 29ms
overlap=max(min(rec1[2],rec2[2])-max(rec1[0],rec2[0]),0)*max(min(rec1[3],rec2[3])-max(rec1[1],rec2[1]),0)
return True if overlap>0 else False | rectangle-overlap | Python Solution | mehtay037 | 0 | 52 | rectangle overlap | 836 | 0.436 | Easy | 13,580 |
https://leetcode.com/problems/rectangle-overlap/discuss/1792529/Python-Simple | class Solution:
def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool:
# a and b are two projections of squares on one of the axis
def intersects(a1, a2, b1, b2):
if a1 < b1:
return b1 < a2
else:
return a1 < b2
def isHor(): # check X
return intersects(rec1[0], rec1[2], rec2[0], rec2[2])
def isVer(): # check Y
return intersects(rec1[1], rec1[3], rec2[1], rec2[3])
return isHor() and isVer() | rectangle-overlap | Python Simple | sirenko | 0 | 122 | rectangle overlap | 836 | 0.436 | Easy | 13,581 |
https://leetcode.com/problems/rectangle-overlap/discuss/1617518/Python-3-simple-solution-with-comments | class Solution:
def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool:
# most left right corner - most right left corner
x = min(rec1[2], rec2[2]) - max(rec1[0], rec2[0])
# lowest top corner - highest bottom corner
y = min(rec1[3], rec2[3]) - max(rec1[1], rec2[1])
return x > 0 and y > 0 | rectangle-overlap | Python 3 simple solution with comments | dereky4 | 0 | 297 | rectangle overlap | 836 | 0.436 | Easy | 13,582 |
https://leetcode.com/problems/rectangle-overlap/discuss/1559324/Python3-Solution-or-1-line-answer-or-99.72-faster | class Solution:
def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool:
return min(rec1[2],rec2[2])-max(rec1[0],rec2[0])>0 and min(rec1[3],rec2[3])-max(rec1[1],rec2[1])>0 | rectangle-overlap | Python3 Solution | 1 line answer | 99.72% faster | satyam2001 | 0 | 119 | rectangle overlap | 836 | 0.436 | Easy | 13,583 |
https://leetcode.com/problems/rectangle-overlap/discuss/1449190/Simple-Python-O(1)-solution | class Solution:
def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool:
# two rectangles overlap if there height overlaps AND their width overlaps
# two intervals [s1, e1] and [s2, e2] overlaps if max(s1, s2) < min(e1, e2)
x1_rec1, y1_rec1, x2_rec1, y2_rec1 = rec1
x1_rec2, y1_rec2, x2_rec2, y2_rec2 = rec2
return max(x1_rec1, x1_rec2) < min(x2_rec1, x2_rec2) and max(y1_rec1, y1_rec2) < min(y2_rec1, y2_rec2) | rectangle-overlap | Simple Python O(1) solution | Charlesl0129 | 0 | 145 | rectangle overlap | 836 | 0.436 | Easy | 13,584 |
https://leetcode.com/problems/rectangle-overlap/discuss/1444970/Python3-One-Line-Faster-Than-99.02 | class Solution:
def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool:
if max(rec1[0], rec2[0]) < min(rec1[2], rec2[2]) \
and max(rec1[1], rec2[1]) < min(rec1[3], rec2[3]):
return True
return False | rectangle-overlap | Python3 One-Line Faster Than 99.02% | Hejita | 0 | 106 | rectangle overlap | 836 | 0.436 | Easy | 13,585 |
https://leetcode.com/problems/rectangle-overlap/discuss/1251331/Python3-simple-solution-beats-90-users | class Solution:
def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool:
x11 = rec1[0]
y11 = rec1[1]
x21 = rec1[2]
y21 = rec1[3]
x12 = rec2[0]
y12 = rec2[1]
x22 = rec2[2]
y22 = rec2[3]
if (x22 <= x11 or y22 <= y11 or y12 >= y21 or x12 >= x21) or (x11 == x21 or y11 == y21 or x12 == x22 or y12 == y22):
return False
else:
return True | rectangle-overlap | Python3 simple solution beats 90% users | EklavyaJoshi | 0 | 169 | rectangle overlap | 836 | 0.436 | Easy | 13,586 |
https://leetcode.com/problems/rectangle-overlap/discuss/509464/Python-using-outside-the-box-calculation-and-derivation | class Solution:
def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool:
# Convert to readable
rec1_x1, rec1_x2, rec2_x1, rec2_x2 = rec1[0], rec1[2], rec2[0], rec2[2]
rec1_y1, rec1_y2, rec2_y1, rec2_y2 = rec1[1], rec1[3], rec2[1], rec2[3]
# Think outside the box if both rec2 coordinates are outside left and right then no overlatp
if rec2_x1 <= rec1_x1 and rec2_x2 <= rec1_x1 or rec2_x1 >= rec1_x2 and rec2_x2 >= rec1_x2:
return False
if rec2_y1 <= rec1_y1 and rec2_y2 <= rec1_y1 or rec2_y1 >= rec1_y2 and rec2_y2 >= rec1_y2:
return False
return True | rectangle-overlap | Python using outside the box calculation and derivation | dentedghost | 0 | 114 | rectangle overlap | 836 | 0.436 | Easy | 13,587 |
https://leetcode.com/problems/rectangle-overlap/discuss/1352617/Easy-Python-Solution(95.95) | class Solution(object):
def isRectangleOverlap(self, rec1, rec2):
if (rec1[0] == rec1[2] or rec1[1] == rec1[3] or rec2[0] == rec2[2] or rec2[1] == rec2[3]):
return False
return not (rec1[2] <= rec2[0] or rec1[3] <= rec2[1] or rec1[0] >= rec2[2] or rec1[1] >= rec2[3]) | rectangle-overlap | Easy Python Solution(95.95%) | Sneh17029 | -2 | 186 | rectangle overlap | 836 | 0.436 | Easy | 13,588 |
https://leetcode.com/problems/new-21-game/discuss/938221/Python3-top-down-and-bottom-up-dp | class Solution:
def new21Game(self, N: int, K: int, W: int) -> float:
@lru_cache(None)
def fn(n):
"""Return prob of of points between K and N given current point n."""
if N < n: return 0
if K <= n: return 1
if n+1 < K: return (1+W)/W*fn(n+1) - 1/W*fn(n+W+1)
return 1/W*sum(fn(n+i) for i in range(1, W+1))
return fn(0) | new-21-game | [Python3] top-down & bottom-up dp | ye15 | 4 | 558 | new 21 game | 837 | 0.361 | Medium | 13,589 |
https://leetcode.com/problems/new-21-game/discuss/938221/Python3-top-down-and-bottom-up-dp | class Solution:
def new21Game(self, N: int, K: int, W: int) -> float:
ans = [0]*K + [1]*(N-K+1) + [0]*W
val = sum(ans[K:K+W])
for i in reversed(range(K)):
ans[i] = val/W
val += ans[i] - ans[i+W]
return ans[0] | new-21-game | [Python3] top-down & bottom-up dp | ye15 | 4 | 558 | new 21 game | 837 | 0.361 | Medium | 13,590 |
https://leetcode.com/problems/new-21-game/discuss/1934338/Python-12-line-codeororrolling-sum | class Solution:
def new21Game(self, n: int, k: int, maxPts: int) -> float:
if n >= k - 1 + maxPts: return 1 #the last possible stop-point is k-1, if we roll a maxPts and it will end within n, that means anyway it will end within n with prob 1, there is no need to continue
dp = [0] * (n + 1) #dp[i] is the probability we reach point i. As we care what's the probability within n, at most we need dp to calculate from 1 to n
dp[0], curSum = 1, 0 #dp[0] is the probability we reach 0. As we start with 0, we have a probability of 1 reaching 0
for i in range(1, n + 1):
if i - 1 < k: # when the previous point hasn't reached k, that means we can still continue to roll, and we'll add that point. Otherwise, when i - 1 already reaches k, then the game stops and we cannot reach status i from i - 1 (we cannot pick any more number)
curSum += dp[i - 1]
if i - 1 >= maxPts: # we can only reach point i from point i - 1, i - 2, ..., i - maxPts. and hence when we calculate point i, we need to make sure the previous points outside of the range drops out
curSum -= dp[i - 1 - maxPts]
dp[i] = curSum / maxPts
return sum(dp[k:]) # we calculate all the probabilities that we land in point k, point k + 1, until point n | new-21-game | Python 12-line code||rolling sum | gulugulugulugulu | 2 | 179 | new 21 game | 837 | 0.361 | Medium | 13,591 |
https://leetcode.com/problems/new-21-game/discuss/2540398/Clean-and-Simple-Python3-or-O(k)-Time-O(maxPts)-Space | class Solution:
def new21Game(self, n: int, k: int, maxPts: int) -> float:
prob = deque([1 if k <= pts <= n else 0 for pts in range(k, k + maxPts)])
cur_sum = sum(prob)
for pts in range(k - 1, -1, -1):
prob.appendleft(cur_sum / maxPts)
cur_sum += prob[0] - prob.pop()
return prob[0] | new-21-game | Clean & Simple Python3 | O(k) Time, O(maxPts) Space | ryangrayson | 0 | 31 | new 21 game | 837 | 0.361 | Medium | 13,592 |
https://leetcode.com/problems/new-21-game/discuss/2202700/python-3-or-dp-or-O(k-%2B-m)O(m) | class Solution:
def new21Game(self, n: int, k: int, maxPts: int) -> float:
dp = collections.deque([float(i <= n) for i in range(k, k + maxPts)])
s = sum(dp)
for i in range(k):
dp.appendleft(s / maxPts)
s += dp[0] - dp.pop()
return dp[0] | new-21-game | python 3 | dp | O(k + m)/O(m) | dereky4 | 0 | 94 | new 21 game | 837 | 0.361 | Medium | 13,593 |
https://leetcode.com/problems/push-dominoes/discuss/2629832/Easy-Python-O(n)-solution | class Solution:
def pushDominoes(self, dominoes: str) -> str:
dominoes = 'L' + dominoes + 'R'
res = []
left = 0
for right in range(1, len(dominoes)):
if dominoes[right] == '.':
continue
middle = right - left - 1
if left:
res.append(dominoes[left])
if dominoes[left] == dominoes[right]:
res.append(dominoes[left] * middle)
elif dominoes[left] == 'L' and dominoes[right] == 'R':
res.append('.' * middle)
else:
res.append('R' * (middle // 2) + '.' * (middle % 2) + 'L' * (middle // 2))
left = right
return ''.join(res) | push-dominoes | Easy Python O(n) solution | namanxk | 3 | 225 | push dominoes | 838 | 0.57 | Medium | 13,594 |
https://leetcode.com/problems/push-dominoes/discuss/2629294/Python3-Multi-source-BFS | class Solution:
def pushDominoes(self, dominoes: str) -> str:
ans = ['.' for _ in range(len(dominoes))]
queue = deque()
for i, d in enumerate(dominoes):
if d == 'L' or d == 'R':
queue.append((i, d))
ans[i] = d
while queue:
size = len(queue)
collision = defaultdict(list)
for _ in range(size):
i, d = queue.popleft()
if d == 'L' and i - 1 >= 0 and ans[i - 1] == '.':
collision[i - 1].append('L')
elif d == 'R' and i + 1 < len(ans) and ans[i + 1] == '.':
collision[i + 1].append('R')
for pos in collision:
if len(collision[pos]) == 2:
ans[pos] = '.'
else:
ans[pos] = collision[pos][0]
queue.append((pos, collision[pos][0]))
return ''.join(ans) | push-dominoes | [Python3] Multi-source BFS | qinzhe | 2 | 54 | push dominoes | 838 | 0.57 | Medium | 13,595 |
https://leetcode.com/problems/push-dominoes/discuss/1905096/WEEB-EXPLAINS-PYTHONC%2B%2B-2-POINTERS-SOLUTION | class Solution:
def pushDominoes(self, string: str) -> str:
low, high = 0, len(string) - 1
string = list(string)
if string[low] == ".":
for i in range(len(string)):
if string[i] == "R":
low = i
break
if string[i] == "L":
for j in range(i):
string[j] = "L"
break
if string[high] == ".":
for i in range(len(string)-1,-1,-1):
if string[i] == "L":
high = i
break
if string[i] == "R":
for j in range(i, len(string)):
string[j] = "R"
break
i = low
for j in range(low+1, high+1):
if string[i] == "R" and string[j] == "L":
mid = (i+j) //2
temp = j
while i != j:
if i >= temp:
i = j
break
string[i] = "R"
string[temp] = "L"
temp-=1
i+=1
if string[i] == "R" and string[j] == "R":
while i != j:
string[i] = "R"
i+=1
if string[i] == "L" and string[j] == "L":
while i != j:
string[i] = "L"
i+=1
if string[i] == "L" and string[j] == "R":
i = j
return "".join(string) | push-dominoes | WEEB EXPLAINS PYTHON/C++ 2 POINTERS SOLUTION | Skywalker5423 | 2 | 210 | push dominoes | 838 | 0.57 | Medium | 13,596 |
https://leetcode.com/problems/push-dominoes/discuss/2631314/Simple-python-solution | class Solution:
def pushDominoes(self, dominoes: str) -> str:
n = len(dominoes)
right_force = [0] * n
for i in range(n):
if dominoes[i] == 'R':
right_force[i] = n
elif dominoes[i] == 'L':
right_force[i] = 0
else:
if(i-1 >= 0):
right_force[i] = max(right_force[i-1]-1, 0)
left_force = [0] * n
for i in range(n-1, -1, -1):
if dominoes[i] == 'L':
left_force[i] = n
elif dominoes[i] == 'R':
left_force[i] = 0
else:
if(i+1 < n):
left_force[i] = max(left_force[i+1]-1, 0)
return ''.join('.' if right_force[i] == left_force[i] else 'R' if right_force[i] > left_force[i] else 'L' for i in range(n)) | push-dominoes | Simple python solution | vanshika_2507 | 1 | 44 | push dominoes | 838 | 0.57 | Medium | 13,597 |
https://leetcode.com/problems/push-dominoes/discuss/2629708/SIMPLE-PYTHON3-SOLUTION-99-faster-using-stringReplacement-explained | class Solution: # States for the dominoes:
# • Any triplet that reaches the state 'R.L' remains
# that state permanently.
#
# • These changes occur to pairs that are not part of an 'R.L':
# 'R.' --> 'RR', .L' --> 'LL'
# Here's the plan:
# 1) To avoid the problem with the 'R.L' state when we address the
# 'R.' --> 'RR' and '.L' --> 'LL' changes, we replace each 'R.L'
#. with a dummy string (say, 'xxx').
#
# 2) We perform the 'R.' --> 'RR', .L' --> 'LL' replacements.
# 3) Once the actions described in 1) and 2) are completed, we repeat
# until no changes occur. We replace the dummy string with 'R.L'.
def pushDominoes(self, dominoes: str) -> str:
temp = ''
while dominoes != temp:
temp = dominoes
dominoes = dominoes.replace('R.L', 'xxx') # <-- 1)
dominoes = dominoes.replace('R.', 'RR') # <-- 2)
dominoes = dominoes.replace('.L', 'LL') # <-- 2)
return dominoes.replace('xxx', 'R.L') # <-- 3) | push-dominoes | ✅✔ SIMPLE PYTHON3 SOLUTION ✅✔ 99% faster using stringReplacement explained | rajukommula | 1 | 44 | push dominoes | 838 | 0.57 | Medium | 13,598 |
https://leetcode.com/problems/push-dominoes/discuss/2629446/2-Way-traversal-solution-in-TC%3A-O(n) | class Solution:
def pushDominoes(self, dominoes: str) -> str:
n=len(dominoes)
dominoes=list(dominoes)
flag=0
for i in range(n-1,-1,-1):
if dominoes[i]=="L":
ct=1
flag=1
elif dominoes[i]=="." and flag==1:
dominoes[i]=ct
ct+=1
elif dominoes[i]=="R":
flag=0
else:
dominoes[i]=0
flagr=0
for i in range(n):
if dominoes[i]=="R":
ctr=1
flagr=1
elif str(dominoes[i]).isdigit() and flagr==1 and abs(ctr)<abs(dominoes[i]) or dominoes[i]==".":
dominoes[i]="R"
ctr+=1
elif str(dominoes[i]).isdigit() and flagr==1 and abs(ctr)==abs(dominoes[i]):
dominoes[i]="."
elif flagr==1 and dominoes[i]==0:
dominoes[i]="R"
elif dominoes[i]=="L":
flagr=0
elif dominoes[i]==0:
dominoes[i]="."
else:
dominoes[i]="L"
return "".join(dominoes) | push-dominoes | 2 Way traversal solution in TC: O(n) | shubham_1307 | 1 | 85 | push dominoes | 838 | 0.57 | Medium | 13,599 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.