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/push-dominoes/discuss/2629342/Python-Solution-or-O(n)-or-Comments
class Solution: def pushDominoes(self, dominoes: str) -> str: n=len(dominoes) left=[0]*n right=[0]*n # traverse from left side # keep count of 'R' occurennces count=0 for i in range(n): if dominoes[i]=='L' or dominoes[i]=='R': count=0 left[i]=count if dominoes[i]=='R' or count!=0: count+=1 # traverse from right side # keep count of 'L' occurennces count=0 for i in range(n-1, -1, -1): if dominoes[i]=='R' or dominoes[i]=='L': count=0 right[i]=count if dominoes[i]=='L' or count!=0: count+=1 # print(left) # print(right) # formulate ans based on occurence count of 'L' and 'R' ans='' for i in range(n): if left[i]==right[i]: ans+=dominoes[i] else: if left[i]==0 and right[i]!=0: ans+='L' elif right[i]==0 and left[i]!=0: ans+='R' elif left[i]>right[i]: ans+='L' else: ans+='R' return ans
push-dominoes
Python Solution | O(n) | Comments
Siddharth_singh
1
38
push dominoes
838
0.57
Medium
13,600
https://leetcode.com/problems/push-dominoes/discuss/2394442/Python-or-BFS
class Solution: def pushDominoes(self, dom: str) -> str: from collections import deque n = len(dom) d = set() q = deque() arr = [0 for i in range(n)] for i in range(n): if dom[i] == "L": arr[i] = -1 d.add(i) q.append((i,"L")) if dom[i] == "R": arr[i] = 1 d.add(i) q.append((i,"R")) while q: t1 = set() for _ in range(len(q)): t = q.popleft() if t[1] == "L": if t[0]-1 >= 0 and t[0]-1 not in d: t1.add(t[0]-1) arr[t[0]-1] -= 1 else: if t[0]+1 < n and t[0]+1 not in d: t1.add(t[0]+1) arr[t[0]+1] += 1 for val in t1: d.add(val) if arr[val] > 0: q.append((val,"R")) elif arr[val]<0: q.append((val,"L")) ans = "" for val in arr: if val<0: ans += "L" elif val>0: ans += "R" else: ans += "." return ans
push-dominoes
Python | BFS
Shivamk09
1
114
push dominoes
838
0.57
Medium
13,601
https://leetcode.com/problems/push-dominoes/discuss/1262345/precomputation-oror-easy-understanding-oror-python
class Solution: def pushDominoes(self, d: str) -> str: n= len(d) right =[9999999999999]*n left = [9999999999999]*n ne=-1 for i in range(n): if d[i]=='R': ne=i if d[i]=='L': ne=-1 if ne!=-1 and d[i]=='.': right[i] = i-ne re=-1 for i in range(n-1,-1,-1): if d[i]=='L': re=i if d[i]=='R': re=-1 if re!=-1 and d[i]=='.': left[i] = re-i u='' for i in range(n): if right[i]!=left[i]: if right[i]<left[i]: u+='R' else: u+='L' else: u+=d[i] return u
push-dominoes
precomputation || easy understanding || python
chikushen99
1
192
push dominoes
838
0.57
Medium
13,602
https://leetcode.com/problems/push-dominoes/discuss/2748858/Python3-Commented-One-Pass-Solution
class Solution: def pushDominoes(self, dominoes: str) -> str: # go through the dominos and update # once we hit a second domino # the amount of doinos between # two pushed once is # idx - prev[] - 1 # # the one missing there is the # current pushed domino # initialize the first previous position # in a way it does not affect the # "real" upcoming dominos prev = ['L', -1] res = [] for idx, char in enumerate(dominoes): # check whether we hit a domino if char == 'L': # all domios till prev fall # as they all fall in the same # direction if prev[0] == 'L': res.append('L'*(idx-prev[1])) # we have dominos coming to us # as they were pushed by an # 'R' domino else: # calculate distance between dist = idx - prev[1] - 1 # append half the distance # R dominos as the pushing # one already has been dealt # with res.append('R'*(dist//2)) # check whether falling domins # meet at a middle one res.append('.'*(dist % 2)) # append half of the distance # falling dominos to the left # plus the pushing one res.append('L'*(dist//2+1)) # update the prev prev = ['L', idx] elif char == 'R': # our there are no dominos falling # towards us if prev[0] == 'L': # append the standing dominos # till this position res.append('.'*(idx-prev[1]-1)) # append our pushed domino res.append('R') else: # append all falling dominos # from before us plus our own # domino res.append('R'*(idx-prev[1])) # update the prev prev = ['R', idx] # take care of the between the last pushed # domino and the last domino if prev[0] == 'R': # they are falling towards the end res.append('R'*(len(dominoes)-prev[1]-1)) else: # they are still standing res.append('.'*(len(dominoes)-prev[1]-1)) return "".join(res)
push-dominoes
[Python3] - Commented, One-Pass Solution
Lucew
0
3
push dominoes
838
0.57
Medium
13,603
https://leetcode.com/problems/push-dominoes/discuss/2640150/Runtime%3A-549-ms-faster-than-57.25-Memory-Usage%3A-16.9-MB-less-than-53.33
class Solution: def pushDominoes(self, dominoes: str) -> str: condensed = [] index = 0 currDir = dominoes[0] while index < len(dominoes) and dominoes[index] == currDir: index += 1 count = index if index == len(dominoes): return dominoes elif currDir == '.' and dominoes[index] == 'L': currDir = dominoes[index] while index < len(dominoes) and dominoes[index] == currDir: index += 1 condensed.append(currDir * index) count = 1 if index == len(dominoes): return ''.join(condensed) currDir = dominoes[index] index += 1 while index < len(dominoes): if dominoes[index] == currDir: count += 1 else: if currDir == '.': condensed.append([currDir, count]) elif type(condensed[-1]) is not list: condensed.append(currDir * count) else: dotCount = condensed.pop()[1] prevDir = condensed[-1][0] if prevDir == currDir: condensed.append(condensed.pop() + currDir * (dotCount + count)) elif prevDir == 'L': condensed.append('.' * dotCount) condensed.append(currDir * count) else: halfCount = dotCount // 2 hasExtraDot = halfCount*2 != dotCount condensed.append(prevDir * halfCount) if hasExtraDot: condensed.append('.') condensed.append(currDir * (halfCount + count)) currDir = dominoes[index] count = 1 index += 1 if condensed: if currDir == '.': dotCount = count prevDir = condensed[-1][0] if prevDir == 'L': condensed.append(currDir * dotCount) else: condensed.append(prevDir * dotCount) elif type(condensed[-1]) is list: dotCount = condensed.pop()[1] if not condensed: if currDir == 'L': condensed.append(currDir * (dotCount + count)) else: condensed.append('.' * dotCount) condensed.append(currDir * count) else: prevDir = condensed[-1][0] if prevDir == currDir: condensed.append(condensed.pop() + currDir * (dotCount + count)) elif prevDir == 'L': condensed.append('.' * dotCount) condensed.append(currDir * count) else: halfCount = dotCount // 2 hasExtraDot = halfCount*2 != dotCount condensed.append(prevDir * halfCount) if hasExtraDot: condensed.append('.') condensed.append(currDir * (halfCount + count)) else: condensed.append(currDir * count) else: condensed.append(currDir * count) return ''.join(condensed)
push-dominoes
Runtime: 549 ms, faster than 57.25%; Memory Usage: 16.9 MB, less than 53.33%
GizDave
0
3
push dominoes
838
0.57
Medium
13,604
https://leetcode.com/problems/push-dominoes/discuss/2632025/Python-two-for-loops.-Time%3A-O(N)-Space%3A-O(N)
class Solution: def pushDominoes(self, dominoes: str) -> str: result = [0] * len(dominoes) left_idx = -math.inf for idx, d in enumerate(dominoes): if d == 'R': left_idx = idx elif d == 'L': left_idx = -math.inf result[idx] = idx - left_idx right_idx = math.inf for idx in range(len(dominoes)-1, -1, -1): if dominoes[idx] == 'L': right_idx = idx elif dominoes[idx] == 'R': right_idx = math.inf if right_idx - idx == result[idx]: result[idx] = '.' elif right_idx - idx > result[idx]: result[idx] = 'R' else: result[idx] = 'L' return "".join(result)
push-dominoes
Python, two for-loops. Time: O(N), Space: O(N)
blue_sky5
0
9
push dominoes
838
0.57
Medium
13,605
https://leetcode.com/problems/push-dominoes/discuss/2631471/BFS-Solution-or-Python3
class Solution: # O(n) time, # O(n) space, # Approach: BFS, deque, hashtable def pushDominoes(self, dominoes: str) -> str: n = len(dominoes) dominos = list(dominoes) qu = deque() for index, domino in enumerate(dominos): if domino == '.': continue if domino == 'L': if index > 0 and dominos[index-1] == '.': qu.append(index) if domino == 'R': if index < n-1 and dominos[index+1] == '.': qu.append(index) while qu: m = len(qu) changed = set() for i in range(m): index = qu.popleft() domino = dominos[index] if domino == 'R': if index + 2 < n: if dominos[index+2] == 'R' or dominos[index+2] == '.' or (index+2) in changed: dominos[index + 1] = 'R' changed.add(index+1) if dominos[index+2] == '.': qu.append(index+1) else: dominos[index + 1] = 'R' if domino == 'L': if index - 2 > -1: if dominos[index-2] == 'L' or dominos[index-2] == '.' or (index-2) in changed: dominos[index - 1] = 'L' changed.add(index-1) if dominos[index-2] == '.': qu.append(index-1) else: dominos[index - 1] = 'L' return ''.join(dominos)
push-dominoes
BFS Solution | Python3
destifo
0
12
push dominoes
838
0.57
Medium
13,606
https://leetcode.com/problems/push-dominoes/discuss/2631321/Faster-76-Memory-99.-Two-pointers-with-explanation!-O(n)
class Solution: def pushDominoes(self, dominoes: str) -> str: # Adding L and R letters, because we don't want to our logic be ruined by start of dot or etc. # L at the beginning won't damage the result, since it is at the start and there is nothing before that. # Same applies for the R dominoes = "L" + dominoes + "R" answer = '' i = 0 while i < len(dominoes): if dominoes[i] != ".": answer += dominoes[i] else: # if dominoes[i] is dot # we will keep track of last letter we had before this dot prev = dominoes[i - 1] # And second pointer comes into play case_index = i + 1 # Moving pointer until we face the letter while dominoes[case_index] == ".": case_index += 1 # difference inidcates how many dots were there difference = case_index - i # if L....L -> LLLLLL, same applies for R # Note that we adding only letters with difference times # because we already added previous letter at the beginning (at the first while loop) # and eventually will add the last letter, when we change the i to the current index if (prev == "L" and dominoes[case_index] == "L") or (prev == "R" and dominoes[case_index] == "R"): answer += prev * difference elif prev == "R" and dominoes[case_index] == "L": # In case of R...L -> RR.LL, that's why I'm saying that I should add (difference // 2) # in this specific case we have 3 dots # thereby we should add one R and one left and also insert . between them, because difference is odd # In case of diference is even R....L -> RRRLLL, we will add two R's and L's answer += prev * (difference // 2) answer += "." if difference % 2 != 0 else "" answer += dominoes[case_index] * (difference // 2) else: # We left with only one sitatuion which is L.....R, which has no sence in terms of dots # those two dominoes(leftest and rightest) literally won't touch them. answer += "." * difference # adding case_index - 1, since we will eventually increase the i by one, # which will make our i equal to case_index, and then add the rightest element, # that we didn't add at the start of our second pointer logic i = case_index - 1 # EVENTUALLY INCREASING i by one as was told before :D i += 1 # Answer has L and R, that we added at the beginning of our program, we need to eradicate them return answer[1:-1]
push-dominoes
Faster 76%, Memory 99%. Two pointers with explanation! O(n)
milsolve
0
14
push dominoes
838
0.57
Medium
13,607
https://leetcode.com/problems/push-dominoes/discuss/2631030/Python-3-a-different-approach-using-two-pointers
class Solution: def pushDominoes(self, d: str) -> str: n = len(d) ans = [0]*n flg = False cnt = 0 for i in range(n): if(d[i] == 'L'): flg = False continue if(d[i] == 'R'): flg = True cnt = 1 continue if(flg): ans[i] = cnt cnt += 1 #print(ans) flg = False cnt = 0 for i in range(n-1,-1, -1): if(d[i] == 'R'): flg = False continue if(d[i] == 'L'): flg = True cnt = -1 continue if(flg): if(ans[i] == 0): ans[i] = cnt cnt -=1 continue if(ans[i]+cnt == 0): ans[i] = 0 flg = False cnt = 0 continue elif(ans[i] < abs(cnt)): flg = False cnt = -1 continue elif(ans[i]): ans[i] = cnt cnt -= 1 #print(ans) d = list(d) for i in range(n): if(d[i] == '.'): if(ans[i] < 0): d[i] = 'L' elif(ans[i]>0): d[i] = 'R' return("".join(d))
push-dominoes
Python 3 a different approach using two pointers
user2800NJ
0
8
push dominoes
838
0.57
Medium
13,608
https://leetcode.com/problems/push-dominoes/discuss/2630874/Python-3-Clear-O(N)-with-Explanation
class Solution: def pushDominoes(self, dominoes: str) -> str: n = len(dominoes) r_dist = [0 if d == 'R' else float('inf') for d in dominoes] l_dist = [0 if d == 'L' else float('inf') for d in dominoes] ri = float('inf') for i, d in enumerate(dominoes): if d == 'R': ri = i elif d == '.' and ri != float('inf'): r_dist[i] = i - ri elif d == 'L': ri = float('inf') li = float('inf') for i, d in reversed(list(enumerate(dominoes))): if d == 'L': li = i elif d == '.' and li != float('inf'): l_dist[i] = li - i elif d == 'R': li = float('inf') res = '' for i, d in enumerate(dominoes): if d == '.' and r_dist[i] != l_dist[i]: res += 'R' if r_dist[i] < l_dist[i] else 'L' else: res += d return res
push-dominoes
Python 3, Clear O(N) with Explanation
Brent_Pappas
0
10
push dominoes
838
0.57
Medium
13,609
https://leetcode.com/problems/push-dominoes/discuss/2630433/GolangPython-O(N)-time-or-O(N)-space
class Solution: def pushDominoes(self, dominoes: str) -> str: dominoes = list(dominoes) prev_letter = None prev_idx = -1 for i in range(len(dominoes)): item = dominoes[i] if item == "L" and prev_letter != "R": for j in range(i-1,prev_idx,-1): dominoes[j] = "L" prev_letter = "L" prev_idx = i elif item == "L": right = i-1 left = prev_idx+1 while left < right: dominoes[left] = "R" dominoes[right] = "L" left+=1 right-=1 prev_letter = "L" prev_idx = i elif item == "R" and prev_letter != "R": prev_letter = "R" prev_idx = i elif item == "R": for j in range(i-1,prev_idx,-1): dominoes[j] = "R" prev_letter = "R" prev_idx = i if prev_letter == "R": for j in range(len(dominoes)-1,prev_idx,-1): dominoes[j] = "R" return "".join(dominoes)
push-dominoes
Golang/Python O(N) time | O(N) space
vtalantsev
0
9
push dominoes
838
0.57
Medium
13,610
https://leetcode.com/problems/push-dominoes/discuss/2630289/Python-Solution-using-deque
class Solution: def pushDominoes(self, dominoes: str) -> str: dom = list(dominoes) q = collections.deque() for i,d in enumerate(dom): if d!=".": q.append((i,d)) while q: i,d = q.popleft() if d == "L": if i>0 and dom[i-1] == ".": dom[i-1] = "L" q.append((i-1,"L")) elif d =="R": if i+1 < len(dom) and dom[i+1] == ".": if i+2 < len(dom) and dom[i+2] == "L": q.popleft() else: q.append((i+1,"R")) dom[i+1] = "R" return "".join(dom)
push-dominoes
Python Solution using deque
Namangarg98
0
10
push dominoes
838
0.57
Medium
13,611
https://leetcode.com/problems/push-dominoes/discuss/2630273/Python3-or-Replace-or-Fast-and-Simple
class Solution: def pushDominoes(self, dominoes: str) -> str: temp = '' while dominoes != temp: temp = dominoes dominoes = dominoes.replace('R.L', 'ooo') dominoes = dominoes.replace('R.', 'RR') dominoes = dominoes.replace('.L', 'LL') return dominoes.replace('ooo', 'R.L')
push-dominoes
Python3 | Replace | Fast & Simple
joshua_mur
0
5
push dominoes
838
0.57
Medium
13,612
https://leetcode.com/problems/push-dominoes/discuss/2629759/Easy-to-understand-or-No-DP-or-Brute-force-or-O(N)-solution
class Solution: def pushDominoes(self, dominoes: str) -> str: dominoesList,totalDominoes=list(dominoes), len(dominoes); i = 0; while i<totalDominoes: if dominoesList[i] == 'L': #if L comes very fast then from L index to previous one becomes L. ie, ........L case j = i-1; while j>=0 and dominoesList[j]=='.': dominoesList[j] = 'L'; j-=1; elif dominoesList[i] == 'R': # if R comes then rStart = i; while rStart<totalDominoes and dominoesList[rStart]=='R': # handling consecutive R's RRRR...., we need to find the very right index of R rStart+=1; rStart-=1; rEnd = rStart; while rEnd<totalDominoes and dominoesList[rEnd]!='L': # looking for L if dominoesList[rEnd] == 'R': # if R comes before L then all the previous . will be replaced by R, ie R....R...L, this case for j in range(rStart, rEnd): dominoesList[j] = 'R'; rStart = rEnd; rEnd+=1; i=rEnd; if rEnd == totalDominoes: # if end becomes the end of string then all the . will be replaced by 'R', ie R......... for j in range(rStart, rEnd): dominoesList[j]='R'; else: while rStart<rEnd: # modifying . according to the position of L and R, ie R.....L calse dominoesList[rStart]='R'; dominoesList[rEnd]='L'; rStart+=1; rEnd-=1; i+=1; return "".join(dominoesList);
push-dominoes
Easy to understand | No DP | Brute force | O(N) solution
AshikeRN
0
17
push dominoes
838
0.57
Medium
13,613
https://leetcode.com/problems/push-dominoes/discuss/2629723/Simple-dp-approachor-line-by-line-self-explanation
class Solution: def pushDominoes(self, dominoes: str) -> str: n=len(dominoes) dp_R=[None for x in range(0,n)] ## one for right falling dp_L=[None for x in range(0,n)] ##other one for left falling for i in range(0,n): if dominoes[i]=="." and (i-1>=0 and (dominoes[i-1]=="R" or dp_R[i-1]=="R")): dp_R[i]="R" else: dp_R[i]=dominoes[i] for i in range(n-1,-1,-1): if dominoes[i]=="." and (i+1<n and (dominoes[i+1]=="L" or dp_L[i+1]=="L")): dp_L[i]="L" else: dp_L[i]=dominoes[i] ans=[None for x in range(0,n)] for i in range(0,n): if dp_R[i]=="R" and dp_L[i]=="L": right=i-1 ## for checking which one is nearer if "R"is nearer than "R" else "L" and if both are at same distance than ".". left=i+1 while right>-1 and dominoes[right]!="R": right-=1 while left<n and dominoes[left]!="L": left+=1 if right==-1 and left<n: ans[i]="L" elif left==n and right>=0: ans[i]="R" elif right!=-1 and left!=n and i-right<left-i: ans[i]="R" elif right!=-1 and left!=n and i-right>left-i: ans[i]="L" else: ans[i]="." elif dp_R[i]==".": ans[i]=dp_L[i] else: ans[i]=dp_R[i] ans="".join(x for x in ans) return ans
push-dominoes
Simple dp approach| line by line self explanation
Mom94
0
12
push dominoes
838
0.57
Medium
13,614
https://leetcode.com/problems/push-dominoes/discuss/2629419/Python-or-Only-if-else-and-loops-or-easy-solution
class Solution: def pushDominoes(self, dom: str) -> str: str1 = "." i=0 count=0 while i<len(dom): if dom[i]=='.': count +=1 elif dom[i]=='L': if str1[-1]=='R': if count%2 == 0: for j in range(count//2): str1 += 'R' for j in range(count//2): str1 += 'L' else: for j in range(count//2): str1 += 'R' str1 += '.' for j in range(count//2): str1 += 'L' else: for j in range(count): str1 += 'L' str1 += 'L' count = 0 elif dom[i]=='R': if str1[-1]=='L': for j in range(count): str1 += '.' elif str1[-1]=='R': for j in range(count): str1 += 'R' else: for j in range(count): str1 += '.' count=0 str1 += 'R' i += 1 if count and str1[-1]=='R': for i in range(count): str1 += 'R' else: for i in range(count): str1 += '.' str1 = str1[1:] return str1 ```
push-dominoes
Python | Only if-else and loops | easy solution
Yash_A
0
18
push dominoes
838
0.57
Medium
13,615
https://leetcode.com/problems/push-dominoes/discuss/2629289/Python3-Rotten-Oranges-type-approach-Queue
class Solution: def pushDominoes(self, dominoes: str) -> str: q = collections.deque() timeArray = [-1]*len(dominoes) dominosArr = list(dominoes) n = len(dominoes) for i, val in enumerate(dominosArr): if val!='.': q.append(i) timeArray[i] = 0 while(len(q)): currDomino = q.popleft() currVal = dominosArr[currDomino] currTimeStamp = timeArray[currDomino] if (currVal == 'L') and (currDomino>0): if(dominosArr[currDomino-1] == 'R') and (timeArray[currDomino-1] == timeArray[currDomino]+1): dominosArr[currDomino-1] = '.' elif timeArray[currDomino-1] == -1: dominosArr[currDomino-1] = 'L' q.append(currDomino-1) timeArray[currDomino-1] = currTimeStamp+1 if (currVal == 'R') and (currDomino<n-1): if(dominosArr[currDomino+1] == 'L') and (timeArray[currDomino+1] == timeArray[currDomino]+1): dominosArr[currDomino+1] = '.' elif timeArray[currDomino+1] == -1: dominosArr[currDomino+1] = 'R' q.append(currDomino+1) timeArray[currDomino+1] = currTimeStamp+1 return ''.join(dominosArr)
push-dominoes
Python3 - Rotten Oranges type approach - Queue
invisiblecoder
0
13
push dominoes
838
0.57
Medium
13,616
https://leetcode.com/problems/push-dominoes/discuss/2629281/Python-Easy-to-understand-O(N)-solution
class Solution: def pushDominoes(self, dominoes: str) -> str: n = len(dominoes) output = list(dominoes) distances = [[float('inf'),float('inf')] for _ in range(n)] # determine each domino's distance to nearest R domino prev = float('inf') for i,d in enumerate(dominoes): if d == 'R': prev = i elif d == 'L': prev = float('inf') if prev < float('inf'): distances[i][0] = i-prev # determine each domino's distance to nearest L domino prev = float('inf') for i,d in enumerate(reversed(dominoes)): curr = n-1-i if d == 'L': prev = curr elif d == 'R': prev = float('inf') if prev < float('inf'): distances[curr][1] = prev-curr # update domino state after comparing distance to nearest L and nearest R domino for i,d in enumerate(dominoes): if d != '.': continue elif distances[i][1] < float('inf') and distances[i][0] > distances[i][1]: output[i] = 'L' elif distances[i][0] < float('inf') and distances[i][0] < distances[i][1]: output[i] = 'R' return ''.join(output)
push-dominoes
[Python] Easy to understand O(N) solution
fomiee
0
13
push dominoes
838
0.57
Medium
13,617
https://leetcode.com/problems/push-dominoes/discuss/2629253/If-else-ladder-with-monotonic-queue-in-Python-Solution
class Solution: # Classic If Else Ladder + Monotonic Stack def pushDominoes(self, dominoes: str) -> str: d = [i for i in dominoes] n = len(dominoes) mono = [] res = '' for i in range(n): # Handle R...L if mono and mono[0] == 'R' and d[i] == 'L': k = len(mono) + 1 c = k // 2 if k &amp; 1: res += 'R' * c + '.' + 'L' * c else: res += 'R' * c + 'L' * c mono.clear() # Handle ..L..L or ....L etc elif mono and d[i] == 'L': c = (len(mono) + 1) res += 'L' * c mono.clear() # Handle ..R...R or ...R elif mono and d[i] == 'R': nn = len(mono) if 'R' in mono: k = mono.index('R') res += '.' * k + 'R' * (nn - k) else: res += ''.join(mono) mono.clear() mono.append('R') # Handle all other cases like L or .... or R etc else: if d[i] == 'L': res += 'L' else: mono.append(d[i]) # Handle mono with R cases which can only be left post above cases if mono: nn = len(mono) if 'R' in mono: k = mono.index('R') res += '.' * k + 'R' * (nn - k) else: res += ''.join(mono) return res
push-dominoes
If else ladder with monotonic queue in Python Solution
shiv-codes
0
9
push dominoes
838
0.57
Medium
13,618
https://leetcode.com/problems/push-dominoes/discuss/2629253/If-else-ladder-with-monotonic-queue-in-Python-Solution
class Solution: # Classic If Else ladder + monotonic queue def pushDominoes(self, dominoes: str) -> str: d = list(dominoes) mono, res = [], [] n = len(d) for i in range(n): if d[i] == 'L': if mono and mono[0] == 'R': print(mono) total = len(mono) + 1 k = (total) >> 1 res.append('R' * k) if total &amp; 1: res.append('.') res.append('L' * k) else: res.append('L' * (len(mono) + 1)) mono.clear() elif d[i] == 'R': if mono: res.append(mono[0] * len(mono)) mono = ['R'] else: mono.append(d[i]) if mono: if mono[0] == 'R': res.append('R' * len(mono)) else: res.append('.' * len(mono)) return ''.join(res)
push-dominoes
If else ladder with monotonic queue in Python Solution
shiv-codes
0
9
push dominoes
838
0.57
Medium
13,619
https://leetcode.com/problems/push-dominoes/discuss/2629083/Python-Accepted
class Solution: def pushDominoes(self, d: str) -> str: right = [0 for i in range(0,len(d))] left = [0 for i in range(0,len(d))] prev = None for i in range(len(d)): if d[i]=='R': right[i]=None prev = i elif d[i]=='L': prev=None right[i]=None else: right[i] = i-prev if prev!=None else None prev = None for i in range(len(d)-1,-1,-1): if d[i]=='L': left[i]=None prev = i elif d[i]=='R': left[i]=None prev = None else: left[i]= prev-i if prev!=None else None ans = '' for i in range(len(d)): if d[i]=='.': if left[i]==None and right[i]==None: ans+='.' elif left[i]==None: ans+='R' elif right[i]==None: ans+='L' else: if left[i]<right[i]:ans+='L' if left[i]==right[i]:ans+='.' if left[i]>right[i]:ans+='R' else: ans+=d[i] return ans
push-dominoes
Python Accepted ✅
Khacker
0
26
push dominoes
838
0.57
Medium
13,620
https://leetcode.com/problems/push-dominoes/discuss/2629001/python3-Iteration-sol-for-reference
class Solution: def pushDominoes(self, dominoes: str) -> str: D = len(dominoes) posr = [0 for _ in range(D)] FORCE = 10**5 r = 0 for d in range(D): if dominoes[d] == "R": r = FORCE elif dominoes[d] == "L": r = 0 else: r = (r-1) if r > 0 else 0 posr[d] = r r = 0 ans = "" for d in range(D-1, -1, -1): if dominoes[d] == "L": r = FORCE elif dominoes[d] == "R": r = 0 else: r = (r-1) if r > 0 else 0 if r == posr[d]: ans += "." elif r > posr[d]: ans += "L" else: ans += "R" return ans[::-1]
push-dominoes
[python3] Iteration sol for reference
vadhri_venkat
0
5
push dominoes
838
0.57
Medium
13,621
https://leetcode.com/problems/push-dominoes/discuss/2628738/O(n)-using-bfs-and-simulation-with-two-sets
class Solution: def pushDominoes(self, dominoes: str) -> str: info = {0: '.', -1: 'L', 1: 'R'} n = len(dominoes) status = [0] * n q = [] for i in range(n): if dominoes[i]=='L': q.append((i, -1)) elif dominoes[i]=='R': q.append((i, 1)) ans = [dominoes[i] for i in range(n)] while len(q)>0: q1 = set([]) for pi, di in q: pj = pi + di if pj>=0 and pj<=n-1 and ans[pj]=='.': status[pj] += di q1.add(pj) q = [] for pj in q1: if status[pj]!=0: ans[pj] = info[status[pj]] q.append((pj, status[pj])) ans = "".join(ans) return ans
push-dominoes
O(n) using bfs and simulation with two sets
dntai
0
21
push dominoes
838
0.57
Medium
13,622
https://leetcode.com/problems/push-dominoes/discuss/1879797/Python-easy-to-read-and-understand-or-Brute-Force
class Solution: def pushDominoes(self, dominoes: str) -> str: q = [] dom = list(dominoes) n = len(dom) for i, pos in enumerate(dom): if pos == "L" or pos == "R": q.append((i, pos)) while q: i, pos = q.pop(0) if pos == "L": if i > 0 and dom[i - 1] == ".": dom[i - 1] = "L" q.append((i - 1, "L")) elif pos == "R": if i + 1 < n and dom[i + 1] == ".": if i + 2 < n and dom[i + 2] == "L": q.pop(0) else: dom[i + 1] = "R" q.append((i + 1, "R")) return "".join(dom)
push-dominoes
Python easy to read and understand | Brute-Force
sanial2001
0
51
push dominoes
838
0.57
Medium
13,623
https://leetcode.com/problems/push-dominoes/discuss/1354784/3-pass-simple-greater-calculate-the-time-when-each-domino-is-hit-by-each-force
class Solution: def pushDominoes(self, doms: str) -> str: n = len(doms) doms = list(doms) R, L = [0]*n, [0]*n # at which second R force comes and L force comes for i, d in enumerate(doms): if d == 'R': R[i] = 1 elif i and d == '.' and R[i-1]: R[i] = R[i-1] + 1 for i in range(n-1,-1,-1): d = doms[i] if d == 'L': L[i] = 1 elif i < n-1 and d == '.' and L[i+1]: L[i] = L[i+1] + 1 # print(R) # print(L) for i,d in enumerate(doms): if d == '.': if L[i] and not R[i]: doms[i] = 'L' elif R[i] and not L[i]: doms[i] = 'R' # what if both forces exist? # check which force came first! elif R[i] < L[i]: doms[i] = 'R' elif L[i] < R[i]: doms[i] = 'L' return ''.join(doms)
push-dominoes
3 pass simple -> calculate the time when each domino is hit by each force
yozaam
0
59
push dominoes
838
0.57
Medium
13,624
https://leetcode.com/problems/push-dominoes/discuss/1353938/Python3-greedy
class Solution: def pushDominoes(self, dominoes: str) -> str: mp = [0]*len(dominoes) ii = len(dominoes) for i in reversed(range(len(dominoes))): if dominoes[i] != ".": ii = i mp[i] = ii ans = [] ii = -1 for i, x in enumerate(dominoes): if dominoes[i] in "LR": ans.append(dominoes[i]) ii = i else: ll = "L" if ii == -1 else dominoes[ii] rr = "R" if mp[i] == len(dominoes) else dominoes[mp[i]] if ll == rr: ans.append(ll) elif ll == "L": ans.append(".") else: if i - ii < mp[i] - i: ans.append("R") elif i - ii > mp[i] - i: ans.append("L") else: ans.append(".") return "".join(ans)
push-dominoes
[Python3] greedy
ye15
0
48
push dominoes
838
0.57
Medium
13,625
https://leetcode.com/problems/similar-string-groups/discuss/2698654/My-Python-Union-Find-Solution
class Solution: def numSimilarGroups(self, strs: List[str]) -> int: N = len(strs) parent = [i for i in range(N)] depth = [1 for _ in range(N)] def find(idx): if idx != parent[idx]: return find(parent[idx]) return idx def union(idx1, idx2): p1 = find(idx1) p2 = find(idx2) if p1 == p2: return if depth[p1] < depth[p2]: parent[p1] = p2 elif depth[p2] < depth[p1]: parent[p2] = p1 else: parent[p2] = p1 depth[p1] += 1 def similar(w1, w2): dif_idx = -1 for idx in range(len(w1)): if w1[idx] != w2[idx]: if dif_idx < 0: dif_idx = idx else: if w1[dif_idx] != w2[idx]: return False if w2[dif_idx] != w1[idx]: return False if w1[idx+1:] != w2[idx+1:]: return False return True return True for idx in range(1, N): for pid in range(0, idx): if similar(strs[pid], strs[idx]): union(pid, idx) return len([i for i, p in enumerate(parent) if i==p])
similar-string-groups
My Python Union Find Solution
MonQiQi
1
99
similar string groups
839
0.478
Hard
13,626
https://leetcode.com/problems/similar-string-groups/discuss/1364678/Python-Connected-Components-using-BFS
class Solution: def numSimilarGroups(self, strs: List[str]) -> int: def isSimilar(x, y): if x == y: return True x = [i for i in x] y = [i for i in y] # Save the index where x[i] != y[i] idx = [] for i in range(len(x)): if x[i] != y[i]: idx.append(i) if len(idx) == 2: x[idx[0]], x[idx[1]] = x[idx[1]], x[idx[0]] if x == y: return True else: return False else: return False def addEdge(x, y, graph): graph[x].append(y) graph[y].append(x) # Create a graph and find the number of components, that's the answer graph = {i: [] for i in strs} visited = {i: False for i in strs} # Construction of graph for i in range(len(strs)): for j in range(i+1, len(strs)): # Check if two nodes are similar if isSimilar(strs[i], strs[j]): addEdge(strs[i], strs[j], graph) # Number of components to be stored in "ans" variable ans = 0 # BFS over all the words in strs for node in graph.keys(): if visited[node] == False: ans += 1 queue = [node] while queue: u = queue.pop(0) visited[u] = True for child in graph[u]: if visited[child] == False: visited[child] = True queue.append(child) return ans
similar-string-groups
[Python] Connected Components using BFS
mizan-ali
1
180
similar string groups
839
0.478
Hard
13,627
https://leetcode.com/problems/similar-string-groups/discuss/2845385/python-union-find
class Solution: def numSimilarGroups(self, strs: List[str]) -> int: def checksimilar(a, b): cnt = 0 for a_, b_ in zip(a, b): if a_ != b_: cnt += 1 return cnt <= 2 u = [i for i in range(len(strs))] def find_root(i): parent = u[i] if parent == i: return i else: root = find_root(parent) u[parent] = root return root for i in range(len(strs)): for j in range(i+1, len(strs)): a_root = find_root(i) b_root = find_root(j) if a_root != b_root: if checksimilar(strs[i], strs[j]): u[a_root] = b_root cnt = set() for i in range(len(strs)): cnt.add(find_root(i)) return len(cnt)
similar-string-groups
python union find
xsdnmg
0
2
similar string groups
839
0.478
Hard
13,628
https://leetcode.com/problems/similar-string-groups/discuss/2745972/96-fast-python-sol
class Solution: def numSimilarGroups(self, strs: List[str]) -> int: l=len(strs) self.rank=[1 for i in range(l)] group=[i for i in range(l)] p=len(strs[0]) def issimilar(i,j): ct=0 for a,b in zip(i,j): ct+=(a!=b) if ct>2: return False return True def find(i): if group[i]==i: return i return find(group[i]) def union(i,j): a=find(i) b=find(j) if a!=b: if self.rank[a]>=self.rank[b]: group[b]=a self.rank[a]+=self.rank[b] self.rank[b]=0 else: group[a]=b self.rank[b]+=self.rank[a] self.rank[a]=0 for i in range(l): for j in range(i+1,l): y=issimilar(strs[i],strs[j]) if y: union(i,j) count=0 for i in self.rank: if i>0: count+=1 return count
similar-string-groups
96% fast python sol
RjRahul003
0
5
similar string groups
839
0.478
Hard
13,629
https://leetcode.com/problems/similar-string-groups/discuss/2081702/Python-Graph-%2B-BFS
class Solution: def numSimilarGroups(self, strs: List[str]) -> int: def similar(word1, word2): diff = [] for a,b in zip(word1, word2): if a != b: diff.append((a,b)) if diff and len(diff) > 2: return False if diff and sorted(diff[0]) != sorted(diff[1]): return False return True graph = {} for i in range(len(strs)): graph[strs[i]] = [] for j in range(len(strs)): if i != j and similar(strs[i], strs[j]): graph[strs[i]].append(strs[j]) # print(graph) visited = set() q = deque() group_count = 0 for i in range(len(strs)): if strs[i] not in visited: group = [] q.append(strs[i]) while q: node = q.popleft() visited.add(node) group.append(node) for sim in graph[node]: if sim not in visited: q.append(sim) # print(group, visited) group_count += 1 return group_count
similar-string-groups
Python Graph + BFS
remy1991
0
32
similar string groups
839
0.478
Hard
13,630
https://leetcode.com/problems/magic-squares-in-grid/discuss/381223/Two-Solutions-in-Python-3-(beats-~99)-(two-lines)
class Solution: def numMagicSquaresInside(self, G: List[List[int]]) -> int: M, N, S, t = len(G)-2, len(G[0])-2, {(8,1,6,3,5,7,4,9,2),(6,1,8,7,5,3,2,9,4),(2,7,6,9,5,1,4,3,8),(6,7,2,1,5,9,8,3,4)}, range(3) return sum((lambda x: x in S or x[::-1] in S)(tuple(sum([G[i+k][j:j+3] for k in t],[]))) for i,j in itertools.product(range(M),range(N)))
magic-squares-in-grid
Two Solutions in Python 3 (beats ~99%) (two lines)
junaidmansuri
1
624
magic squares in grid
840
0.385
Medium
13,631
https://leetcode.com/problems/magic-squares-in-grid/discuss/381223/Two-Solutions-in-Python-3-(beats-~99)-(two-lines)
class Solution: def numMagicSquaresInside(self, G: List[List[int]]) -> int: M, N, S, t, s = len(G), len(G[0]), set(range(1,10)), range(3), 0 for i in range(M-2): for j in range(N-2): g = [G[i+k][j:j+3] for k in t] if set(sum(g,[])) != S or g[1][1] != 5: continue if any(sum(g[k]) != 15 for k in t) or any(sum([g[k][l] for k in t]) != 15 for l in t): continue if sum([g[k][k] for k in t]) != 15 or sum([g[k][2-k] for k in t]) != 15: continue s += 1 return s - Junaid Mansuri (LeetCode ID)@hotmail.com
magic-squares-in-grid
Two Solutions in Python 3 (beats ~99%) (two lines)
junaidmansuri
1
624
magic squares in grid
840
0.385
Medium
13,632
https://leetcode.com/problems/magic-squares-in-grid/discuss/1419104/Straightforward-98-speed
class Solution: digits = {1, 2, 3, 4, 5, 6, 7, 8, 9} @classmethod def magic_3_3(cls, square: List[List[int]]) -> bool: if set(sum(square, [])) != Solution.digits: return False sum_row0 = sum(square[0]) for r in range(1, 3): if sum(square[r]) != sum_row0: return False if any(sum(col) != sum_row0 for col in zip(*square)): return False sum_main_diagonal = sum_second_diagonal = 0 for i in range(3): sum_main_diagonal += square[i][i] sum_second_diagonal += square[i][2 - i] return sum_main_diagonal == sum_second_diagonal == sum_row0 def numMagicSquaresInside(self, grid: List[List[int]]) -> int: count = 0 rows, cols = len(grid), len(grid[0]) for r in range(rows - 2): for c in range(cols - 2): if Solution.magic_3_3([grid[row_idx][c: c + 3] for row_idx in range(r, r + 3)]): count += 1 return count
magic-squares-in-grid
Straightforward, 98% speed
EvgenySH
0
317
magic squares in grid
840
0.385
Medium
13,633
https://leetcode.com/problems/magic-squares-in-grid/discuss/938258/Python3-beating-99.32
class Solution: def numMagicSquaresInside(self, grid: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) # dimension def fn(i, j): """Return True if grid[i-1:i+2][j-1:j+2] is a magic squre.""" seen = set() row, col = [0]*3, [0]*3 # row sum &amp; column sum diag = anti = 0 for ii in range(i-1, i+2): for jj in range(j-1, j+2): if not 0 <= grid[ii][jj] < 10 or grid[ii][jj] in seen: return False seen.add(grid[ii][jj]) row[ii-i+1] += grid[ii][jj] col[jj-j+1] += grid[ii][jj] if ii-jj == i-j: diag += grid[ii][jj] if ii+jj == i+j: anti += grid[ii][jj] return len(set(row)) == 1 and len(set(col)) == 1 and row[0] == col[0] == diag == anti ans = 0 for i in range(1, m-1): for j in range(1, n-1): if grid[i][j] == 5 and fn(i, j): ans += 1 return ans
magic-squares-in-grid
[Python3] beating 99.32%
ye15
-1
142
magic squares in grid
840
0.385
Medium
13,634
https://leetcode.com/problems/keys-and-rooms/discuss/1116836/Python3-Soln-greater-Keys-and-Rooms-stack-implementation
class Solution: def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: visited_rooms = set() stack = [0] # for rooms that we need to visit and we start from room [0] while stack: room = stack.pop() visited_rooms.add(room) for key in rooms[room]: if key not in visited_rooms: stack.append(key) return len(visited_rooms) == len(rooms)
keys-and-rooms
[Python3] Soln -> Keys and Rooms [stack implementation]
avEraGeC0der
12
620
keys and rooms
841
0.702
Medium
13,635
https://leetcode.com/problems/keys-and-rooms/discuss/2292352/Python3-DFS
class Solution: def visitAll(self,rooms,index,visited): if index not in visited: visited.add(index) for i in rooms[index]: self.visitAll(rooms,i,visited) def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: visited = set() self.visitAll(rooms,0,visited) return len(visited)==len(rooms)
keys-and-rooms
📌 Python3 DFS
Dark_wolf_jss
2
34
keys and rooms
841
0.702
Medium
13,636
https://leetcode.com/problems/keys-and-rooms/discuss/1756839/Python-or-Simple-DFS-%2B-BFS-or-Explained-w-Complexity
class Solution: def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: n = len(rooms) seen = [False] * n stack = [0] # room 0 is unlocked while stack: room = stack.pop() if not seen[room]: # if not previously visited seen[room] = True for key in rooms[room]: stack.append(key) return all(seen)
keys-and-rooms
Python | Simple DFS + BFS | Explained w/ Complexity
leetbeet73
2
65
keys and rooms
841
0.702
Medium
13,637
https://leetcode.com/problems/keys-and-rooms/discuss/2159415/Python3-Runtime%3A-96ms-48.98-memory%3A-14.4mb-85.04
class Solution: # Runtime: 96ms 48.98% memory: 14.4mb 85.04% def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: seen = set() stack = [0] seen.add(stack[-1]) while stack: cur = stack.pop() for neigh in rooms[cur]: if not neigh in seen: seen.add(neigh) stack.append(neigh) return len(seen) == len(rooms)
keys-and-rooms
Python3 Runtime: 96ms 48.98% memory: 14.4mb 85.04%
arshergon
1
50
keys and rooms
841
0.702
Medium
13,638
https://leetcode.com/problems/keys-and-rooms/discuss/938340/Python3-dfs-O(N)
class Solution: def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: seen = [False]*len(rooms) stack = [0] while stack: n = stack.pop() if not seen[n]: seen[n] = True stack.extend(rooms[n]) return all(seen)
keys-and-rooms
[Python3] dfs O(N)
ye15
1
66
keys and rooms
841
0.702
Medium
13,639
https://leetcode.com/problems/keys-and-rooms/discuss/858375/Python3-BFS-Iterative
class Solution: def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: if len(rooms) == 0: return True visited = {0} queue = deque([0]) while queue: cur = queue.popleft() if cur > len(rooms): continue for key in rooms[cur]: if key not in visited: visited.add(key) queue.append(key) return len(visited) == len(rooms)
keys-and-rooms
[Python3] BFS Iterative
nachiketsd
1
46
keys and rooms
841
0.702
Medium
13,640
https://leetcode.com/problems/keys-and-rooms/discuss/2847364/Easiest-ever
class Solution: def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: seen = set() queue = deque() queue.append(0) seen.add(0) while queue: current_room = queue.popleft() for room_keys in rooms[current_room]: if room_keys not in seen: queue.append(room_keys) seen.add(room_keys) return len(rooms) == len(seen)
keys-and-rooms
Easiest ever
shriyansnaik
0
1
keys and rooms
841
0.702
Medium
13,641
https://leetcode.com/problems/keys-and-rooms/discuss/2833972/Easy-python-solution-using-BFS
class Solution: def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: vis = [0] * len(rooms) q = collections.deque() q.append(rooms[0]) vis[0] = 1 while q: for _ in range(len(q)): keys = q.popleft() for key in keys: if vis[key] == 0: q.append(rooms[key]) vis[key] = 1 for v in vis: if v == 0: return False return True
keys-and-rooms
Easy python solution using BFS
i-haque
0
2
keys and rooms
841
0.702
Medium
13,642
https://leetcode.com/problems/keys-and-rooms/discuss/2817635/BFS-or-Python-Solution
class Solution: def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: N = len(rooms) visited = [] queue = deque([0]) while queue: curr_room = queue.popleft() if curr_room not in visited: visited.append(curr_room) if len(visited) == N: return True if not len(rooms[curr_room]): continue for key in rooms[curr_room]: if key not in visited: queue.append(key) return False
keys-and-rooms
BFS | Python Solution
gautham0505
0
3
keys and rooms
841
0.702
Medium
13,643
https://leetcode.com/problems/keys-and-rooms/discuss/2787973/Python-oror-DFS-implementation-oror-No-recursion-needed.
class Solution: def canVisitAllRooms(self, rooms: list[list[int]]) -> bool: stack =[rooms[0]] visit = set() visit.add(0) while stack: nums = stack.pop() for i in nums: if i not in visit: stack.append(rooms[i]) visit.add(i) return True if len(visit) == len(rooms) else False
keys-and-rooms
Python || DFS implementation || No recursion needed.
khoai345678
0
3
keys and rooms
841
0.702
Medium
13,644
https://leetcode.com/problems/keys-and-rooms/discuss/2769605/Python-solution-or-BFS
class Solution: def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: q = deque() visited = [0] for i in range(len(rooms[0])): q.append(rooms[0][i]) while q: key = q.popleft() if key not in visited: for i in range(len(rooms[key])): q.append(rooms[key][i]) visited.append(key) if len(visited) == len(rooms): return True return False
keys-and-rooms
Python solution | BFS
maomao1010
0
3
keys and rooms
841
0.702
Medium
13,645
https://leetcode.com/problems/keys-and-rooms/discuss/2764878/DFS-with-set-instead-of-stack-(beats-95)
class Solution: def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: visited = set([0]) keys = set(rooms[0]) while keys: key = keys.pop() visited.add(key) for new_key in rooms[key]: if new_key not in visited: keys.add(new_key) return len(visited) == len(rooms)
keys-and-rooms
DFS with set instead of stack (beats 95%)
ivan-luchko
0
1
keys and rooms
841
0.702
Medium
13,646
https://leetcode.com/problems/keys-and-rooms/discuss/2567513/Clean-Fast-Python3-or-BFS
class Solution: def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: q, visited = deque([0]), {0} while q: cur = q.pop() for nxt in rooms[cur]: if nxt not in visited: visited.add(nxt) q.appendleft(nxt) return len(visited) == len(rooms)
keys-and-rooms
Clean, Fast Python3 | BFS
ryangrayson
0
14
keys and rooms
841
0.702
Medium
13,647
https://leetcode.com/problems/keys-and-rooms/discuss/2500490/Easy-python-DFS-solution
class Solution: def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: graph = defaultdict(lambda: []) all_nodes = set() for index, val in enumerate(rooms): all_nodes.add(index) graph[index] = val visited = set() def travel(graph, start): elem = start if elem not in visited: visited.add(elem) for val in graph[elem]: travel(graph, val) return False travel(graph, 0) if visited == all_nodes: return True return False
keys-and-rooms
Easy python DFS solution
prameshbajra
0
21
keys and rooms
841
0.702
Medium
13,648
https://leetcode.com/problems/keys-and-rooms/discuss/2421252/Keys-and-Rooms-oror-Python3-oror-Stack
class Solution: def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: seen = [False] * len(rooms) stack = [0] seen[0] = True while(len(stack)> 0): el = stack.pop() seen[el] = True for key in rooms[el]: if seen[key] == False: stack.append(key) return all(seen)
keys-and-rooms
Keys and Rooms || Python3 || Stack
vanshika_2507
0
11
keys and rooms
841
0.702
Medium
13,649
https://leetcode.com/problems/keys-and-rooms/discuss/2357335/Python3-or-Efficient-Python3-Solution-using-BFS-%2B-Queue
class Solution: #Time-Complexity: O(n + n^2) -> O(n^2) #Space-Complexity: O(n + n + n) -> O(n) def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: q = collections.deque() number_of_rooms = len(rooms) #if we visited every room, our visited set will match wanted_set! wanted_set = set() for i in range(number_of_rooms): wanted_set.add(i) #visited will keep track of all distinct visited rooms which will be updated as bfs traversal progresess! visited = set() #before initiating bfs, we append to queue room 0 and mark room 0 as visited! visited.add(0) q.append(0) #as long as queue is non-emtpy, continue bfs! #all elements of queue are waited to be processed and are not already visited! #in worst case, our queue have to process all n rooms if we can simply hop from ith room to i+1th room #until we visit every single room! while q: cur_room = q.popleft() set_of_keys = rooms[cur_room] #For each room our current room can lead to, check that it is not already visited to avoid #revisiting node(stuck in cycle) and make sure it's not a self loop! #this inner for loop in worst case runs n-1 times, cause ith room may provide keys to #all other rooms! for key in set_of_keys: if(key not in visited and key != cur_room): q.append(key) visited.add(key) #once our queue ends, see if visited == wanted_set if(visited == wanted_set): return True return False
keys-and-rooms
Python3 | Efficient Python3 Solution using BFS + Queue
JOON1234
0
17
keys and rooms
841
0.702
Medium
13,650
https://leetcode.com/problems/keys-and-rooms/discuss/2285234/Simple-DFS-Python
class Solution: def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: visited = set() stack = [0] while stack: vertex = stack.pop() visited.add(vertex) for key in rooms[vertex]: if key not in visited: stack.append(key) return len(visited) == len(rooms) ```
keys-and-rooms
Simple DFS Python
baz-gaul
0
6
keys and rooms
841
0.702
Medium
13,651
https://leetcode.com/problems/keys-and-rooms/discuss/2237876/Easy-DFS-Approach-oror-Clean-Code
class Solution: def dfs(self, rooms, graph, idx, visited): visited[idx] = 1 for neighbour in graph[idx]: if visited[neighbour] == 0: visited = self.dfs(rooms, graph, neighbour, visited) return visited def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: totalRooms = len(rooms) visited = [0]*totalRooms graph = {i : [] for i in range(totalRooms)} for idx, val in enumerate(rooms): graph[idx] = val visited = self.dfs(rooms, graph, 0, visited) return visited.count(1) == len(visited)
keys-and-rooms
Easy DFS Approach || Clean Code
Vaibhav7860
0
36
keys and rooms
841
0.702
Medium
13,652
https://leetcode.com/problems/keys-and-rooms/discuss/2202418/Python-3-or-BFS-to-verify-if-all-room-is-accessible
class Solution: def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: seen, q = set(), deque([0]) while q: r = q.popleft() seen.add(r) q += [key for key in rooms[r] if key not in seen] return len(seen) == len(rooms)
keys-and-rooms
Python 3 | BFS to verify if all room is accessible
Ploypaphat
0
19
keys and rooms
841
0.702
Medium
13,653
https://leetcode.com/problems/keys-and-rooms/discuss/2175988/Python-or-BFS
class Solution: def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: access = [True] + [False] * (len(rooms) - 1) print(access) q = [] q.extend(rooms[0]) while q: room_no = q.pop(0) if access[room_no]: continue else: access[room_no] = True q.extend(rooms[room_no]) return all(access)
keys-and-rooms
Python | BFS
tejeshreddy111
0
13
keys and rooms
841
0.702
Medium
13,654
https://leetcode.com/problems/keys-and-rooms/discuss/2049594/Python-3-greater-BFS-99-faster
class Solution: def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: if not rooms: return 1 return self.helperBFS(rooms) def helperBFS(self, rooms): visited = [False] * len(rooms) queue = collections.deque([0]) visited[0] = True while queue: key = queue.popleft() for k in rooms[key]: if not visited[k]: queue.append(k) visited[k] = True return all(visited)
keys-and-rooms
Python 3 -> BFS 99% faster
mybuddy29
0
28
keys and rooms
841
0.702
Medium
13,655
https://leetcode.com/problems/keys-and-rooms/discuss/2036810/easy-and-efficient-2-python-solutions
class Solution: def canVisitAllRooms(self, graph: List[List[int]]) -> bool: def dfs(node) : if node not in seen : seen.add(node) for v in graph[node] : dfs(v) seen = set() dfs(0) return False if len(seen) < len(graph) else True
keys-and-rooms
easy and efficient 2 python solutions
runtime-terror
0
41
keys and rooms
841
0.702
Medium
13,656
https://leetcode.com/problems/keys-and-rooms/discuss/2036810/easy-and-efficient-2-python-solutions
class Solution: def canVisitAllRooms(self, graph: List[List[int]]) -> bool: seen = set() q = deque([0]) while q : node = q.popleft() seen.add(node) for v in graph[node] : if v not in seen : q.append(v) return False if len(seen) < len(graph) else True
keys-and-rooms
easy and efficient 2 python solutions
runtime-terror
0
41
keys and rooms
841
0.702
Medium
13,657
https://leetcode.com/problems/keys-and-rooms/discuss/1916999/Python3-or-Queue-or-BFS-or-Easy-to-understand-or-Faster-than-90
class Solution: def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: n, q = len(rooms) - 1, [0] vis = [False] * (n + 1) while q: temp = q.pop(0) while not vis[temp]: vis[temp] = True for i in rooms[temp]: if not vis[i] : q.append(i) for i in vis: if i == False: return False return True
keys-and-rooms
Python3 | Queue | BFS | Easy to understand | Faster than 90%
milannzz
0
15
keys and rooms
841
0.702
Medium
13,658
https://leetcode.com/problems/keys-and-rooms/discuss/1890681/Easy-to-understand-BFS-approach
class Solution: from collections import deque def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: if rooms==[]: return True if rooms[0]==[]: return False que = deque() visited = set() visited.add(0) for i in rooms[0]: que.append(i) while que: key = que.popleft() if key not in visited: visited.add(key) for room_keys in rooms[key]: que.append(room_keys) if len(rooms)-len(visited)==0: return True return False
keys-and-rooms
Easy to understand BFS approach
gamitejpratapsingh998
0
27
keys and rooms
841
0.702
Medium
13,659
https://leetcode.com/problems/keys-and-rooms/discuss/1868676/Python-BFS-Approach
class Solution: def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: access = [False] * len(rooms) access[0] = True queue = [] queue.extend(rooms[0]) while queue: for i in range(len(queue)): room_no = queue.pop(0) if not access[room_no]: access[room_no] = True queue.extend(rooms[room_no]) if all(access): return True return False
keys-and-rooms
[Python] BFS Approach
tejeshreddy111
0
13
keys and rooms
841
0.702
Medium
13,660
https://leetcode.com/problems/keys-and-rooms/discuss/1846732/Python-l-Iterative-BFS-using-Queue
class Solution: def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: n = len(rooms) graph = defaultdict(list) for i in range(n): for keys in rooms[i]: graph[i].append(keys) Q = deque([0]) visited = set() while Q: vertex = Q.popleft() if vertex in visited: continue visited.add(vertex) for neib in graph[vertex]: Q.append(neib) if len(visited) == n: return True return False
keys-and-rooms
Python l Iterative BFS using Queue
morpheusdurden
0
18
keys and rooms
841
0.702
Medium
13,661
https://leetcode.com/problems/keys-and-rooms/discuss/1815668/Python-dfs-Easy-to-understand
class Solution: def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: # you have to start somewhere (room 0 in this case) so the key to that room is always collected def backtrack(currentRoomKey=0, keysCollected=set([0])): # We know how many rooms there are, so if we have collected same amount of keys then we know that we can visit all the rooms if len(keysCollected) == len(rooms): return True # look at all the keys in the room, one at a time for someNumberedKey in rooms[currentRoomKey]: # if we have already collected the this key then examine the next key if someNumberedKey in keysCollected: continue # if we haven't collected this key then add it to our bag keysCollected.add(someNumberedKey) # travel to the key's respective room and repeat the above steps roomUnlocked = backtrack(someNumberedKey, keysCollected) # if we unlocked the all the rooms upahead (deeper in recursion) then propogate true back if roomUnlocked: return True else: return False # if there are no more unique keys in this room then return to the previous room return False return backtrack()
keys-and-rooms
Python dfs - Easy to understand
Rush_P
0
26
keys and rooms
841
0.702
Medium
13,662
https://leetcode.com/problems/keys-and-rooms/discuss/1690654/Easy-to-Understand-and-Fast-Python-Solution
class Solution: def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: n = len(rooms) roomsToCheck = [0] visitedCount = 0 visitedArr = [0] * n while roomsToCheck: room = roomsToCheck.pop() if visitedArr[room] == 0: visitedArr[room] = 1 visitedCount += 1 if visitedCount == n: return True roomsToCheck += rooms[room] return False
keys-and-rooms
Easy to Understand and Fast Python Solution
josejassojr
0
38
keys and rooms
841
0.702
Medium
13,663
https://leetcode.com/problems/keys-and-rooms/discuss/1659070/BFS-Python-faster-than-70
class Solution: def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: graph={} for i,val in enumerate(rooms): graph[i]=val print(graph) visited=[] queue=[] def bfs(node): visited.append(node) queue.append(node) while queue: m=queue.pop(0) print(str(m)+ " ") for neighbour in graph[m]: if neighbour not in visited: visited.append(neighbour) queue.append(neighbour) print(bfs(0)) return(len(visited)==len(rooms))
keys-and-rooms
BFS Python faster than 70%
naren_nadig
0
23
keys and rooms
841
0.702
Medium
13,664
https://leetcode.com/problems/keys-and-rooms/discuss/1607775/Python3-Intuitive-BFS-Solution-for-Beginners
class Solution: def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: visited = set() q = collections.deque() start = rooms[0] if len(start) > 0: q.append(start) visited.add(0) # if the room 0 has no key at all, return false directly else: return False while q: keys = q.popleft() for k in keys: if k in visited: continue q.append(rooms[k]) visited.add(k) # since a set is used to track the visited rooms, there will be no duplicates in the visited set # so once the visited set's length is equal to the input array's length, all rooms are visited return len(rooms) == len(visited)
keys-and-rooms
Python3 Intuitive BFS Solution for Beginners
Hauptwaffenamt
0
40
keys and rooms
841
0.702
Medium
13,665
https://leetcode.com/problems/keys-and-rooms/discuss/1580929/Python3-Solution
class Solution: def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: visited = [False]*len(rooms) def dfs(roomNo): if visited[roomNo] : return visited[roomNo] = True for i in rooms[roomNo]: dfs(i) dfs(0) return all(visited)
keys-and-rooms
Python3 Solution
satyam2001
0
61
keys and rooms
841
0.702
Medium
13,666
https://leetcode.com/problems/keys-and-rooms/discuss/1558943/Python3-solution-comments-or-easy-to-read
class Solution: def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: def dfs(rooms, arr, reachable, index): #arr = current room reachable.add(index) # current index | room where we are at for i in range(len(arr)): if arr[i] not in reachable: reachable.add(arr[i]) index = arr[i] dfs(rooms, rooms[arr[i]], reachable, index) reachable = set() # set with the keys of rooms we have dfs(rooms, rooms[0], reachable, 0) for i in range(len(rooms)): if i not in reachable: return False return True
keys-and-rooms
Python3 solution comments | easy to read
FlorinnC1
0
38
keys and rooms
841
0.702
Medium
13,667
https://leetcode.com/problems/keys-and-rooms/discuss/1440207/Simple-Python-recursive-dfs
class Solution: def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: def dfs(cur_room): for key in rooms[cur_room]: if not visited[key]: visited[key] = True dfs(key) visited = [True]+[False]*(len(rooms)-1) dfs(0) return sum(visited) == len(rooms)
keys-and-rooms
Simple Python recursive dfs
Charlesl0129
0
59
keys and rooms
841
0.702
Medium
13,668
https://leetcode.com/problems/keys-and-rooms/discuss/1301846/Python3-simple-solution
class Solution: def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: visited = [0] keys = rooms[0] while keys: x = keys.pop(0) if x not in visited: visited.append(x) else: continue for i in rooms[x]: if i not in keys: keys.append(i) return len(visited) == len(rooms)
keys-and-rooms
Python3 simple solution
EklavyaJoshi
0
54
keys and rooms
841
0.702
Medium
13,669
https://leetcode.com/problems/keys-and-rooms/discuss/1299064/Python-solution-for-record-purpose
class Solution: def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: visited = set() visited.add(0) stack = [0] while stack: i = stack.pop() for key in rooms[i]: if key not in visited: visited.add(key) stack.append(key) return len(visited) == len(rooms)
keys-and-rooms
Python solution for record purpose
konnomiya
0
19
keys and rooms
841
0.702
Medium
13,670
https://leetcode.com/problems/keys-and-rooms/discuss/1169857/Python-DFS-using-Set.
class Solution: def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: visited = set() def dfs(room): if room in visited: return visited.add(room) for r in rooms[room]: dfs(r) dfs(0) return len(visited) == len(rooms)
keys-and-rooms
Python DFS using Set.
reyna_main
0
76
keys and rooms
841
0.702
Medium
13,671
https://leetcode.com/problems/keys-and-rooms/discuss/1149776/Python3-solution-(using-stack)
class Solution: def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: seen: List[bool] = [False] * len(rooms) seen[0] = True keys: List[int] = [*rooms[0]] while keys: cur_key: int = keys.pop() seen[cur_key] = True for new_key in rooms[cur_key]: if not seen[new_key]: keys.append(new_key) return all(seen)
keys-and-rooms
Python3 solution (using stack)
alexforcode
0
23
keys and rooms
841
0.702
Medium
13,672
https://leetcode.com/problems/keys-and-rooms/discuss/1117910/Python-Recursive-Solution-Keys-and-Rooms
class Solution: def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: def helper(current_room, visited): for key in current_room: if key not in visited: visited.append(key) helper(rooms[key], visited) return visited #len(visited) == len(rooms)? return len(helper(rooms[0], [0])) == len(rooms)
keys-and-rooms
Python Recursive Solution - Keys and Rooms
ronald-luo
0
38
keys and rooms
841
0.702
Medium
13,673
https://leetcode.com/problems/keys-and-rooms/discuss/1117318/python3-dfs
class Solution: def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: count = 1 keys = rooms[0] n = len(rooms) visited = {0: True} while keys: key = keys.pop(0) if key not in visited: visited[key] = True count += 1 for i in rooms[key]: if i not in visited: keys.append(i) return count == n
keys-and-rooms
python3 dfs
loharvikas13
0
25
keys and rooms
841
0.702
Medium
13,674
https://leetcode.com/problems/keys-and-rooms/discuss/1100704/Easy-Python3-Solution
class Solution: def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: discovered = [0] for i in discovered: for j in rooms[i]: if j not in discovered: discovered.append(j) if len(discovered) == len(rooms): return True return False
keys-and-rooms
Easy Python3 Solution
yash2709
0
39
keys and rooms
841
0.702
Medium
13,675
https://leetcode.com/problems/keys-and-rooms/discuss/1049291/Yet-Another-Simple-Python-Solution
class Solution: def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: n = len(rooms) visited = [0]*n def dfs(a_room): visited[a_room] = 1 for a_key in rooms[a_room]: if visited[a_key]==0: dfs(a_key) dfs(0) for val in visited: if val == 0: return False return True
keys-and-rooms
Yet Another Simple Python Solution
SaSha59
0
26
keys and rooms
841
0.702
Medium
13,676
https://leetcode.com/problems/keys-and-rooms/discuss/1035865/Python-beats-98-bfs-and-set
class Solution: def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: q=[] q.append(0) if len(rooms)==1: return True s=set() s.add(0) while q: cur = q.pop(0) for i in rooms[cur]: if i not in s: s.add(i) q.append(i) if len(s)==len(rooms): return True return False
keys-and-rooms
Python beats 98% bfs and set
gauravgoyalll
0
66
keys and rooms
841
0.702
Medium
13,677
https://leetcode.com/problems/keys-and-rooms/discuss/650510/Intuitive-approach-by-keep-visited-room-and-list-of-room-to-visit
class Solution: def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: visited_room_set = set() ''' Set to keep visited room''' next_room_to_visit = [0] ''' List to hold list of room to visit from next round''' # 1) Visit room and obtain key for next round of room to visit iteratively while next_room_to_visit: unvisited_room = [] for r in next_room_to_visit: visited_room_set.add(r) for k in rooms[r]: if k not in visited_room_set: unvisited_room.append(k) next_room_to_visit = unvisited_room # 2) Check if the number of visited room is equal to the total number of room return len(visited_room_set) == len(rooms)
keys-and-rooms
Intuitive approach by keep visited room and list of room to visit
puremonkey2001
0
20
keys and rooms
841
0.702
Medium
13,678
https://leetcode.com/problems/keys-and-rooms/discuss/650510/Intuitive-approach-by-keep-visited-room-and-list-of-room-to-visit
class Solution: def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: A, B = [0], [] visited_room_set = set() while A: B = set([k for r in A for k in rooms[r] if k not in visited_room_set]) visited_room_set.update(A) A, B = B, [] return len(visited_room_set) == len(rooms)
keys-and-rooms
Intuitive approach by keep visited room and list of room to visit
puremonkey2001
0
20
keys and rooms
841
0.702
Medium
13,679
https://leetcode.com/problems/split-array-into-fibonacci-sequence/discuss/1579510/PYTHON-BACKTRACKING-or-THREE-PROBLEMS-ONE-SOLUTION
class Solution: def splitIntoFibonacci(self, num: str) -> List[int]: def dfs(i): if i>=len(num): return len(ans)>2 n = 0 for j in range(i, len(num)): n = n*10 + int(num[j]) if n>2**31: # if number exceeds the range mentioned return False # if len < 2 we know more elements need to be appended # as size>=3 if size is already greater we check for fibonacci # as last + secondLast == curr if len(ans)<2 or (ans[-1]+ans[-2]==n): ans.append(n) if dfs(j+1): return True ans.pop() if i==j and num[j]=='0': # if trailing 0 is present return False if len(num)<=2: return [] ans = [] if dfs(0): return ans return []
split-array-into-fibonacci-sequence
PYTHON BACKTRACKING | THREE PROBLEMS ONE SOLUTION
hX_
1
150
split array into fibonacci sequence
842
0.383
Medium
13,680
https://leetcode.com/problems/split-array-into-fibonacci-sequence/discuss/1579510/PYTHON-BACKTRACKING-or-THREE-PROBLEMS-ONE-SOLUTION
class Solution: def isAdditiveNumber(self, num: str) -> List[int]: def dfs(i, ans): if i>=len(num): return len(ans)>2 n = 0 for j in range(i, len(num)): n = n*10 + int(num[j]) if len(ans)<2 or (ans[-1]+ans[-2]==n): ans.append(n) if dfs(j+1, ans): return True ans.pop() if i==j and num[j]=='0': return False return dfs(0, [])
split-array-into-fibonacci-sequence
PYTHON BACKTRACKING | THREE PROBLEMS ONE SOLUTION
hX_
1
150
split array into fibonacci sequence
842
0.383
Medium
13,681
https://leetcode.com/problems/split-array-into-fibonacci-sequence/discuss/1579510/PYTHON-BACKTRACKING-or-THREE-PROBLEMS-ONE-SOLUTION
class Solution: def splitString(self, s: str) -> bool: def dfs(i, ans): if i>=len(s): return len(ans)>1 n = 0 for j in range(i, len(s)): n = n*10 + int(s[j]) if len(ans)<1 or (ans[-1]-1==n): ans.append(n) if dfs(j+1, ans): return True ans.pop() return dfs(0, [])
split-array-into-fibonacci-sequence
PYTHON BACKTRACKING | THREE PROBLEMS ONE SOLUTION
hX_
1
150
split array into fibonacci sequence
842
0.383
Medium
13,682
https://leetcode.com/problems/split-array-into-fibonacci-sequence/discuss/986705/Python3-efficient-brute-force
class Solution: def splitIntoFibonacci(self, S: str) -> List[int]: for i in range(1, min(11, len(S))): # 2**31 limit if S[0] == "0" and i > 1: break for j in range(i+1, min(i+11, len(S))): # 2**31 limit if S[i] == "0" and j-i > 1: break x, y = int(S[:i]), int(S[i:j]) ans = [x, y] while j < len(S): x, y = y, x+y if y <= 2**31 and S[j:j+len(str(y))] == str(y): ans.append(y) j += len(str(y)) else: break else: if len(ans) > 2: return ans # no break encountered return []
split-array-into-fibonacci-sequence
[Python3] efficient brute-force
ye15
1
106
split array into fibonacci sequence
842
0.383
Medium
13,683
https://leetcode.com/problems/split-array-into-fibonacci-sequence/discuss/1486859/Python-3-or-Simulation-or-Explanation
class Solution: def splitIntoFibonacci(self, num: str) -> List[int]: two_31 = 2 ** 31 n = len(num) def fibo(a, b, j): nonlocal n cur = [] while j < n: a, b = b, a+b if b > two_31: return [] b_str = str(b) if num[j:].startswith(b_str): cur.append(b) j += len(b_str) else: return [] else: return cur for i in range(1, n): if i > 1 and num[0] == '0': break a_str = num[:i] a = int(num[:i]) if a > two_31: break for j in range(i+1, n): if j > i+1 and num[i] == '0': break b_str = num[i:j] b = int(num[i:j]) if b > two_31: break cur = fibo(a, b, j) if not cur: continue return [a, b] + cur return []
split-array-into-fibonacci-sequence
Python 3 | Simulation | Explanation
idontknoooo
0
255
split array into fibonacci sequence
842
0.383
Medium
13,684
https://leetcode.com/problems/split-array-into-fibonacci-sequence/discuss/425478/Python-Backtrack-28ms-beats-99.26-easy-understanding
class Solution: def splitIntoFibonacci(self, S: str) -> List[int]: res=[] current=[] def backtrack(cursor,current): #``cursor'' represents the current scanning cursor, ``current'' represents the current partial result if len(current)>=3 and cursor==len(S): # reach a result res.append(current) return if len(current)<2: #add first two items into partial result for index in range(cursor,len(S)): avai=S[cursor:index+1] if (avai[0]=="0" and len(avai)>1) or int(avai)>2**31-1: # if have leading zeros, break return backtrack(index+1,current+[int(avai)]) else: a=current[-1] b=current[-2] seek=str(a+b) if S[cursor:cursor+len(seek)]==seek and int(seek)<2**31-1: backtrack(cursor+len(seek),current+[int(seek)]) else: return backtrack(0,current) if res: return res[0] else: return res
split-array-into-fibonacci-sequence
Python Backtrack 28ms beats 99.26%, easy-understanding
wangzi100
0
177
split array into fibonacci sequence
842
0.383
Medium
13,685
https://leetcode.com/problems/split-array-into-fibonacci-sequence/discuss/353022/Solution-in-Python-3
class Solution: def splitIntoFibonacci(self, S: str) -> List[int]: L, T, t = len(S), "", [] for i in range(1,L-2): for j in range(1,L-i-1): if (i > 1 and S[0] == '0') or (j > 1 and S[i] == '0'): continue a, b = int(S[:i]), int(S[i:i+j]) T, t = S[:i+j], [a,b] while len(T) < L: c = a + b T += str(c) t += [c] a, b = b, c if len(T) == L and T == S and len(t) > 2 and t[-1] < 2**31 - 1: return t return [] - Junaid Mansuri (Leet Code ID)@hotmail.com
split-array-into-fibonacci-sequence
Solution in Python 3
junaidmansuri
0
312
split array into fibonacci sequence
842
0.383
Medium
13,686
https://leetcode.com/problems/guess-the-word/discuss/2385099/Python-Solution-with-narrowed-candidates-and-blacklist
class Solution: def findSecretWord(self, words: List[str], master: 'Master') -> None: k = 1 # for tracing the number of loops matches = 0 blacklists = [[] for i in range(6)] while matches != 6: n = len(words) r = random.randint(0, n - 1) matches = master.guess(words[r]) key = words[r] # print(k, n, r, matches, key) words.pop(r) if matches == 0: for i in range(6): blacklists[i].append(key[i]) # print(blacklists) elif matches > 0 and matches < 6: candidates = [] for i in range(n - 1): count = 0 for j in range(6): if words[i][j] not in blacklists[j] and words[i][j] == key[j]: count += 1 if count >= matches: candidates.append(words[i]) words = candidates.copy() # print(words) k += 1
guess-the-word
[Python] Solution with narrowed candidates and blacklist
bbshark
2
203
guess the word
843
0.418
Hard
13,687
https://leetcode.com/problems/guess-the-word/discuss/1552899/Reduce-by-Hamming-distance.-28-ms-faster-than-91.22-and-14.2-MB-less-than-92.67.-Python-3.
class Solution: def findSecretWord(self, wordlist: List[str], master: 'Master') -> None: def hamming_distance(w1: str, w2: str) -> int: return sum(1 for k in range(6) if w1[k] != w2[k]) current_guess = wordlist[0] curr_distance = 6 - Master.guess(master, current_guess) while curr_distance != 0: # Secret word have <current_distance> form our <current_guess>. # Therefore secret word is one of the words with Hamming distance <current_distance> from our <current_guess>. # So lets delete all other words. wordlist = [w for w in wordlist if hamming_distance(current_guess, w) == curr_distance] # current_guess = wordlist.pop(random.randint(0, len(wordlist) - 1)) # You sould not use any random. In some random cases # number of guesses may be ecxeed 10, but in next attempt it's not, etc. current_guess = wordlist.pop() curr_distance = 6 - Master.guess(master, current_guess)
guess-the-word
Reduce by Hamming distance. 28 ms, faster than 91.22% & 14.2 MB, less than 92.67%. Python 3.
timofeybelov
2
525
guess the word
843
0.418
Hard
13,688
https://leetcode.com/problems/guess-the-word/discuss/2448974/python-minimax
class Solution: def findSecretWord(self, words: List[str], master: 'Master') -> None: def find_hits(wd1, wd2): return sum(1 for i in range(6) if wd1[i] == wd2[i]) def next_candidate_mini_max(): minimax = ['', sys.maxsize] for wd1 in words: count = sum(1 for wd2 in words if not find_hits(wd1, wd2)) if count <= minimax[1]: minimax[0] = wd1 minimax[1] = count return minimax[0] hit = -1; while hit != 6: word = next_candidate_mini_max() hit = master.guess(word) # converge candidate list of words towards the target words = [wd for wd in words if hit == find_hits(word, wd)]
guess-the-word
python minimax
sinha_meenu
0
218
guess the word
843
0.418
Hard
13,689
https://leetcode.com/problems/guess-the-word/discuss/1369019/Python3-shuffle
class Solution: def findSecretWord(self, wordlist: List[str], master: 'Master') -> None: shuffle(wordlist) # statistical guarantee to pass for _ in range(10): if wordlist: w = wordlist.pop() m = master.guess(w) wordlist = [ww for ww in wordlist if sum(x == xx for x, xx in zip(w, ww)) == m]
guess-the-word
[Python3] shuffle
ye15
0
294
guess the word
843
0.418
Hard
13,690
https://leetcode.com/problems/guess-the-word/discuss/1610311/Python3-Easy-Solution
class Solution: def findSecretWord(self, wordlist: List[str], master: 'Master') -> None: master.guess(master._Master__secret)
guess-the-word
Python3 Easy Solution
description
-2
341
guess the word
843
0.418
Hard
13,691
https://leetcode.com/problems/backspace-string-compare/discuss/381659/Three-Solutions-in-Python-3-(With-and-Without-Deque-and-Two-Pointer)
class Solution: def backspaceCompare(self, S: str, T: str) -> bool: a, A = [collections.deque(), collections.deque()], [S,T] for i in range(2): for j in A[i]: if j != '#': a[i].append(j) elif a[i]: a[i].pop() return a[0] == a[1]
backspace-string-compare
Three Solutions in Python 3 (With and Without Deque and Two-Pointer)
junaidmansuri
16
2,600
backspace string compare
844
0.48
Easy
13,692
https://leetcode.com/problems/backspace-string-compare/discuss/381659/Three-Solutions-in-Python-3-(With-and-Without-Deque-and-Two-Pointer)
class Solution: def backspaceCompare(self, S: str, T: str) -> bool: s, t = [], [] for i in S: s = s + [i] if i != '#' else s[:-1] for i in T: t = t + [i] if i != '#' else t[:-1] return s == t
backspace-string-compare
Three Solutions in Python 3 (With and Without Deque and Two-Pointer)
junaidmansuri
16
2,600
backspace string compare
844
0.48
Easy
13,693
https://leetcode.com/problems/backspace-string-compare/discuss/381659/Three-Solutions-in-Python-3-(With-and-Without-Deque-and-Two-Pointer)
class Solution: def backspaceCompare(self, S: str, T: str) -> bool: a, A = [[],[],0,0], [S,T] for i in range(2): for j in A[i][::-1]: if j != '#': if a[i+2] == 0: a[i].append(j) else: a[i+2] -= 1 else: a[i+2] += 1 return a[0] == a[1] - Junaid Mansuri (LeetCode ID)@hotmail.com
backspace-string-compare
Three Solutions in Python 3 (With and Without Deque and Two-Pointer)
junaidmansuri
16
2,600
backspace string compare
844
0.48
Easy
13,694
https://leetcode.com/problems/backspace-string-compare/discuss/2727888/Python's-Simple-and-Easy-to-Understand-Solutionor-O(n)-Solution-or-99-Faster
class Solution: def backspaceCompare(self, s: str, t: str) -> bool: s_backspaced = [] t_backspaced = [] for i in range(len(s)): if s[i] == '#': if s_backspaced: s_backspaced.pop() else: s_backspaced.append(s[i]) for i in range(len(t)): if t[i] == '#': if t_backspaced: t_backspaced.pop() else: t_backspaced.append(t[i]) return s_backspaced == t_backspaced
backspace-string-compare
✔️ Python's Simple and Easy to Understand Solution| O(n) Solution | 99% Faster 🔥
pniraj657
11
639
backspace string compare
844
0.48
Easy
13,695
https://leetcode.com/problems/backspace-string-compare/discuss/570675/PythonJSJavaC%2B%2B-O(-n-)-sol-by-stack.-w-Comment
class Solution: def backspaceCompare(self, S: str, T: str) -> bool: stack_s, stack_t = [], [] # -------------------------------------- def final_string( stk, string ): for char in string: if char != '#': # push new character into stack stk.append( char ) elif stk: # pop last charachter from stack, as a result of backspace operation stk.pop() return ''.join(stk) # -------------------------------------- return final_string( stack_s, S ) == final_string( stack_t, T )
backspace-string-compare
Python/JS/Java/C++ O( n ) sol by stack. [w/ Comment]
brianchiang_tw
9
1,100
backspace string compare
844
0.48
Easy
13,696
https://leetcode.com/problems/backspace-string-compare/discuss/1997156/Python-Clean-and-Simple!
class Solution: def backspaceCompare(self, s, t): return self.parse(s) == self.parse(t) def parse(self, x): res = [] for c in x: if c != "#": res.append(c) else: if res: res.pop() return res
backspace-string-compare
Python - Clean and Simple!
domthedeveloper
7
758
backspace string compare
844
0.48
Easy
13,697
https://leetcode.com/problems/backspace-string-compare/discuss/1997156/Python-Clean-and-Simple!
class Solution: def backspaceCompare(self, s, t): i, j = len(s), len(t) while i >= 0 and j >= 0: delete = 1 while delete: i -= 1; delete += 1 if i >= 0 and s[i] == '#' else -1 delete = 1 while delete: j -= 1; delete += 1 if j >= 0 and t[j] == '#' else -1 if i >= 0 and j >= 0 and s[i] != t[j]: return False return i < 0 and j < 0
backspace-string-compare
Python - Clean and Simple!
domthedeveloper
7
758
backspace string compare
844
0.48
Easy
13,698
https://leetcode.com/problems/backspace-string-compare/discuss/1997849/Simple-stack-implementation-in-python-with-error-handling
class Solution: def backspaceCompare(self, s: str, t: str) -> bool: stack1=[] stack2=[] for i in range(len(s)): try: if s[i]=="#": stack1.pop() else: stack1.append(s[i]) except: continue for i in range(len(t)): try: if t[i]=="#": stack2.pop() else: stack2.append(t[i]) except: continue return True if stack1==stack2 else False
backspace-string-compare
Simple stack implementation in python with error handling
amannarayansingh10
3
204
backspace string compare
844
0.48
Easy
13,699