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/most-stones-removed-with-same-row-or-column/discuss/2812849/Pthon3-or-Simple-or-DFS
class Solution: def dfs(self, x, y, edgeList, seen): if (x, y) in seen: return seen[(x, y)] = True for x1, y1 in edgeList[(x, y)]: self.dfs(x1, y1, edgeList, seen) def removeStones(self, stones: List[List[int]]) -> int: r, c = defaultdict(list), defaultdict(list) for x, y in stones: r[x].append((x, y)) c[y].append((x, y)) edgeList = defaultdict(list) for x, y in stones: edgeList[(x, y)] += r[x] edgeList[(x, y)] += c[y] count = 0 seen = {} for x, y in stones: if (x, y) not in seen: self.dfs(x, y, edgeList, seen) count += 1 return len(stones) - count
most-stones-removed-with-same-row-or-column
Pthon3 | Simple | DFS
vikinam97
0
11
most stones removed with same row or column
947
0.588
Medium
15,400
https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/discuss/2812753/(Python)-No-Use-Union-and-Find-Straight-Forward-Solution
class Solution: def removeStones(self, stones: List[List[int]]) -> int: parents = [] for x, y in stones: if parents : tmp = [] res = [] # Find the connection between new node and previous groups for i in range(len(parents)) : xSet = parents[i][0] ySet = parents[i][1] if x in xSet or y in ySet : # Record the connections on list ('tmp') tmp.append(i) else : # If there is no connection, record it on the other list ('res') res.append(parents[i]) # Union the groups that have connection each other if tmp : xSet = {x} ySet = {y} for i in tmp: xSet |= parents[i][0] ySet |= parents[i][1] # And Union new born group with previous groups ('res') that has no connection res.append([xSet, ySet]) parents = res # If there is no connection else : parents.append([{x}, {y}]) else : parents.append([{x}, {y}]) return len(stones)-len(parents)
most-stones-removed-with-same-row-or-column
(Python) No Use Union & Find, Straight Forward Solution
SooCho_i
0
13
most stones removed with same row or column
947
0.588
Medium
15,401
https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/discuss/2812709/Python3-Simple-DSU-Solution
class Solution: def removeStones(self, stones: List[List[int]]) -> int: uf=UnionFind(len(stones)) for i in range(len(stones)): for j in range(i+1,len(stones)): #print(i,j) for k in range(2): if stones[i][k]==stones[j][k]: uf.union(i,j) return uf.out class UnionFind: def __init__(self, size): self.root = [i for i in range(size)] self.out=0 def find(self, x): if x == self.root[x]: return x self.root[x] = self.find(self.root[x]) return self.root[x] def union(self, x, y): rootX = self.find(x) rootY = self.find(y) if rootX != rootY: self.root[rootY] = rootX self.out+=1 #print(x,y,self.out)
most-stones-removed-with-same-row-or-column
[Python3] Simple DSU Solution
Hikari-Tsai
0
14
most stones removed with same row or column
947
0.588
Medium
15,402
https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/discuss/2812703/2-Dictionaries-%2B-DFS-greater-O(N)
class Solution: def dfs(self, r, c, graph_r, graph_c, visited): if (r, c) in visited: return 0 visited.add((r, c)) count = 0 for nr, nc in graph_r[r]: if nr != c or nc != r: count += self.dfs(nr, nc, graph_r, graph_c, visited) for nr, nc in graph_c[c]: if nr != c or nc != r: count += self.dfs(nr, nc, graph_r, graph_c, visited) return count + 1 def removeStones(self, stones: List[List[int]]) -> int: graph_r = defaultdict(list) graph_c = defaultdict(list) for r, c in stones: graph_r[r].append((r, c)) graph_c[c].append((r, c)) res = 0 visited = set() for r, c in stones: count = self.dfs(r, c, graph_r, graph_c, visited) if count: res += (count - 1) return res
most-stones-removed-with-same-row-or-column
2 Dictionaries + DFS => O(N)
baanhnguyen92
0
12
most stones removed with same row or column
947
0.588
Medium
15,403
https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/discuss/2812522/Python-Simple-DFS-solution
class Solution: def dfs(self,x,y): self.stones.remove([x,y]) l = -1 while self.stones and len(self.stones) != l: l = len(self.stones) for a,b in self.stones: if a == x or b == y: self.dfs(a,b) break def removeStones(self, stones: List[List[int]]) -> int: l_all = len(stones) self.stones = stones l = -1 island = 0 while self.stones and len(self.stones) != l: l = len(self.stones) for x,y in self.stones: self.dfs(x,y) island += 1 break return l_all - island
most-stones-removed-with-same-row-or-column
Python Simple DFS solution
AllenXia
0
19
most stones removed with same row or column
947
0.588
Medium
15,404
https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/discuss/2812449/Python3-simple-DFS-approach
class Solution: def removeStones(self, stones: List[List[int]]) -> int: def dfs(rows, cols, r, c, visited): visited.add((r,c)) for row,col in rows[r]: if (row,col) not in visited: dfs(rows, cols, row, col, visited) for row,col in cols[c]: if (row,col) not in visited: dfs(rows, cols, row, col, visited) rows, cols = {}, {} for r,c in stones: rows[r] = rows.get(r,[])+[(r,c)] cols[c] = cols.get(c,[])+[(r,c)] shared = 0 visited = set() for r, c in stones: if (r,c) not in visited: shared += 1 dfs(rows, cols, r, c, visited) return len(stones) - shared
most-stones-removed-with-same-row-or-column
Python3 simple DFS approach
shashank732001
0
37
most stones removed with same row or column
947
0.588
Medium
15,405
https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/discuss/2420982/Most-stones-removed-with-same-row-or-column-oror-Python3-oror-Union-Find
class Solution: def removeStones(self, stones: List[List[int]]) -> int: root = set() parent = {} rank = {} for x, y in stones: self.set_param(x, parent, rank) self.set_param(~y, parent, rank) self.union(x, ~y, parent, rank) # get parent for all nodes for p in parent: root.add(self.find(parent[p], parent)) # Answer is: no. of stones - no. of components # Since we can't remove all stones from a components, there we be number of components number of stones left return len(stones) - len(root) def set_param(self, x, parent, rank): if(x not in parent): parent[x] = x rank[x] = 0 def find(self, x, parent): if(x != parent[x]): parent[x] = self.find(parent[x], parent) return parent[x] def union(self, x, y, parent, rank): parent_x = self.find(x, parent) parent_y = self.find(y, parent) if(parent_x == parent_y): return rank_x = rank[parent_x] rank_y = rank[parent_y] if(rank_x > rank_y): parent[parent_y] = parent_x elif(rank_x < rank_y): parent[parent_x] = parent_y else: parent[parent_y] = parent_x rank[parent_x] += 1
most-stones-removed-with-same-row-or-column
Most stones removed with same row or column || Python3 || Union-Find
vanshika_2507
0
49
most stones removed with same row or column
947
0.588
Medium
15,406
https://leetcode.com/problems/bag-of-tokens/discuss/2564480/Easy-python-solution-TC%3A-O(nlogn)-SC%3A-O(1)
class Solution: def bagOfTokensScore(self, tokens: List[int], power: int) -> int: score=0 tokens.sort() i=0 j=len(tokens)-1 mx=0 while i<=j: if tokens[i]<=power: power-=tokens[i] score+=1 i+=1 mx=max(mx,score) elif score>0: score-=1 power+=tokens[j] j-=1 else: break return mx
bag-of-tokens
Easy python solution TC: O(nlogn), SC: O(1)
shubham_1307
10
820
bag of tokens
948
0.521
Medium
15,407
https://leetcode.com/problems/bag-of-tokens/discuss/2566534/Python3-Runtime%3A-55-ms-faster-than-98.92-or-Memory%3A-13.9-MB-less-than-97.17
class Solution: def bagOfTokensScore(self, tokens: List[int], power: int) -> int: tokens.sort() i,j = 0,len(tokens)-1 points = maxPoints = 0 while i<=j: if power>=tokens[i]: power-=tokens[i] points+=1 maxPoints = max(maxPoints,points) i+=1 elif points>0: points-=1 power+=tokens[j] j-=1 else: return maxPoints return maxPoints
bag-of-tokens
[Python3] Runtime: 55 ms, faster than 98.92% | Memory: 13.9 MB, less than 97.17%
anubhabishere
2
27
bag of tokens
948
0.521
Medium
15,408
https://leetcode.com/problems/bag-of-tokens/discuss/2564642/Easy-Python-Solution-oror-Two-Pointer-approach
class Solution: def bagOfTokensScore(self, tokens: List[int], power: int) -> int: tokens.sort() l,r = 0, len(tokens)-1 curr_score = 0 max_score = 0 while l <= r: if(tokens[l] <= power): power -= tokens[l] curr_score += 1 l += 1 max_score = max(max_score, curr_score) elif(curr_score > 0): power += tokens[r] curr_score -= 1 r -= 1 max_score = max(max_score, curr_score) else: break return max_score
bag-of-tokens
Easy Python Solution || Two Pointer approach
urmil_kalaria
2
36
bag of tokens
948
0.521
Medium
15,409
https://leetcode.com/problems/bag-of-tokens/discuss/2566951/Python-Two-Pointer-Solution
class Solution: def bagOfTokensScore(self, tokens: List[int], power: int) -> int: tokens.sort() l = 0 r = len(tokens)-1 ans = 0 score = 0 while l<=r: if score>=0 and power>=tokens[l]: power-=tokens[l] l+=1 score += 1 ans = max(ans,score) elif score>=1 and power<tokens[l]: power += tokens[r] score -=1 r-=1 else: return 0 return ans
bag-of-tokens
Python Two Pointer Solution
rija_1
1
20
bag of tokens
948
0.521
Medium
15,410
https://leetcode.com/problems/bag-of-tokens/discuss/2564584/python3-or-simple-and-easy-to-understand-or-explained-or-commented
class Solution: def bagOfTokensScore(self, tokens: List[int], power: int) -> int: score, ans = 0, 0 # variable initialization tokens.sort() # sorting it in non decreasing order n = len(tokens) i=0 while i<n: if power < tokens[i]: # if power is less than tokens[i] if score > 0: # score > 0 means we can face down and increase the power power += tokens[n-1] n-=1 score -= 1 # decreasing the score as used for increase in power else: i+=1 else: power -= tokens[i] # decreasing the power as it used to increase the score score += 1 # increasing the score i+=1 ans = max(ans, score) # keep track of maximum score return ans
bag-of-tokens
python3 | simple and easy to understand | explained | commented
H-R-S
1
15
bag of tokens
948
0.521
Medium
15,411
https://leetcode.com/problems/bag-of-tokens/discuss/1782184/For-Beginners-oror-Well-Explained-oror-Two-pointers
class Solution: def bagOfTokensScore(self, tokens: List[int], power: int) -> int: res = 0 nums= sorted(tokens) i,j = 0, len(nums)-1 score = 0 while i<=j: while i<=j and nums[i]<=power: score+=1 res = max(res,score) power-=nums[i] i+=1 if score==0: return res power+=nums[j] j-=1 score-=1 return res
bag-of-tokens
📌📌 For Beginners || Well-Explained || Two-pointers 🐍
abhi9Rai
1
61
bag of tokens
948
0.521
Medium
15,412
https://leetcode.com/problems/bag-of-tokens/discuss/912499/Python3-greedy-O(NlogN)
class Solution: def bagOfTokensScore(self, tokens: List[int], P: int) -> int: tokens.sort() score, lo, hi = 0, 0, len(tokens)-1 while lo <= hi: if tokens[lo] <= P: # exchange power for score P -= tokens[lo] lo += 1 score += 1 elif score and lo < hi: # exchange score for power P += tokens[hi] hi -= 1 score -= 1 else: break return score
bag-of-tokens
[Python3] greedy O(NlogN)
ye15
1
58
bag of tokens
948
0.521
Medium
15,413
https://leetcode.com/problems/bag-of-tokens/discuss/2796174/Simple-python-two-pointer-solution-using-sorting
class Solution: def bagOfTokensScore(self, tokens: List[int], power: int) -> int: score = 0 #two pointer va technique i = 0 j = len(tokens)-1 mx = 0 tokens.sort() while j>=i: if power-tokens[i]>=0: score+=1 power-=tokens[i] i+=1 mx = max(mx, score) elif score>=1: power+=tokens[j] j-=1 score-=1 else: j-=1 return mx
bag-of-tokens
Simple python two pointer solution using sorting
Rajeev_varma008
0
1
bag of tokens
948
0.521
Medium
15,414
https://leetcode.com/problems/bag-of-tokens/discuss/2774530/JavaPython3-or-Two-Pointers-%2B-Greedy
class Solution: def bagOfTokensScore(self, tokens: List[int], power: int) -> int: tokens.sort() score,ans=[0]*2 left,right=0,len(tokens)-1 while left<=right: if power>=tokens[left]: power-=tokens[left] score+=1 left+=1 elif score>0: power+=tokens[right] score-=1 right-=1 else: break ans=max(ans,score) return ans
bag-of-tokens
[Java/Python3] | Two Pointers + Greedy
swapnilsingh421
0
2
bag of tokens
948
0.521
Medium
15,415
https://leetcode.com/problems/bag-of-tokens/discuss/2684986/Python3-Solution
class Solution: def bagOfTokensScore(self, tokens: List[int], power: int) -> int: if tokens == []: return 0 tokens.sort() score = 0 # play the smallest token face up until power is about to drop below 1 while len(tokens) > 0 and power - tokens[0] > 0: lo_token = tokens.pop(0) power -= lo_token score += 1 # play the largest token face down to increase power when required if len(tokens) > 1 and power - tokens[0] <= 0: hi_token = tokens.pop() power += hi_token score -= 1 if len(tokens) > 0 and tokens[0] == power: score += 1 return score
bag-of-tokens
Python3 Solution
tawaca
0
2
bag of tokens
948
0.521
Medium
15,416
https://leetcode.com/problems/bag-of-tokens/discuss/2569208/Would-someone-optimize-my-solu-please
class Solution(object): def bagOfTokensScore(self, tokens, power): score = 0 tokens.sort() if not tokens: return 0 while len(tokens) > 1 and (power >= tokens[0] or score > 0): if score > 0: score -= 1 power += tokens.pop(-1) while power >= tokens[0]: power -= tokens.pop(0) score += 1 if len(tokens) == 0: return score if tokens[0] <= power: score += 1 return score """ :type tokens: List[int] :type power: int :rtype: int """ ```
bag-of-tokens
Would someone optimize my solu, please?
ChengyuanDAIBrian
0
3
bag of tokens
948
0.521
Medium
15,417
https://leetcode.com/problems/bag-of-tokens/discuss/2569185/Python3-oror-2-pointers-oror-faster-than-100
class Solution: def bagOfTokensScore(self, tokens: List[int], power: int) -> int: tokens.sort() score = 0 left, right = 0, len(tokens) - 1 while right >= left: if power >= tokens[left]: power -= tokens[left] score += 1 left += 1 elif score > 0 and right - left > 0: score -= 1 power += tokens[right] right -= 1 else: return score return score
bag-of-tokens
Python3 || 2 pointers || faster than 100%
Skirocer
0
3
bag of tokens
948
0.521
Medium
15,418
https://leetcode.com/problems/bag-of-tokens/discuss/2568263/python3-golang-O(N*logN-%2B-N)-sort-and-two-points-solution
class Solution: def bagOfTokensScore(self, tokens: List[int], power: int) -> int: out = cur = 0 d = deque(sorted(tokens)) while d and (d[0] <= power or cur): if d[0] <= power: power -= d.popleft() cur += 1 else: power += d.pop() cur -= 1 out = max(out, cur) return out
bag-of-tokens
[python3 / golang] O(N*logN + N) - sort and two points solution
malegkin
0
5
bag of tokens
948
0.521
Medium
15,419
https://leetcode.com/problems/bag-of-tokens/discuss/2566971/Python-Greedy-algorithm-using-two-pointers-(With-explanation)
class Solution: def bagOfTokensScore(self, tokens: List[int], power: int) -> int: # Establish score to return score = 0 # Why use Collections.deque instead of the list # as-is? One word - optimization! Deque has been # written in such a way where popping items off # the front of the list using popleft occurs in O(1) # time, while running tokens.pop(0) runs in O(n) time. # Since we care a lot about runtime, deque's # the way to go here d = deque(sorted(tokens)) while d: # Since we've sorted the list in ascending # order, we don't need to compare the power to # all values - if it's smaller than the smallest, # it'll be smaller than everything if power < d[0]: # Pop the tail of the list (play token face-down) if score > 0 and len(d) > 1: power += d.pop() score -= 1 # It's possible power will be smaller than # all scores but either our score's too low # to play anything face-down OR there's only # one piece left, making the play redundnat. # In either of these cases, we're done else: return score else: #Pop the head (play token face-up) power -= d.popleft() score += 1 # Game over - time to return our score! return score
bag-of-tokens
[Python] Greedy algorithm using two pointers (With explanation)
DyHorowitz
0
7
bag of tokens
948
0.521
Medium
15,420
https://leetcode.com/problems/bag-of-tokens/discuss/2566794/O(nlogn)-with-sorting-%2B-heuristic-(example-explaination)
class Solution: def bagOfTokensScore(self, tokens: List[int], power: int) -> int: t = sorted(tokens) print(t, power) ans = 0 flag = True while flag: print("+ ", "score:", ans, "power:", power, t) if len(t)>0 and power>=t[0]: power -= t[0] ans += 1 t.pop(0) elif ans>0 and len(t)>1: power = power + t[-1] - t[0] t.pop(-1) t.pop(0) else: flag = False print("ans:", ans) print("=" * 20) print() return ans print = lambda *a, **aa: ()
bag-of-tokens
O(nlogn) with sorting + heuristic (example explaination)
dntai
0
2
bag of tokens
948
0.521
Medium
15,421
https://leetcode.com/problems/bag-of-tokens/discuss/2566517/Runtime%3A-80-ms-faster-than-59.43-of-Python3-Memory-Usage%3A-13.9-MB-less-than-99.06-of-Python3
class Solution: def bagOfTokensScore(self, tokens: List[int], power: int) -> int: ans=0 tokens.sort() while len(tokens)!=0: if tokens[0]<=power: power-=tokens[0] ans+=1 tokens.remove(tokens[0]) else: if ans>=1 and len(tokens)>=2: power+=tokens[-1] tokens.pop() ans-=1 else: break return ans
bag-of-tokens
Runtime: 80 ms, faster than 59.43% of Python3; Memory Usage: 13.9 MB, less than 99.06% of Python3
DG-Problemsolver
0
2
bag of tokens
948
0.521
Medium
15,422
https://leetcode.com/problems/bag-of-tokens/discuss/2566372/Python-Accepted
class Solution: def bagOfTokensScore(self, tokens, power): tokens.sort() n = len(tokens) i, j = 0, n while i < j: if tokens[i] <= power: power -= tokens[i] i += 1 elif i - (n - j) and j > i + 1: j -= 1 power += tokens[j] else: break return i - (n - j)
bag-of-tokens
Python Accepted ✅
Khacker
0
3
bag of tokens
948
0.521
Medium
15,423
https://leetcode.com/problems/bag-of-tokens/discuss/2565983/Python-Greedy-two-Pointer-Solution
class Solution: def bagOfTokensScore(self, tokens: List[int], power: int) -> int: # sort the tokens by increasing size tokens.sort() if not tokens: return 0 # make two pointers, play the small one face up and the big # ones face down. left = 0 right = len(tokens)-1 score = 0 max_score = 0 while (power > 0 or score > 0) and left <= right: # if we have enough power we can play a card face up if tokens[left] <= power: # print(f'Play {tokens[left]}') power -= tokens[left] score += 1 max_score = max(score, max_score) left += 1 # if we don't have enough power we need to play a card # face down elif score > 0: # print(f'Receive {tokens[right]}') power += tokens[right] score -= 1 right -= 1 else: break return max_score
bag-of-tokens
[Python] - Greedy two Pointer Solution
Lucew
0
3
bag of tokens
948
0.521
Medium
15,424
https://leetcode.com/problems/bag-of-tokens/discuss/2565896/Python-easy-Solution-(sort-%2B-two-pointers)
class Solution: def bagOfTokensScore(self, tokens: List[int], power: int) -> int: l,r = 0,len(tokens)-1 score = 0 tokens.sort() while l<=r: if power - tokens[l]<0: # if power less than token if score == 0 or l==r: break #we can not take tokens in score is zero and we need not decrease score when l==r power += tokens[r] r-=1 score -= 1 else: # if power greater than token power -= tokens[l] score+=1 l+=1 return score
bag-of-tokens
Python easy Solution (sort + two pointers)
amlanbtp
0
7
bag of tokens
948
0.521
Medium
15,425
https://leetcode.com/problems/bag-of-tokens/discuss/2565892/simple-python-solution
class Solution: def bagOfTokensScore(self, tokens: List[int], power: int) -> int: score=0 tokens.sort() i=0 j=len(tokens)-1 mx=0 while i<=j: if tokens[i]<=power: power-=tokens[i] score+=1 i+=1 mx=max(mx,score) elif score>0: score-=1 power+=tokens[j] j-=1 else: break return mx
bag-of-tokens
simple python solution
rajukommula
0
7
bag of tokens
948
0.521
Medium
15,426
https://leetcode.com/problems/bag-of-tokens/discuss/2565773/Simple-%22python%22-Solution
class Solution: def bagOfTokensScore(self, tokens: List[int], power: int) -> int: i, j = 0, len(tokens) score = 0 tsort = sorted(tokens) while i < j: if power >= tsort[i]: power -= tsort[i] score += 1 i += 1 else: if i + 1 < j and score > 0: power += tsort[j - 1] j -= 1 score -= 1 else: break return scor
bag-of-tokens
Simple "python" Solution
anandchauhan8791
0
10
bag of tokens
948
0.521
Medium
15,427
https://leetcode.com/problems/bag-of-tokens/discuss/2565676/Python3-or-Simple-and-Easy-to-learn-or-Begginers-Friendly
class Solution: def bagOfTokensScore(self, tokens: List[int], power: int) -> int: incr = sorted(tokens) score, resScore = 0, 0 if tokens and incr[0] > power: return score visit = [False]*(len(tokens)) i = -1 while i < len(tokens)-1: i+=1 token = incr[i] if visit[i]: continue if token <= power: score += 1 power -= token visit[i] = True else: if score and False in visit: u = len(tokens) - visit[::-1].index(False) - 1 score -= 1 visit[u] = True power += incr[u] i -= 1 # print(power, score, visit) resScore = max(score, resScore) return resScore
bag-of-tokens
Python3 | Simple and Easy to learn | Begginers Friendly
VijayantShri
0
2
bag of tokens
948
0.521
Medium
15,428
https://leetcode.com/problems/bag-of-tokens/discuss/2565499/Python-or-Two-Pointer-or-Greedy-or-O(n-.-logn)
class Solution: def bagOfTokensScore(self, tokens: List[int], power: int) -> int: i, j = 0, len(tokens)-1 score, max_score = 0, 0 tokens.sort() while i <= j: if not (power >= tokens[i] or score >= 1): break if power >= tokens[i]: # face up power -= tokens[i] score += 1 max_score = max(max_score, score) i += 1 else: # face down power += tokens[j] score -= 1 j -= 1 return max_score
bag-of-tokens
Python | Two Pointer | Greedy | O(n . logn)
dos_77
0
4
bag of tokens
948
0.521
Medium
15,429
https://leetcode.com/problems/bag-of-tokens/discuss/2565275/GolangPython-O(N*log(N))-time-or-O(1)-space
class Solution: def bagOfTokensScore(self, tokens: List[int], power: int) -> int: tokens.sort() score = 0 max_score = 0 left = 0 right = len(tokens)-1 while left<=right: if tokens[left] <= power: power-=tokens[left] left+=1 score+=1 elif score: power+=tokens[right] right-=1 score-=1 else: break max_score = max(max_score,score) return max_score
bag-of-tokens
Golang/Python O(N*log(N)) time | O(1) space
vtalantsev
0
5
bag of tokens
948
0.521
Medium
15,430
https://leetcode.com/problems/bag-of-tokens/discuss/2565057/Python-Greedy-Algorithm-with-List-pop()-(13-lines)
class Solution: def bagOfTokensScore(self, tokens: List[int], power: int) -> int: ''' Try greedy algorithm: 1. Use power to take token of lowest value to convert to score 2. When power is not enough, use score to convert highest value to power 2a. But if this 'highest value' is the only value left, ie no values left to convert to score, do not convert score 3. Repeat steps 1 and 2 until every value is covered ''' tokens = sorted(tokens) score = 0 while len(tokens) > 0: if power >= tokens[0]: power -= tokens[0] score += 1 tokens.pop(0) elif len(tokens) > 1 and score > 0: power += tokens.pop() score -= 1 else: break return score
bag-of-tokens
Python Greedy Algorithm with List pop() (13 lines)
chkmcnugget
0
7
bag of tokens
948
0.521
Medium
15,431
https://leetcode.com/problems/bag-of-tokens/discuss/2564988/Python-solution-with-2-pointers
class Solution: def bagOfTokensScore(self, tokens: List[int], power: int) -> int: tokens.sort() score = 0 i = 0 j = len(tokens) - 1 while i<=j: if power>=tokens[i]: #Case 1 power -= tokens[i] score +=1 i+=1 elif score >0 and i<j: #Case 2 power += tokens[j] score -=1 j-=1 else: #Otherwise break break return score
bag-of-tokens
Python solution with 2 pointers
manojkumarmanusai
0
11
bag of tokens
948
0.521
Medium
15,432
https://leetcode.com/problems/bag-of-tokens/discuss/2564799/Two-pointers-python3-soln
class Solution: # O(n) time, # O(1) space, # Approach: two pointers, greedy, sorting def bagOfTokensScore(self, tokens: List[int], power: int) -> int: n = len(tokens) tokens.sort() l, r = 0, n curr_score = 0 max_score = curr_score while l < r: if power >= tokens[l]: curr_score +=1 power -= tokens[l] l +=1 else: r -=1 if curr_score <= 0: break curr_score -=1 power += tokens[r] max_score = max(max_score, curr_score) return max_score
bag-of-tokens
Two pointers python3 soln
destifo
0
1
bag of tokens
948
0.521
Medium
15,433
https://leetcode.com/problems/bag-of-tokens/discuss/2564789/Python-Two-Pointers
class Solution: def bagOfTokensScore(self, tokens: List[int], power: int) -> int: tokens.sort() l = 0 r = len(tokens) - 1 score = 0 while l <= r: if power >= tokens[l]: power -= tokens[l] score += 1 l += 1 elif score >= 1 and l != r: power += tokens[r] r -= 1 score -= 1 else: l += 1 return score
bag-of-tokens
Python Two Pointers
user6397p
0
2
bag of tokens
948
0.521
Medium
15,434
https://leetcode.com/problems/bag-of-tokens/discuss/2564777/Python-Solution-With-Sorting
class Solution: def bagOfTokensScore(self, tokens: List[int], power: int) -> int: n = len(tokens) if n == 0: return 0 tokens.sort() score = 0 ans = 0 l = 0 r = len(tokens)-1 while l <= r: if tokens[l]<=power: power -= tokens[l] score += 1 ans = max(ans,score) l += 1 elif score > 0: power += tokens[r] score -= 1 r -= 1 else: l += 1 return max(ans,score)
bag-of-tokens
Python Solution With Sorting
a_dityamishra
0
7
bag of tokens
948
0.521
Medium
15,435
https://leetcode.com/problems/bag-of-tokens/discuss/2564765/Python-2-pointers-approach-or-Explained-line-by-line-or-Easy-approach
class Solution: def bagOfTokensScore(self, tokens: List[int], power: int) -> int: #sort the list of tokens tokens.sort() #get the length of the list n = len(tokens) #moving pointers, i from start and j from end #not j is n (denoting outside the list) i, j = 0, n score = 0 #run a loop while i is less than j while i<j: #if the power of ith token is less than #the current power if tokens[i]<=power: #subtract the power by tokens[i] power -= tokens[i] #increment in the score by 1 score += 1 #update the pointer i += 1 #now power is less, so check if score is #greater than 0 or not elif score>0: #first update the pointer value of j j -= 1 #if j is equal to i now, break as ith #element is already taken if j==i: break #update the power power += tokens[j] #decrement the score by 1 score -= 1 #if neither the power is sufficient nor the #score, break the loop as can not move ahead else: break #return the score return score
bag-of-tokens
Python 2-pointers approach | Explained line by line | Easy approach
harshsaini6979
0
8
bag of tokens
948
0.521
Medium
15,436
https://leetcode.com/problems/bag-of-tokens/discuss/2564553/O(N-log-N)-solution
class Solution: def bagOfTokensScore(self, tokens: List[int], power: int) -> int: tokens.sort() n = len(tokens) score = 0 left = 0 right = n - 1 max_score = 0 while left <= right: if power >= tokens[left]: power -= tokens[left] score += 1 left += 1 max_score = max(max_score, score) elif score > 0: power += tokens[right] score -= 1 right -= 1 else: break return max_score
bag-of-tokens
O(N log N) solution
mansoorafzal
0
4
bag of tokens
948
0.521
Medium
15,437
https://leetcode.com/problems/bag-of-tokens/discuss/2564551/Python-greedy-two-pointers
class Solution: def bagOfTokensScore(self, tokens: List[int], power: int) -> int: # examine empty lists to avoid IndexError in the last step if not tokens: return 0 tokens.sort() up = 0 down = len(tokens) - 1 score = 0 while up < down: if power >= tokens[up]: power -= tokens[up] up += 1 score += 1 continue if power < tokens[up] and score >= 1: power += tokens[down] down -= 1 score -= 1 continue break score += 1 if tokens[up] <= power else 0 # we separate the case where up == down to avoid decreasing score to earn power where there is even no tokens available left return score
bag-of-tokens
Python greedy two-pointers
MajimaAyano
0
6
bag of tokens
948
0.521
Medium
15,438
https://leetcode.com/problems/bag-of-tokens/discuss/2564498/Python-oror-Greedy-oror-Two-Pointers-oror-TC%3A-O(n*logn)
class Solution: def bagOfTokensScore(self, tokens: List[int], power: int) -> int: if not tokens or power == 0: return 0 n = len(tokens) tokens.sort() up, down = 0, n-1 max_score = 0 if tokens[0] > power: return 0 score = 0 while up <= down: if tokens[up] <= power: power -= tokens[up] score += 1 up += 1 else: if score > 0: power += tokens[down] score -= 1 down -= 1 max_score = max(max_score,score) return max_score
bag-of-tokens
Python || Greedy || Two Pointers || TC: O(n*logn)
s_m_d_29
0
11
bag of tokens
948
0.521
Medium
15,439
https://leetcode.com/problems/bag-of-tokens/discuss/2564413/Python-Solution
class Solution: def bagOfTokensScore(self, tokens: List[int], power: int) -> int: tokens.sort() l, r = 0, len(tokens) - 1 result = 0 while l <= r: if power < tokens[l] and result > 0: power += tokens[r] if r - l > 0: result -= 1 r -= 1 elif power >= tokens[l]: power -= tokens[l] l += 1 result += 1 else: return result return result
bag-of-tokens
Python Solution
hgalytoby
0
12
bag of tokens
948
0.521
Medium
15,440
https://leetcode.com/problems/bag-of-tokens/discuss/2564248/Python-or-Two-Pointers-and-Greedy-or-Easy-to-Understand-or-With-Explanation
class Solution: def bagOfTokensScore(self, tokens: List[int], power: int) -> int: # two pointers &amp; greedy # 1. sort tokens (ascending order) # 2. if power >= tokens[left], then face it up, score + 1 # 3. if power < tokens[left], we can't earn point by face up tokens[left], then there are two situations: # (1) score > 0, we can face down tokens[right] to earn power # (2) score <= 0, just return the max_score # Note: we need to keep updating the max_score tokens.sort() left = 0 right = len(tokens) -1 score = 0 max_score = 0 while left <= right: if power >= tokens[left]: power -= tokens[left] score += 1 left += 1 max_score = max(max_score, score) elif score > 0: power += tokens[right] score -= 1 right -= 1 else: return max_score return max_score
bag-of-tokens
Python | Two Pointers & Greedy | Easy to Understand | With Explanation
Mikey98
0
19
bag of tokens
948
0.521
Medium
15,441
https://leetcode.com/problems/bag-of-tokens/discuss/2105389/python-3-oror-two-pointer-greedy-solution
class Solution: def bagOfTokensScore(self, tokens: List[int], power: int) -> int: tokens.sort() left, right = 0, len(tokens) - 1 score = maxScore = 0 while left <= right: if power >= tokens[left]: power -= tokens[left] score += 1 maxScore = max(maxScore, score) left += 1 elif score >= 1: power += tokens[right] score -= 1 right -= 1 else: break return maxScore
bag-of-tokens
python 3 || two pointer greedy solution
dereky4
0
45
bag of tokens
948
0.521
Medium
15,442
https://leetcode.com/problems/bag-of-tokens/discuss/1900275/PYTHON-SOL-oror-SORTING-oror-TWO-POINTER-oror-EXPLAINED-oror-APPROACH-EXPLAINED-oror
class Solution: def bagOfTokensScore(self, tokens: List[int], power: int) -> int: score = 0 tokens.sort() low = 0 high = len(tokens)-1 while low <= high: if tokens[low] <= power: power -= tokens[low] score += 1 low += 1 else: if low == high: return score if score == 0: return 0 score -= 1 power += tokens[high] high -= 1 return score
bag-of-tokens
PYTHON SOL || SORTING || TWO POINTER || EXPLAINED || APPROACH EXPLAINED ||
reaper_27
0
20
bag of tokens
948
0.521
Medium
15,443
https://leetcode.com/problems/bag-of-tokens/discuss/527472/Python3-simple-solution
class Solution: def bagOfTokensScore(self, tokens: List[int], P: int) -> int: tokens.sort() score = 0 while len(tokens) > 0: if P >= tokens[0]: P -= tokens[0] score += 1 tokens.pop(0) elif len(tokens) > 2 and score > 0: score -= 1 P += tokens[-1] tokens.pop() else: break return score
bag-of-tokens
Python3 simple solution
tjucoder
0
53
bag of tokens
948
0.521
Medium
15,444
https://leetcode.com/problems/largest-time-for-given-digits/discuss/406661/Python3-6-line-via-permutation
class Solution: def largestTimeFromDigits(self, A: List[int]) -> str: hh = mm = -1 for x in set(permutations(A, 4)): h = 10*x[0] + x[1] m = 10*x[2] + x[3] if h < 24 and m < 60 and 60*h + m > 60*hh + mm: hh, mm = h, m return f"{hh:02}:{mm:02}" if hh >= 0 else ""
largest-time-for-given-digits
[Python3] 6-line via permutation
ye15
2
124
largest time for given digits
949
0.352
Medium
15,445
https://leetcode.com/problems/largest-time-for-given-digits/discuss/406661/Python3-6-line-via-permutation
class Solution: def largestTimeFromDigits(self, A: List[int]) -> str: def permutations(i=0): """Return all permutations via generator.""" if i == len(A): yield A for ii in range(i, len(A)): A[i], A[ii] = A[ii], A[i] yield from permutations(i+1) A[i], A[ii] = A[ii], A[i] hh = mm = -1 for x in permutations(): h = 10*x[0] + x[1] m = 10*x[2] + x[3] if h < 24 and m < 60 and 60*hh + mm < 60*h + m: hh, mm = h, m return f"{hh:02}:{mm:02}" if hh >= 0 else ""
largest-time-for-given-digits
[Python3] 6-line via permutation
ye15
2
124
largest time for given digits
949
0.352
Medium
15,446
https://leetcode.com/problems/largest-time-for-given-digits/discuss/406661/Python3-6-line-via-permutation
class Solution: def largestTimeFromDigits(self, arr: List[int]) -> str: def fn(i): """Return unique permutations of arr.""" if i == 4: yield arr else: seen = set() for ii in range(i, 4): if arr[ii] not in seen: seen.add(arr[ii]) arr[i], arr[ii] = arr[ii], arr[i] yield from fn(i+1) arr[i], arr[ii] = arr[ii], arr[i] hh = mm = -1 for x in fn(0): h = 10*x[0] + x[1] m = 10*x[2] + x[3] if h < 24 and m < 60: hh, mm = max((hh, mm), (h, m)) return f"{hh:02}:{mm:02}" if hh > -1 else ""
largest-time-for-given-digits
[Python3] 6-line via permutation
ye15
2
124
largest time for given digits
949
0.352
Medium
15,447
https://leetcode.com/problems/largest-time-for-given-digits/discuss/1964297/Python-easy-to-read-and-understand-or-permutations
class Solution: def valid(self, time): if time[0] > 2 or time[0] < 0: return False if time[0] == 2 and time[1] > 3: return False if time[2] > 5 or time[0] < 0: return False return True def solve(self, arr): if len(arr) == 1: return [arr] res = [] for i in range(len(arr)): val = arr[i] rem = self.solve(arr[:i]+arr[i+1:]) for j in range(len(rem)): temp = [val]+rem[j] if len(temp) == 4: if self.valid(temp): res.append([val]+rem[j]) else: res.append([val]+rem[j]) return res def largestTimeFromDigits(self, arr: List[int]) -> str: res = self.solve(arr) if not res: return "" res.sort() ans = res.pop() ans = [str(i) for i in ans] ans.insert(2, ":") return "".join(ans)
largest-time-for-given-digits
Python easy to read and understand | permutations
sanial2001
0
105
largest time for given digits
949
0.352
Medium
15,448
https://leetcode.com/problems/largest-time-for-given-digits/discuss/1900402/PYTHON-SOL-oror-ITERTOOLS.PERMUTATIONS-%2B-CASE-CHECKING-oror-EASY-oror
class Solution: def largestTimeFromDigits(self, arr: List[int]) -> str: def check(num): if num[0] > 2 : return False if num[0] == 2 and num[1] > 3: return False if num[2] > 5 : return False return True p = itertools.permutations(arr) ans = None for i in p: if check(i) == True: if ans == None or i > ans: ans = i if ans == None:return "" return str(ans[0])+str(ans[1])+':'+str(ans[2])+str(ans[3])
largest-time-for-given-digits
PYTHON SOL || ITERTOOLS.PERMUTATIONS + CASE CHECKING || EASY ||
reaper_27
0
48
largest time for given digits
949
0.352
Medium
15,449
https://leetcode.com/problems/largest-time-for-given-digits/discuss/1258473/Simple-python-solution-without-using-inbuilt-lib
class Solution: def largestTimeFromDigits(self, arr: List[int]) -> str: if min(arr)>3: return "" arr.sort() for h in range(23,-1,-1): for m in range(59,-1,-1): t=[h//10,h%10,m//10,m%10] ts=sorted(t) if ts==arr: return str(t[0])+str(t[1])+":"+str(t[2])+str(t[3]) return ""
largest-time-for-given-digits
Simple python solution without using inbuilt lib
jaipoo
0
135
largest time for given digits
949
0.352
Medium
15,450
https://leetcode.com/problems/largest-time-for-given-digits/discuss/1040289/python3-permutations-python3-O(4!)
class Solution: def largestTimeFromDigits(self, arr: List[int]) -> str: mx=() for x in itertools.permutations(arr): if( x[:2]<(2,4) and x[2]<6 ): mx=max(mx,x) if(mx==()): return "" else: s="" for i,x in enumerate(mx): if(i==2): s+=":" s+=str(x) return s
largest-time-for-given-digits
python3 permutations python3 O(4!)
_Rehan12
0
67
largest time for given digits
949
0.352
Medium
15,451
https://leetcode.com/problems/largest-time-for-given-digits/discuss/580812/Intuitive-but-cumbersome-solution
class Solution: def largestTimeFromDigits(self, A: List[int]) -> str: def get_new_a_without_n(A, n): a = [] a.extend(A) a.remove(n) return a def build_time(result, digit=0, rest_numbers=A): if len(result) == 4: return result else: if digit == 0: # First digit between 2-0 for n in range(2, -1, -1): if n in rest_numbers: a = get_new_a_without_n(rest_numbers, n) result.append(n) if build_time(result, 1, a): return result del result[-1] elif digit == 1: # Second digit: # If first digit is 2, then between 3-0 # Else between 9-0 if result[-1] == 2: nrange = range(3, -1, -1) else: nrange = range(9, -1, -1) for n in nrange: if n in rest_numbers: a = get_new_a_without_n(rest_numbers, n) result.append(n) if build_time(result, 2, a): return result del result[-1] elif digit == 2: # Third digit between 5-0 for n in range(5, -1, -1): if n in rest_numbers: a = get_new_a_without_n(rest_numbers, n) result.append(n) if build_time(result, 3, a): return result del result[-1] else: # The last digit between 9-0 if rest_numbers[0] < 10: result.append(rest_numbers[0]) return result return None result = [] build_time(result) if result: return "{}{}:{}{}".format(result[0], result[1], result[2], result[3]) else: return ""
largest-time-for-given-digits
Intuitive but cumbersome solution
puremonkey2001
0
79
largest time for given digits
949
0.352
Medium
15,452
https://leetcode.com/problems/largest-time-for-given-digits/discuss/460162/Python3-simple-solution-using-a-for()-loop
class Solution: def largestTimeFromDigits(self, A: List[int]) -> str: A.sort() if A[0] >= 3 or A[1]>=6: return "" for p in itertools.permutations(A[::-1]): if (p[0] * 10 + p[1]) < 24 and (p[2]*10 + p[3]) < 60: return str(p[0])+str(p[1])+":"+str(p[2])+str(p[3]) return ""
largest-time-for-given-digits
Python3 simple solution using a for() loop
jb07
0
177
largest time for given digits
949
0.352
Medium
15,453
https://leetcode.com/problems/largest-time-for-given-digits/discuss/476502/python-3.8-crazy-one-liner-with-assignment-expression-beats-80%2B-(permutations)
class Solution: def largestTimeFromDigits(self, A: List[int]) -> str: return ''.join(result[-1]) if (result := sorted([[*p[:2]]+[':']+[*p[2:]] for p in itertools.permutations([str(n) for n in A]) if int(''.join(p[:2])) < 24 and int(''.join(p[2:])) < 60], key=lambda p: int(''.join(p[:2]))*100 + int(''.join(p[3:])))) else ""
largest-time-for-given-digits
python 3.8 crazy one-liner with assignment expression beats 80%+ (permutations)
oskomorokhov
-2
194
largest time for given digits
949
0.352
Medium
15,454
https://leetcode.com/problems/reveal-cards-in-increasing-order/discuss/394028/Solution-in-Python-3-(Deque)-(three-lines)
class Solution: def deckRevealedIncreasing(self, D: List[int]) -> List[int]: L, Q, _ = len(D)-1, collections.deque(), D.sort() for _ in range(L): Q.appendleft(D.pop()), Q.appendleft(Q.pop()) return D + list(Q) - Junaid Mansuri (LeetCode ID)@hotmail.com
reveal-cards-in-increasing-order
Solution in Python 3 (Deque) (three lines)
junaidmansuri
5
803
reveal cards in increasing order
950
0.778
Medium
15,455
https://leetcode.com/problems/reveal-cards-in-increasing-order/discuss/2770735/Simple-Approach
class Solution: def deckRevealedIncreasing(self, deck: List[int]) -> List[int]: def reveal(n): lst = list(range(n)) ans = [] i = 0 while lst: if not i&amp;1: ans.append(lst.pop(0)) else: lst.append(lst.pop(0)) i += 1 return ans ans = reveal(len(deck)) ans = sorted([v, i] for i, v in enumerate(ans)) deck.sort() return (deck[j] for i,j in ans)
reveal-cards-in-increasing-order
Simple Approach
Mencibi
1
38
reveal cards in increasing order
950
0.778
Medium
15,456
https://leetcode.com/problems/reveal-cards-in-increasing-order/discuss/2418597/Python-Using-Deque-O(n)-time-complexity
class Solution: def deckRevealedIncreasing(self, deck: List[int]) -> List[int]: d=deque(sorted(deck)) res = deque() l = len(d) while l != len(res): t = d.pop() if len(res)>0: r = res.pop() res.appendleft(r) res.appendleft(t) return res
reveal-cards-in-increasing-order
Python, Using Deque, O(n) time complexity
Nish786
1
74
reveal cards in increasing order
950
0.778
Medium
15,457
https://leetcode.com/problems/reveal-cards-in-increasing-order/discuss/2670766/Python-easy-solution
class Solution: def deckRevealedIncreasing(self, deck: List[int]) -> List[int]: d = sorted(deck, reverse=1) res = [d[0]] d.pop(0) while(d): # 1. move the bottom to the top btn = res.pop(-1) res.insert(0, btn) # 2. add a card to the top card = d.pop(0) res.insert(0, card) return res
reveal-cards-in-increasing-order
Python easy solution
Jack_Chang
0
7
reveal cards in increasing order
950
0.778
Medium
15,458
https://leetcode.com/problems/reveal-cards-in-increasing-order/discuss/1733792/Simple-Queue-solution-using-a-deque-object-or-Python3-or-36ms-beats-98-timeor-beats-96.86-space
class Solution: def deckRevealedIncreasing(self, deck: List[int]) -> List[int]: deck.sort() # You can sort in ascending or descending if you are using for loop but if using pop() method, only sort in ascending. q = deque([deck[-1]]) # Initialised deque object with the max deck value. # Remember you can always just use pop() function on the deck list. I just chose not to. for i in range(len(deck)-2 ,-1 ,-1): # Use while deck here if you are going for the pop() approach q.appendleft(q.pop()) # Bringing the last element in the queue to the front q.appendleft(deck[i]) # Adding the next largest element from deck to the front of our queue return list(q) # You can just return q, it would still be correct.
reveal-cards-in-increasing-order
Simple Queue solution using a deque object | Python3 | 36ms beats 98% time| beats 96.86% space
nandhakiran366
0
48
reveal cards in increasing order
950
0.778
Medium
15,459
https://leetcode.com/problems/reveal-cards-in-increasing-order/discuss/974921/Python3-simulation-via-a-deque-O(NlogN)
class Solution: def deckRevealedIncreasing(self, deck: List[int]) -> List[int]: ans = [0]*len(deck) idx = deque(range(len(deck))) for x in sorted(deck): ans[idx.popleft()] = x if idx: idx.append(idx.popleft()) return ans
reveal-cards-in-increasing-order
[Python3] simulation via a deque O(NlogN)
ye15
0
111
reveal cards in increasing order
950
0.778
Medium
15,460
https://leetcode.com/problems/flip-equivalent-binary-trees/discuss/1985423/Python-oror-4-line-93
class Solution: def flipEquiv(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool: if not root1 or not root2: return not root1 and not root2 if root1.val != root2.val: return False return (self.flipEquiv(root1.left, root2.left) and self.flipEquiv(root1.right, root2.right)) or (self.flipEquiv(root1.left, root2.right) and self.flipEquiv(root1.right, root2.left))
flip-equivalent-binary-trees
Python || 4-line 93%
gulugulugulugulu
2
69
flip equivalent binary trees
951
0.668
Medium
15,461
https://leetcode.com/problems/flip-equivalent-binary-trees/discuss/1467671/Python-Clean-Iterative-and-Recursive-DFS
class Solution: def flipEquiv(self, root1: TreeNode, root2: TreeNode) -> bool: queue = deque([(root1, root2)]) while queue: node1, node2 = queue.pop() if (not node1) and (not node2): continue elif (not node1) or (not node2) or (node1.val != node2.val): return False L1, R1, L2, R2 = node1.left, node1.right, node2.left, node2.right if (L1 and L2 and L1.val == L2.val) or (R1 and R2 and R1.val == R2.val): queue.append((L1, L2)) queue.append((R1, R2)) else: queue.append((L1, R2)) queue.append((L2, R1)) return True
flip-equivalent-binary-trees
[Python] Clean Iterative & Recursive DFS
soma28
1
149
flip equivalent binary trees
951
0.668
Medium
15,462
https://leetcode.com/problems/flip-equivalent-binary-trees/discuss/1467671/Python-Clean-Iterative-and-Recursive-DFS
class Solution: def flipEquiv(self, root1: TreeNode, root2: TreeNode) -> bool: def dfs(node1 = root1, node2 = root2): if (not node1) and (not node2): return True elif (not node1) or (not node2) or (node1.val != node2.val): return False L1, R1, L2, R2 = node1.left, node1.right, node2.left, node2.right if (L1 and L2 and L1.val == L2.val) or (R1 and R2 and R1.val == R2.val): return dfs(L1, L2) and dfs(R1, R2) else: return dfs(L1, R2) and dfs(L2, R1) return dfs()
flip-equivalent-binary-trees
[Python] Clean Iterative & Recursive DFS
soma28
1
149
flip equivalent binary trees
951
0.668
Medium
15,463
https://leetcode.com/problems/flip-equivalent-binary-trees/discuss/459663/Python-3-clean-version
class Solution: def flipEquiv(self, root1: TreeNode, root2: TreeNode) -> bool: if not root1: return root2 is None if not root2: return False return root1.val == root2.val \ and (self.flipEquiv(root1.left, root2.left) \ and self.flipEquiv(root1.right, root2.right) \ or self.flipEquiv(root1.right, root2.left) \ and self.flipEquiv(root1.left, root2.right))
flip-equivalent-binary-trees
Python 3 clean version
Christian_dudu
1
64
flip equivalent binary trees
951
0.668
Medium
15,464
https://leetcode.com/problems/flip-equivalent-binary-trees/discuss/2707332/Python-one-liner
class Solution: def flipEquiv(self, r1: Optional[TreeNode], r2: Optional[TreeNode]) -> bool: return not r1 and not r2 if not r1 or not r2 else (self.flipEquiv(r1.right, r2.right) and self.flipEquiv(r1.left, r2.left)) or (self.flipEquiv(r1.left, r2.right) and self.flipEquiv(r1.right, r2.left)) if r1.val == r2.val else False
flip-equivalent-binary-trees
Python one-liner
scrptgeek
0
4
flip equivalent binary trees
951
0.668
Medium
15,465
https://leetcode.com/problems/flip-equivalent-binary-trees/discuss/2462213/Python-beats-85-oror-simple
class Solution: def flipEquiv(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool: if not root1 and not root2: return True if not (root1 and root2): return False if root1.val != root2.val: return False regular = self.flipEquiv(root1.left,root2.left) and self.flipEquiv(root1.right,root2.right) flipped = self.flipEquiv(root1.left,root2.right) and self.flipEquiv(root1.right,root2.left) return regular or flipped
flip-equivalent-binary-trees
Python beats 85% || simple
aruj900
0
15
flip equivalent binary trees
951
0.668
Medium
15,466
https://leetcode.com/problems/flip-equivalent-binary-trees/discuss/2120995/python-3-oror-simple-recursive-solution
class Solution: def flipEquiv(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool: def swap(root): if root.right is None or (root.left is not None and root.left.val > root.right.val): root.left, root.right = root.right, root.left def equal(root1, root2): if root1 is None or root2 is None: return root1 is None and root2 is None swap(root1) swap(root2) return (root1.val == root2.val and equal(root1.left, root2.left) and equal(root1.right, root2.right)) return equal(root1, root2)
flip-equivalent-binary-trees
python 3 || simple recursive solution
dereky4
0
43
flip equivalent binary trees
951
0.668
Medium
15,467
https://leetcode.com/problems/flip-equivalent-binary-trees/discuss/975006/Python3-recursive
class Solution: def flipEquiv(self, root1: TreeNode, root2: TreeNode) -> bool: if not root1 or not root2: return root1 is root2 return root1.val == root2.val and (self.flipEquiv(root1.left, root2.left) and self.flipEquiv(root1.right, root2.right) or self.flipEquiv(root1.left, root2.right) and self.flipEquiv(root1.right, root2.left))
flip-equivalent-binary-trees
[Python3] recursive
ye15
0
30
flip equivalent binary trees
951
0.668
Medium
15,468
https://leetcode.com/problems/flip-equivalent-binary-trees/discuss/975006/Python3-recursive
class Solution: def flipEquiv(self, root1: TreeNode, root2: TreeNode) -> bool: def fn(n1, n2): """Return True if n1 is a flip of n2.""" if not n1 or not n2: return n1 is n2 return n1.val == n2.val and (fn(n1.left, n2.right) and fn(n1.right, n2.left) or fn(n1.left, n2.left) and fn(n1.right, n2.right)) return fn(root1, root2)
flip-equivalent-binary-trees
[Python3] recursive
ye15
0
30
flip equivalent binary trees
951
0.668
Medium
15,469
https://leetcode.com/problems/largest-component-size-by-common-factor/discuss/1546345/Python3-union-find
class Solution: def largestComponentSize(self, nums: List[int]) -> int: m = max(nums) uf = UnionFind(m+1) for x in nums: for p in range(2, int(sqrt(x))+1): if x%p == 0: uf.union(x, p) uf.union(x, x//p) freq = Counter(uf.find(x) for x in nums) return max(freq.values())
largest-component-size-by-common-factor
[Python3] union-find
ye15
4
259
largest component size by common factor
952
0.404
Hard
15,470
https://leetcode.com/problems/largest-component-size-by-common-factor/discuss/1546345/Python3-union-find
class Solution: def largestComponentSize(self, nums: List[int]) -> int: m = max(nums) spf = list(range(m+1)) for x in range(4, m+1, 2): spf[x] = 2 for x in range(3, int(sqrt(m+1))+1): if spf[x] == x: for xx in range(x*x, m+1, x): spf[xx] = x uf = UnionFind(len(nums)) mp = {} for i, x in enumerate(nums): while x > 1: if spf[x] in mp: uf.union(i, mp[spf[x]]) else: mp[spf[x]] = i x //= spf[x] return max(uf.rank)
largest-component-size-by-common-factor
[Python3] union-find
ye15
4
259
largest component size by common factor
952
0.404
Hard
15,471
https://leetcode.com/problems/largest-component-size-by-common-factor/discuss/1905677/PYTHON-SOL-oror-UNION-FIND-oror-EXPLAINED-oror
class Solution: def largestComponentSize(self, nums: List[int]) -> int: def find(node): if parent[node] == -1: return node else: parent[node] = find(parent[node]) return parent[node] def union(idx1,idx2): par1,par2 = find(idx1),find(idx2) if par1!=par2: if rank[par1] > rank[par2]: parent[par2] = par1 elif rank[par2] > rank[par1]: parent[par1] = par2 else: parent[par2] = par1 rank[par1] += 1 n = len(nums) parent = defaultdict(lambda:-1) rank = defaultdict(lambda:0) for i in range(n): limit = int(nums[i]**0.5) for j in range(2,limit+1): if nums[i] % j == 0: union(nums[i],j) union(nums[i],nums[i]//j) count = defaultdict(lambda:0) best = -1 for num in nums: par = find(num) tmp = count[par] + 1 if tmp > best: best = tmp count[par] = tmp return best
largest-component-size-by-common-factor
PYTHON SOL || UNION FIND || EXPLAINED ||
reaper_27
0
65
largest component size by common factor
952
0.404
Hard
15,472
https://leetcode.com/problems/verifying-an-alien-dictionary/discuss/1370816/Python3-fast-and-easy-to-understand-28-ms-faster-than-96.25
class Solution: def isAlienSorted(self, words: List[str], order: str) -> bool: hm = {ch: i for i, ch in enumerate(order)} prev_repr = list(hm[ch] for ch in words[0]) for i in range(1, len(words)): cur_repr = list(hm[ch] for ch in words[i]) if cur_repr < prev_repr: return False prev_repr = cur_repr return True
verifying-an-alien-dictionary
Python3, fast and easy to understand, 28 ms, faster than 96.25%
MihailP
5
364
verifying an alien dictionary
953
0.527
Easy
15,473
https://leetcode.com/problems/verifying-an-alien-dictionary/discuss/1206464/Python3-simple-solution-using-dictionary
class Solution: def isAlienSorted(self, words: List[str], order: str) -> bool: l1 = {c:i for i,c in enumerate(order)} l2 = [[l1[i] for i in word] for word in words] return l2 == sorted(l2)
verifying-an-alien-dictionary
Python3 simple solution using dictionary
EklavyaJoshi
5
153
verifying an alien dictionary
953
0.527
Easy
15,474
https://leetcode.com/problems/verifying-an-alien-dictionary/discuss/2168022/Python-Simple-Solution
class Solution: def isAlienSorted(self, words: List[str], order: str) -> bool: orderIndex={c : i for i,c in enumerate(order)} #c =key, i=value (orderIndex = h:1, l:2,a:3..etc) for i in range(len(words)-1): w1,w2=words[i], words[i+1] for j in range(len(w1)): if j==len(w2): return False if w1[j]!=w2[j]: if orderIndex[w2[j]]<orderIndex[w1[j]]: return False break return True
verifying-an-alien-dictionary
Python Simple Solution
pruthashouche
2
191
verifying an alien dictionary
953
0.527
Easy
15,475
https://leetcode.com/problems/verifying-an-alien-dictionary/discuss/1566100/Simple-Python-solution
class Solution: def isAlienSorted(self, words: List[str], order: str) -> bool: myOrder={k:v for v,k in enumerate(order)} for word1,word2 in zip(words,words[1:]): p1,p2=0,0 equalFlag=1 #flip to 0 when the 2 diff letters are found while p1<len(word1) and p2<len(word2): if word1[p1]==word2[p2]: p1+=1 p2+=1 elif myOrder[word2[p2]]<myOrder[word1[p1]]: return False elif myOrder[word2[p2]]>myOrder[word1[p1]]: equalFlag=0 break if equalFlag and len(word1)>len(word2): #for cases like {apple,app} return False return True
verifying-an-alien-dictionary
Simple Python 🐍 solution
InjySarhan
2
202
verifying an alien dictionary
953
0.527
Easy
15,476
https://leetcode.com/problems/verifying-an-alien-dictionary/discuss/2089378/Python-One-Linear
class Solution: def isAlienSorted(self, words: List[str], order: str) -> bool: return sorted(words, key=lambda word: [order.index(c) for c in word]) == words
verifying-an-alien-dictionary
Python One Linear
pe-mn
1
67
verifying an alien dictionary
953
0.527
Easy
15,477
https://leetcode.com/problems/verifying-an-alien-dictionary/discuss/466660/Python3-three-liner-beats-89.25
class Solution: def isAlienSorted(self, words: List[str], order: str) -> bool: index = {c: i for i, c in enumerate(order)} indexWords = [[index[x] for x in word] for word in words] return indexWords == sorted(indexWords)
verifying-an-alien-dictionary
Python3 three-liner, beats 89.25%
hugedog
1
88
verifying an alien dictionary
953
0.527
Easy
15,478
https://leetcode.com/problems/verifying-an-alien-dictionary/discuss/2847637/Python-oror-93-Faster-oror-99-Less-Memory-oror-Dictonary-Solution
class Solution: def isAlienSorted(self, words: List[str], order: str) -> bool: d = {} for i,j in enumerate(order): d[j] = i for i in range(len(words)-1): for j in range(len(words[i])): if words[i]==words[i+1]: break if j<len(words[i]) and j<len(words[i+1]): if d[words[i][j]]>d[words[i+1][j]]: return False elif d[words[i][j]]<d[words[i+1][j]]: break else: pass elif j<=len(words[i]) and j>=len(words[i+1]): return False return True
verifying-an-alien-dictionary
Python || 93% Faster || 99% Less Memory || Dictonary Solution
Vedant_3907
0
1
verifying an alien dictionary
953
0.527
Easy
15,479
https://leetcode.com/problems/verifying-an-alien-dictionary/discuss/2740016/Solution-using-enumerate-and-indexing
class Solution: def isAlienSorted(self, words: List[str], order: str) -> bool: # put the order into a hash map: key = character, index = value orderInd = {c:i for i, c in enumerate(order)} # make sure words are lower case: words = [word.lower() for word in words] # loop through index minus 1: to compare every pair of words: for i in range(len(words)-1): # set w1 to index 0 of words and w2 to index 1 of words: w1, w2 = words[i], words[i+1] # for the characters in the length of w1: for j in range(len(w1)): # if the characters length in w1 == character length in w2: return false if j == len(w2): # return False: return False # elif the characters don't match: then check if sorted in correct order elif w1[j] != w2[j]: # then check the value based on w2[j] and w1[j] as your keys in the orderInd dictionary: if orderInd[w2[j]] < orderInd[w1[j]]: return False # break from loop: break # return True: return True
verifying-an-alien-dictionary
Solution using enumerate and indexing
NavarroKU
0
6
verifying an alien dictionary
953
0.527
Easy
15,480
https://leetcode.com/problems/verifying-an-alien-dictionary/discuss/2736635/Intuitive-and-Easy-Python-Solution
class Solution: def isAlienSorted(self, words: List[str], order: str) -> bool: def compare(w1, w2): for i in range(min(len(w1), len(w2))): if order.find(w2[i]) == order.find(w1[i]): continue elif order.find(w1[i]) < order.find(w2[i]): return True else: return False return len(w1) <= len(w2) for i in range(len(words) - 1): if not compare(words[i], words[i + 1]): return False return True
verifying-an-alien-dictionary
Intuitive and Easy Python Solution
g_aswin
0
8
verifying an alien dictionary
953
0.527
Easy
15,481
https://leetcode.com/problems/verifying-an-alien-dictionary/discuss/2702467/python-solution-using-hashmap
class Solution: def isAlienSorted(self, words: List[str], order: str) -> bool: hashmap = {} for i in range(len(order)): hashmap[order[i]] = i for i in range(len(words)-1): for j in range(len(words[i])): if j >= len(words[i+1]): return False if words[i][j] != words[i+1][j]: if hashmap[words[i][j]] > hashmap[words[i+1][j]]: return False else: break return True
verifying-an-alien-dictionary
python solution using hashmap
ilikeelephant
0
4
verifying an alien dictionary
953
0.527
Easy
15,482
https://leetcode.com/problems/verifying-an-alien-dictionary/discuss/2698279/Python-Solution-using-hashmap
class Solution: def isAlienSorted(self, words: List[str], order: str) -> bool: index = {c:i for i, c in enumerate(order)} for i in range(len(words)-1): w1,w2 = words[i],words[i+1] for j in range(len(w1)): if j==len(w2): return False if w1[j]!=w2[j]: if index[w2[j]]<index[w1[j]]: return False break return True
verifying-an-alien-dictionary
Python Solution using hashmap
Navaneeth7
0
3
verifying an alien dictionary
953
0.527
Easy
15,483
https://leetcode.com/problems/verifying-an-alien-dictionary/discuss/2643197/python3-oror-easy-oror-solution
class Solution: def isAlienSorted(self, words: List[str], order: str) -> bool: hashMap={} for i in range(len(order)): hashMap[order[i]]=i def helper(first,second): x=0 y=0 while x<len(first) and y<len(second): if hashMap[first[x]]<hashMap[second[y]]: return True if hashMap[first[x]]>hashMap[second[y]]: return False x+=1 y+=1 if x<len(first): return False for i in range(len(words)-1): first=words[i] second=words[i+1] if helper(first,second)==False: return False return True
verifying-an-alien-dictionary
python3 || easy || solution
_soninirav
0
7
verifying an alien dictionary
953
0.527
Easy
15,484
https://leetcode.com/problems/verifying-an-alien-dictionary/discuss/2526849/Python3-two-solutions
class Solution(object): def isAlienSorted(self, words, order): """ :type words: List[str] :type order: str :rtype: bool """ def is_in_order(word_A, word_B): for i in range(min(len(word_A), len(word_B))): if hashmap[word_A[i]] < hashmap[word_B[i]]: return True elif hashmap[word_A[i]] > hashmap[word_B[i]]: return False if len(word_A) > len(word_B): return False return True hashmap = {} for i in range(len(order)): # Time Complexity O(N=26), or O(1) hashmap[order[i]] = i for i in range(len(words)-1): # Time Complexity O(M), M = the total number of characters across all words if not is_in_order(words[i], words[i+1]): return False return True
verifying-an-alien-dictionary
Python3 two solutions
NinjaBlack
0
54
verifying an alien dictionary
953
0.527
Easy
15,485
https://leetcode.com/problems/verifying-an-alien-dictionary/discuss/2526849/Python3-two-solutions
class Solution(object): def isAlienSorted(self, words, order): """ :type words: List[str] :type order: str :rtype: bool """ dic = {} new_words = [] for i, ch in enumerate(order): # Time Complexity O(N=26), or O(1) dic[ch] = i for w in words: # Time Complexity O(M), M = the total number of characters across all words new = [] for c in w: new.append(dic[c]) new_words.append(new) for w1, w2 in zip(new_words, new_words[1:]): # Time Complexity O(M), M = the total number of characters across all words if w1 > w2: return False return True
verifying-an-alien-dictionary
Python3 two solutions
NinjaBlack
0
54
verifying an alien dictionary
953
0.527
Easy
15,486
https://leetcode.com/problems/verifying-an-alien-dictionary/discuss/2412807/Python3-Compare-chars-with-explanation
class Solution: def isAlienSorted(self, words: List[str], order: str) -> bool: char_iter = 0 # The algorithm uses an iterable, char_iter, to check each word at the same character position. # Given a position, char_iter, it checks that character in each word # When it detects that two words have different characters in the char_iter position: # - If the prior word's character comes first in the lexicon, the two words are different but in order # Therefore, remove it from the list, as it is no longer needed # - If the character is later in the lexicon, the words are different but out of order # Therefore, break and return false # When reaching the end of a word, if it is not first in the list it is out of order - return false # If it is first in the list, it is in order and no longer needs to be checked - pop it # When only one word is left in the list, it is true that the original list was in order while len(words) > 1: for w in words: # Reached the end of the word. If first in list, remove it. If not, order is broken (by blank char) if char_iter == len(w): if words.index(w) != 0: return False else: words.pop(0) continue # Two chars in the same position are different. If in order, remove the word. If not, order broken curr_letter = words[0][char_iter] if w[char_iter] != curr_letter: if order.index(curr_letter) > order.index(w[char_iter]): return False else: words.pop(words.index(w)) char_iter += 1 return True
verifying-an-alien-dictionary
[Python3] Compare chars - with explanation
connorthecrowe
0
56
verifying an alien dictionary
953
0.527
Easy
15,487
https://leetcode.com/problems/verifying-an-alien-dictionary/discuss/2200196/Python-Simple-Python-Solution-Using-HashMap-or-Dictionary
class Solution: def isAlienSorted(self, words: List[str], order: str) -> bool: store_index = {} for index in range(len(order)): store_index[order[index]] = index for i in range(len(words)-1): for j in range(len(words[i])): if j >= len(words[i+1]): return False elif words[i][j] != words[i+1][j]: if store_index[words[i][j]] > store_index[words[i+1][j]]: return False else: break return True
verifying-an-alien-dictionary
[ Python ] ✅✅ Simple Python Solution Using HashMap or Dictionary🥳✌👍
ASHOK_KUMAR_MEGHVANSHI
0
99
verifying an alien dictionary
953
0.527
Easy
15,488
https://leetcode.com/problems/verifying-an-alien-dictionary/discuss/2131219/Beginner-Friendly-solution-(python-with-detailed-explaination)
class Solution: def isAlienSorted(self, words: List[str], order: str) -> bool: hashMap = dict(zip(order,string.ascii_lowercase)) temp = '' res = [] for word in words: for ch in word: temp+=hashMap[ch] if len(temp) == len(word): res.append(temp) temp = '' return res ==sorted(res) ```
verifying-an-alien-dictionary
Beginner Friendly solution (python with detailed explaination)
Lexcapital
0
35
verifying an alien dictionary
953
0.527
Easy
15,489
https://leetcode.com/problems/verifying-an-alien-dictionary/discuss/2075950/python
class Solution: def isAlienSorted(self, words: List[str], order: str) -> bool: if len(words) == 1: return True alien_dict = {} for i in range(len(order)): alien_dict[order[i]] = i for i in range(len(words)-1): for j in range(i , len(words)-1): if words[j] == words[j+1]: continue l1 = len(words[j]) l2 = len(words[j+1]) index = min(l1 , l2) for k in range(index): if alien_dict[words[j][k]] > alien_dict[words[j+1][k]]: return False elif alien_dict[words[j][k]] < alien_dict[words[j+1][k]]: break elif k >= (index-1) and l2 < l1: return False return True
verifying-an-alien-dictionary
python
akashp2001
0
61
verifying an alien dictionary
953
0.527
Easy
15,490
https://leetcode.com/problems/verifying-an-alien-dictionary/discuss/1981590/Python-clean-solution-with-helper-methods
class Solution: def translation_alphabet(self, order: str) -> dict[str, str]: a = ord('a') alphabet = {} for idx, c in enumerate(order): alphabet[c] = chr(a + idx) return alphabet def translate(self, word: str, alphabet: dict[str, str]) -> str: new_word = [] for c in word: new_word.append(alphabet[c]) return "".join(new_word) def is_sorted(self, words: List[str]) -> bool: for idx in range(len(words) - 1): if words[idx] > words[idx + 1]: return False return True def isAlienSorted(self, words: List[str], order: str) -> bool: alphabet = self.translation_alphabet(order) for idx, word in enumerate(words): words[idx] = self.translate(word, alphabet) return self.is_sorted(words)
verifying-an-alien-dictionary
Python clean solution with helper methods
user3694B
0
58
verifying an alien dictionary
953
0.527
Easy
15,491
https://leetcode.com/problems/verifying-an-alien-dictionary/discuss/1905633/Python-Clean-and-Simple!
class Solution: def isAlienSorted(self, words, order): d = {c:i for i,c in enumerate(order)} words = list(map(lambda w:list(map(lambda c:d[c],w)),words)) return all(words[i] >= words[i-1] for i in range(1,len(words)))
verifying-an-alien-dictionary
Python - Clean and Simple!
domthedeveloper
0
102
verifying an alien dictionary
953
0.527
Easy
15,492
https://leetcode.com/problems/verifying-an-alien-dictionary/discuss/1890449/python3-solution
class Solution: def isAlienSorted(self, words: List[str], order: str) -> bool: order_dict = { y: x for x, y in enumerate(order) } def cmp_func(a, b): for i, j in itertools.zip_longest(a, b, fillvalue="_"): if order_dict.get(i, -1) < order_dict.get(j, -1): return True elif order_dict.get(i, -1) == order_dict.get(j, -1): continue else: return False else: return True for w1, w2 in zip(words[:-1], words[1:]): if not cmp_func(w1, w2): return False else: return True
verifying-an-alien-dictionary
python3 solution
kaixliu
0
64
verifying an alien dictionary
953
0.527
Easy
15,493
https://leetcode.com/problems/verifying-an-alien-dictionary/discuss/1835087/python-3-oror-HashMap-solution
class Solution: def isAlienSorted(self, words: List[str], order: str) -> bool: self.orderMap = {c: i for i, c in enumerate(order)} return all(self.le(words[i], words[i + 1]) for i in range(len(words) - 1)) def le(self, word1: str, word2: str) -> bool: """ check if word1 <= word2 """ for c1, c2 in zip(word1, word2): if self.orderMap[c1] < self.orderMap[c2]: return True elif self.orderMap[c1] > self.orderMap[c2]: return False return len(word1) <= len(word2)
verifying-an-alien-dictionary
python 3 || HashMap solution
dereky4
0
134
verifying an alien dictionary
953
0.527
Easy
15,494
https://leetcode.com/problems/verifying-an-alien-dictionary/discuss/1679118/Straightforward-approach-in-Python
class Solution: def isAlienSorted(self, words: List[str], order: str) -> bool: def is_right_order(word1, word2): #edge cases if word1 == word2: return True elif word1.startswith(word2): return False #compare each character for char1, char2 in zip(word1, word2): order1, order2 = char_to_idx[char1], char_to_idx[char2] if order1 < order2: return True if order1 > order2: return False return True char_to_idx = {char : idx for idx, char in enumerate(order)} #compare two adjacent words for prev_word, curr_word in zip(words, words[1:]): if not is_right_order(prev_word, curr_word): return False return True
verifying-an-alien-dictionary
Straightforward approach in Python
kryuki
0
141
verifying an alien dictionary
953
0.527
Easy
15,495
https://leetcode.com/problems/verifying-an-alien-dictionary/discuss/1625609/Python3-Solution-with-using-hashmap
class Solution: def isAlienSorted(self, words: List[str], order: str) -> bool: #prepare d = {} for idx, symb in enumerate(order): d[symb] = idx for idx in range(len(words) - 1): for w_idx in range(len(words[idx])): if len(words[idx + 1]) - 1 < w_idx: return False if d[words[idx][w_idx]] > d[words[idx + 1][w_idx]]: return False elif d[words[idx][w_idx]] < d[words[idx + 1][w_idx]]: break return True
verifying-an-alien-dictionary
[Python3] Solution with using hashmap
maosipov11
0
78
verifying an alien dictionary
953
0.527
Easy
15,496
https://leetcode.com/problems/verifying-an-alien-dictionary/discuss/1600214/Simplest-Python-Solution-97-Faster
class Solution: def isAlienSorted(self, words: List[str], order: str) -> bool: alpha={} # define alphabet dict rank=1 # rank in alphabet # fill the alphabet dict for letter in order: alpha[letter]=rank rank+=1 # compare always two words at a time for i in range(len(words)-1): word1=words[i] word2=words[i+1] # if words are the same, exit the current execution and go to next i if word1==word2: continue # if first word starts with second, return False if word1.startswith(word2): return False # convert the strings to list word1=list(word1) word2=list(word2) # assign indexes before iterating through both words index1=0 index2=0 # iterate until the lengths are not exceeded while index1<len(word1) and index2<len(word2): if word1[index1]==word2[index2]: # if letters are the same, increase index index1+=1 index2+=1 else: # if letters are not the same if alpha[word1[index1]]>alpha[word2[index2]]: # if letter in word1 comes after in alphabet than letter in word2, return False return False else: break # end the while loop if the words are in order to move to next word pair to verify return True # if no False is returned until this point, it is True
verifying-an-alien-dictionary
Simplest Python Solution - 97% Faster
demirk
0
99
verifying an alien dictionary
953
0.527
Easy
15,497
https://leetcode.com/problems/verifying-an-alien-dictionary/discuss/1592634/Python-Easy-To-Understand-with-MapDictonary
class Solution: def isAlienSorted(self, words: List[str], order: str) -> bool: if len(words) < 2: return True order = {c:i for i,c in enumerate(order)} for wi in range(1, len(words)): first, second = words[wi-1], words[wi] minLen = min(len(first), len(second)) print(wi, first[:minLen], second[:minLen]) if first[:minLen]==second[:minLen]: if len(second)<len(first): return False else: for i in range(minLen): print(order[first[i]], order[second[i]]) if order[first[i]] > order[second[i]]: return False elif order[first[i]] < order[second[i]]: break #elif order[first[i]] == order[second[i]]: continue return True
verifying-an-alien-dictionary
Python Easy To Understand with Map/Dictonary
abrarjahin
0
92
verifying an alien dictionary
953
0.527
Easy
15,498
https://leetcode.com/problems/verifying-an-alien-dictionary/discuss/1451587/Python-3-avoiding-comparison-of-all-values
class Solution: def isAlienSorted(self, words: List[str], order: str) -> bool: i = 1 while i < len(words): word1 = words[i - 1] word2 = words[i] j = 0 if (word1.find(word2) == 0) and (len(word1) > len(word2)): return False while j < min(len(word1), len(word2)): o1 = order.find(word1[j]) o2 = order.find(word2[j]) if o1 < o2: break; elif o1 == o2: j += 1 else: return False i += 1 return True
verifying-an-alien-dictionary
Python 3 avoiding comparison of all values
mihirbhende1201
0
117
verifying an alien dictionary
953
0.527
Easy
15,499