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/add-to-array-form-of-integer/discuss/1083523/Pythonic-one-line-decision | class Solution:
def addToArrayForm(self, A: List[int], K: int) -> List[int]:
return [int(n) for n in list(str(int("".join([str(x) for x in A])) + K))] | add-to-array-form-of-integer | Pythonic one line decision | cruim | 0 | 74 | add to array form of integer | 989 | 0.455 | Easy | 16,100 |
https://leetcode.com/problems/add-to-array-form-of-integer/discuss/1037609/2-simple-methods-with-explanation-(Python3) | class Solution:
def addToArrayForm(self, A: List[int], K: int) -> List[int]:
st = ""
for i in A:
st += str(i)
return(list(str(int(st) + K))) | add-to-array-form-of-integer | 2 simple methods with explanation (Python3) | vatsalbhuva11 | 0 | 85 | add to array form of integer | 989 | 0.455 | Easy | 16,101 |
https://leetcode.com/problems/add-to-array-form-of-integer/discuss/1037609/2-simple-methods-with-explanation-(Python3) | class Solution:
def addToArrayForm(self, A: List[int], K: int) -> List[int]:
return (list(str(int(''.join([str(x) for x in A]))+K))) | add-to-array-form-of-integer | 2 simple methods with explanation (Python3) | vatsalbhuva11 | 0 | 85 | add to array form of integer | 989 | 0.455 | Easy | 16,102 |
https://leetcode.com/problems/add-to-array-form-of-integer/discuss/751001/One-Line-Easy-Python-Solution | class Solution:
def addToArrayForm(self, A: List[int], K: int) -> List[int]:
return list(map(int,list(str(int(''.join(list(map(str, A))))+K)))) | add-to-array-form-of-integer | One Line Easy Python Solution | CrazyCoder007 | 0 | 124 | add to array form of integer | 989 | 0.455 | Easy | 16,103 |
https://leetcode.com/problems/add-to-array-form-of-integer/discuss/670381/4-Line-Intuitive-Python-solution | class Solution(object):
def addToArrayForm(self, A, K):
num = 0
for i in range(len(A)):
num = (num*10 + A[i])
return [int(i) for i in str(num + K)] | add-to-array-form-of-integer | 4-Line Intuitive Python solution | la_vie_de_chat | 0 | 116 | add to array form of integer | 989 | 0.455 | Easy | 16,104 |
https://leetcode.com/problems/add-to-array-form-of-integer/discuss/376762/Python-100 | class Solution(object):
def addToArrayForm(self, A, K):
"""
:type A: List[int]
:type K: int
:rtype: List[int]
"""
A.reverse()
i = 0
while K != 0:
if i == len(A):
A.append(0)
A[i] = A[i] + K % 10
K //= 10
i += 1
for i in range(len(A) - 1):
if A[i] > 9:
A[i] %= 10
A[i + 1] += 1
if A[-1] > 9:
A.append(0)
A[-2] %= 10
A[-1] = 1
A.reverse()
return A | add-to-array-form-of-integer | Python 100% | DenysCoder | 0 | 342 | add to array form of integer | 989 | 0.455 | Easy | 16,105 |
https://leetcode.com/problems/add-to-array-form-of-integer/discuss/305538/Python-3 | class Solution:
def addToArrayForm(self, A: List[int], K: int) -> List[int]:
a=int(''.join(str(i) for i in A))
res=a+K
ans=[]
for i in str(res):
ans.append(int(i))
return ans | add-to-array-form-of-integer | Python 3 | JasperZhou | 0 | 131 | add to array form of integer | 989 | 0.455 | Easy | 16,106 |
https://leetcode.com/problems/add-to-array-form-of-integer/discuss/289314/python-sol | class Solution:
def addToArrayForm(self, A: List[int], K: int) -> List[int]:
A_str=""
for i in A:
A_str=A_str+str(i)
Ans = int(A_str)+K
Ans_list=[]
for j in str(Ans):
Ans_list.append(int(j))
return Ans_list | add-to-array-form-of-integer | python sol | skywalker0803r | 0 | 119 | add to array form of integer | 989 | 0.455 | Easy | 16,107 |
https://leetcode.com/problems/add-to-array-form-of-integer/discuss/246068/Python-Easy-Solution | class Solution(object):
def addToArrayForm(self, A, K):
"""
:type A: List[int]
:type K: int
:rtype: List[int]
"""
A = int(''.join(map(str, A)))
B = A + K
C = list(map(int, str(B)))
return C | add-to-array-form-of-integer | Python Easy Solution | ParthS007 | 0 | 162 | add to array form of integer | 989 | 0.455 | Easy | 16,108 |
https://leetcode.com/problems/satisfiability-of-equality-equations/discuss/2624938/python3-oror-13-lines-sets-oror-1-TM%3A-8967 | class Solution: # Here's the plan:
# 1) We make an undirected graph in which the nodes are integers
# (as lower-case letters) and each edge connects integers
# that are equal.
# 2) We use a union-find process to determine the connected graphs
# 3) We keep track of the pairs (a,b) such that a =! b. If the any
# such pair are in the same connected graph, then return False,
# otherwise return True.
def equationsPossible(self, equations: List[str]) -> bool:
parent, diff = {}, []
def find(x):
if x not in parent: return x
else: return find(parent[x])
for s in equations: # <-- 1)
a, b = s[0], s[3]
if s[1]== "=": # <-- 2)
x, y = find(a), find(b)
if x!=y:
parent[y] = x
else:
diff.append((a,b)) # <-- 3)
return all(find(a)!=find(b) for a, b in diff) | satisfiability-of-equality-equations | python3 || 13 lines, sets || 1 T/M: 89%/67% | warrenruud | 26 | 1,800 | satisfiability of equality equations | 990 | 0.508 | Medium | 16,109 |
https://leetcode.com/problems/satisfiability-of-equality-equations/discuss/2626592/Python-Union-Find-Solution-Two-Passes-or-Beats-99-Time-or-Time%3A-O(N)-Space%3A-O(N) | class Solution:
def equationsPossible(self, equations: List[str]) -> bool:
"""
Time: O(N), Space: O(N)
"""
parent = {}
def union(c1, c2):
pc1 = find(c1)
pc2 = find(c2)
if pc1 == pc2:
return
parent[pc2] = pc1
def find(c):
if not parent.get(c):
parent[c] = c
return c
if parent[c] == c:
return c
return find(parent[c])
# First make the disjoint sets by traversing the equals
for eq in equations:
if eq[1] == '=':
x, y = eq[0], eq[3]
union(x, y)
# for all inequalities, their parents must be different
for eq in equations:
if eq[1] == '!':
if find(eq[0]) == find(eq[3]):
return False
return True | satisfiability-of-equality-equations | Python Union Find Solution - Two Passes | Beats 99% Time | Time: O(N), Space: O(N) | dos_77 | 1 | 67 | satisfiability of equality equations | 990 | 0.508 | Medium | 16,110 |
https://leetcode.com/problems/satisfiability-of-equality-equations/discuss/2624849/Python-or-Union-Find-or-With-Explanation-or-Easy-to-Understand | class Solution:
def equationsPossible(self, equations: List[str]) -> bool:
# We use union-find (or called disjoint-set) in this problem
# the basic idea of union-find is to connect the components that share a same root
# e.g. a == b, b == c, c == d, then a, b, c, d should be put together
# we pick up a root for these connected components, this root could be a, b, c, or d , we actually don't care :)
# we just want them be together!
# initialize an array, where the root of each element is itself at the begining
root = list(range(26))
# find the root of x
def find(x):
if x != root[x]:
root[x] = find(root[x])
return root[x]
# merge the connected components that x and y belong to respectively
def union(x, y):
root_x, root_y = find(x), find(y)
root[root_x] = root_y
# build the connected components with the equal equations
for equation in equations:
if equation[1] == '=':
x, y = ord(equation[0])-ord('a'), ord(equation[3])-ord('a')
# x and y should share a same root, so we use union here
union(x, y)
# traverse the unequal equations to obtain the final result
for equation in equations:
if equation[1] == '!':
x, y = ord(equation[0])-ord('a'), ord(equation[3])-ord('a')
# x, y should have different roots, so here we find their roots respectively
if find(x) == find(y):
return False
return True | satisfiability-of-equality-equations | Python | Union Find | With Explanation | Easy to Understand | Mikey98 | 1 | 93 | satisfiability of equality equations | 990 | 0.508 | Medium | 16,111 |
https://leetcode.com/problems/satisfiability-of-equality-equations/discuss/2628242/Python-Easy-AF-Solution-or-Union-Find | class Solution:
def equationsPossible(self, equations: List[str]) -> bool:
roots, get = [i for i in range(26)], lambda x: ord(x) - ord('a')
def find(x):
return x if roots[x] == x else find(roots[x])
for a,op,_,b in equations:
if op == '=':
roots[find(get(a))] = find(get(b))
for a,op,_,b in equations:
if op == '!' and find(get(a)) == find(get(b)): return False
return True | satisfiability-of-equality-equations | ✅ Python Easy AF Solution | Union Find | dhananjay79 | 0 | 33 | satisfiability of equality equations | 990 | 0.508 | Medium | 16,112 |
https://leetcode.com/problems/satisfiability-of-equality-equations/discuss/2628061/Lazy-solution-with-Floyd-Warshall-in-Python | class Solution:
def parse(self, eq):
return ord(eq[0]) - ord('a'), eq[1:3], ord(eq[3]) - ord('a')
def equationsPossible(self, equations: List[str]) -> bool:
graph = [[0] * 26 for _ in range(26)]
for eq in equations:
x, r, y = self.parse(eq)
if r == '==':
graph[x][y], graph[y][x] = 1, 1
elif x == y:
return False
for k in range(26):
for i in range(26):
if graph[i][k]:
for j in range(26):
if graph[k][j]:
graph[i][j] = 1
for eq in equations:
x, r, y = self.parse(eq)
if r == '!=' and graph[x][y]:
return False
return True | satisfiability-of-equality-equations | Lazy solution with Floyd-Warshall in Python | metaphysicalist | 0 | 5 | satisfiability of equality equations | 990 | 0.508 | Medium | 16,113 |
https://leetcode.com/problems/satisfiability-of-equality-equations/discuss/2627766/Python-Simple-Python-Solution-Using-Graph-and-DFS | class Solution:
def equationsPossible(self, equations: List[str]) -> bool:
graph = {}
notequal = []
for equation in equations:
a = equation[0]
b = equation[3]
option = equation[1:3]
if option == '==':
if a not in graph:
graph[a] = set(b)
else:
graph[a].add(b)
if b not in graph:
graph[b] = set(a)
else:
graph[b].add(a)
else:
if a == b:
return False
else:
notequal.append(equation)
def FindPath(a, b, visited = None):
if visited is None:
visited = set()
visited.add(a)
if a == b:
return True
if a not in graph:
return False
for key in graph[a]:
if key not in visited:
visited.add(key)
if FindPath(key, b, visited):
return True
return False
for equation in notequal:
a = equation[0]
b = equation[3]
option = equation[1:3]
if FindPath(a,b):
return False
return True | satisfiability-of-equality-equations | [ Python ] ✅✅ Simple Python Solution Using Graph and DFS 🥳✌👍 | ASHOK_KUMAR_MEGHVANSHI | 0 | 63 | satisfiability of equality equations | 990 | 0.508 | Medium | 16,114 |
https://leetcode.com/problems/satisfiability-of-equality-equations/discuss/2625803/python3-oror-lowest-Memory-usage-oror-Runtime-%3A-38 | class Solution:
def equationsPossible(self, equations: List[str]) -> bool:
word_dict = {chr(i+97):i for i in range(26)}
dif = []
for i in equations:
xy = sorted([i[0],i[3]])
if i[1] == '!':
dif.append(xy)
else:
num = word_dict[xy[0]]
chan = word_dict[xy[1]]
for i in word_dict:
if word_dict[i] == chan:
word_dict[i] = num
for i,j in dif:
if word_dict[i] == word_dict[j]:
return False
return True | satisfiability-of-equality-equations | python3 || lowest Memory usage || Runtime : 38% | seogudwns | 0 | 17 | satisfiability of equality equations | 990 | 0.508 | Medium | 16,115 |
https://leetcode.com/problems/satisfiability-of-equality-equations/discuss/2625776/python3-efficient-solution-using-graph-concept | class Solution:
def equationsPossible(self, equations: List[str]) -> bool:
dic=defaultdict(list)
for i in equations:
if i[1]=='=' and i[2]=='=':
dic[i[0]].append(i[3])
dic[i[3]].append(i[0])
for j in equations:
if j[1]=='!':
qu=deque([j[0]])
vis=set()
vis.add(j[0])
get=False
while qu and not get:
r=len(qu)
for _ in range(r):
temp=qu.popleft()
if temp==j[3]:
get=True
break
for nabour in dic[temp]:
if nabour not in vis:
qu.append(nabour)
vis.add(nabour)
if get:
return False
return True | satisfiability-of-equality-equations | python3 efficient solution using graph concept | benon | 0 | 23 | satisfiability of equality equations | 990 | 0.508 | Medium | 16,116 |
https://leetcode.com/problems/satisfiability-of-equality-equations/discuss/2625700/O(nlogn)-using-Union-FInd-for-building-equal-equations-and-checking-differences | class Solution:
def equationsPossible(self, equations: List[str]) -> bool:
def find(root, u):
root[u] = root.get(u, u)
if u != root[u]:
root[u] = find(root, root[u])
return root[u]
diff = {}
root = {}
for ei in equations:
ai, bi, op = ei[0], ei[3], ei[1]
root[ai] = find(root, ai)
root[bi] = find(root, bi)
if op=='!':
diff[ai] = diff.get(ai, [])
diff[ai].append(bi)
else:
if root[ai] != root[bi]:
root[root[bi]] = root[ai]
for u in root:
root[u] = find(root, u)
# print(root)
# print(diff)
ans = True
for u in diff:
for v in diff[u]:
if root[u]==root[v]:
ans = False
break
if not ans:
break
# print("=" * 20, "\n")
return ans | satisfiability-of-equality-equations | O(nlogn) using Union-FInd for building equal equations and checking differences | dntai | 0 | 4 | satisfiability of equality equations | 990 | 0.508 | Medium | 16,117 |
https://leetcode.com/problems/satisfiability-of-equality-equations/discuss/2625034/python3-DFS-sol-for-reference | class Solution:
def equationsPossible(self, equations: List[str]) -> bool:
g = defaultdict(set)
def dfs(s, target):
ret = False
visiting[s] = 1
for nei in g[s]:
if visiting[nei] == 0:
if nei == target:
return True
ret |= dfs(nei, target)
return ret
for i in equations:
if i[1:3] == "==":
g[i[0]].add(i[-1])
g[i[-1]].add(i[0])
visiting = defaultdict(int)
for i in equations:
if i[1:3] == "!=":
if i[0] == i[-1]:
return False
visiting.clear()
if dfs(i[0], i[-1]):
return False
return True | satisfiability-of-equality-equations | [python3] DFS sol for reference | vadhri_venkat | 0 | 7 | satisfiability of equality equations | 990 | 0.508 | Medium | 16,118 |
https://leetcode.com/problems/satisfiability-of-equality-equations/discuss/2505046/Python-union-find | class Solution:
def equationsPossible(self, equations: List[str]) -> bool:
def find(n):
n = ord(n) - ord('a')
while root[n] != n:
n = root[n]
return n
def union(n1, n2):
r1, r2 = find(n1), find(n2)
root[r2] = r1
root = list(range(26))
for eq in equations:
if eq[1] == '=':
union(eq[0], eq[-1])
for eq in equations:
if eq[1] == '!' and find(eq[0]) == find(eq[-1]):
return False
return True | satisfiability-of-equality-equations | Python, union-find | blue_sky5 | 0 | 32 | satisfiability of equality equations | 990 | 0.508 | Medium | 16,119 |
https://leetcode.com/problems/satisfiability-of-equality-equations/discuss/2420527/Satisfiability-of-Equality-Equations-oror-Python3-oror-Union-Find | class Solution:
def equationsPossible(self, equations: List[str]) -> bool:
parent = {}
rank = {}
for eq in equations:
if(eq[1:3] == '=='):
self.set_param(eq[0], parent, rank)
self.set_param(eq[-1], parent, rank)
self.union(eq[0], eq[-1], parent, rank)
for eq in equations:
if(eq[1:3] == '!='):
self.set_param(eq[0], parent, rank)
self.set_param(eq[-1], parent, rank)
find_x = self.find(eq[0], parent)
find_y = self.find(eq[-1], parent)
if(find_x == find_y):
return False
return True
def set_param(self, x, parent, rank):
if(x not in parent):
parent[x] = x
if(x not in rank):
rank[x] = 0
def find(self, x, parent):
if(parent[x] != x):
parent[x] = self.find(parent[x], parent)
return parent[x]
def union(self, x, y, parent, rank):
p_x = self.find(x, parent)
p_y = self.find(y, parent)
if(p_x == p_y):
return
rankx = rank[p_x]
ranky = rank[p_y]
if(rankx > ranky):
parent[p_y] = p_x
elif(rankx < ranky):
parent[p_x] = p_y
else:
parent[p_y] = p_x
rank[p_x] += 1 | satisfiability-of-equality-equations | Satisfiability of Equality Equations || Python3 || Union-Find | vanshika_2507 | 0 | 6 | satisfiability of equality equations | 990 | 0.508 | Medium | 16,120 |
https://leetcode.com/problems/satisfiability-of-equality-equations/discuss/1986591/PYTHON-SOL-oror-UNION-FIND-AND-PATH-COMPRESSION-oror-VERY-EASY-SOL-oror-EXPLAINED-WELL-oror | class Solution:
def findParent(self,x):
if self.parent[x] != x:
self.parent[x] = self.findParent(self.parent[x])
return self.parent[x]
def union(self,a,b):
p1 = self.findParent(a)
p2 = self.findParent(b)
if p1 != p2:
if self.rank[p1] > self.rank[p2]:
self.parent[p2] = p1
elif self.rank[p1] < self.rank[p2]:
self.parent[p1] = p2
else:
self.parent[p2] = p1
self.rank[p1] += 1
def equationsPossible(self, equations: List[str]) -> bool:
self.parent = [i for i in range(26)]
self.rank = [1]*26
indexes = []
for index,equation in enumerate(equations):
a = equation[0]
b = equation[3]
isEqual = True if equation[1:3] == '==' else False
if isEqual == True:
self.union(ord(a)-97,ord(b)-97)
else:
indexes.append(index)
for i in range(26):
self.parent[i] = self.findParent(i)
for index in indexes:
equation = equations[index]
a = equation[0]
b = equation[3]
if self.parent[ord(a)-97] == self.parent[ord(b)-97]:
return False
return True | satisfiability-of-equality-equations | PYTHON SOL || UNION FIND AND PATH COMPRESSION || VERY EASY SOL || EXPLAINED WELL || | reaper_27 | 0 | 66 | satisfiability of equality equations | 990 | 0.508 | Medium | 16,121 |
https://leetcode.com/problems/satisfiability-of-equality-equations/discuss/1584430/Python3 | class Solution:
EQUAL = '=='
NOT_EQUAL = '!='
def equationsPossible(self, equations: List[str]) -> bool:
groups = {}
for equation in equations:
left = equation[0]
op = equation[1] + equation[2]
right = equation[3]
if left == right and op == self.NOT_EQUAL:
return False
larger = max(left, right)
smaller = min(left, right)
if larger == smaller:
if larger not in groups:
groups[smaller] = smaller
groups[larger] = smaller
if op == self.EQUAL:
if left in groups and right in groups:
left_leader = self.get_group_leader(groups, left)
right_leader = self.get_group_leader(groups, right)
operands_to_update = [left_leader, right_leader, left, right]
self.assign_groups(groups, operands_to_update)
elif left not in groups and right not in groups:
operands_to_update = [left, right]
self.assign_groups(groups, operands_to_update)
elif left in groups:
left_leader = self.get_group_leader(groups, left)
operands_to_update = [left_leader, left, right]
self.assign_groups(groups, operands_to_update)
else:
right_leader = self.get_group_leader(groups, right)
operands_to_update = [right_leader, left, right]
self.assign_groups(groups, operands_to_update)
else:
if left in groups and right in groups:
left_leader = self.get_group_leader(groups, left)
right_leader = self.get_group_leader(groups, right)
if left_leader == right_leader:
return False
elif left not in groups and right not in groups:
groups[left] = left
groups[right] = right
elif left in groups:
left_leader = self.get_group_leader(groups, left)
if left_leader == right:
return False
groups[right] = right
else:
right_leader = self.get_group_leader(groups, right)
if right_leader == left:
return False
groups[left] = left
for equation in equations:
left = equation[0]
left_leader = self.get_group_leader(groups, left)
op = equation[1] + equation[2]
right = equation[3]
right_leader = self.get_group_leader(groups, right)
if left_leader == right_leader and op == self.NOT_EQUAL:
return False
return True
def get_group_leader(self, groups, operand):
if groups[operand] == operand:
return operand
group_leader = self.get_group_leader(groups, groups[operand])
groups[operand] = group_leader
return group_leader
def assign_groups(self, groups, operands, leader=None):
if leader is None:
leader = min(operands)
for operand in operands:
groups[operand] = leader | satisfiability-of-equality-equations | Python3 | shiv-sj | 0 | 61 | satisfiability of equality equations | 990 | 0.508 | Medium | 16,122 |
https://leetcode.com/problems/satisfiability-of-equality-equations/discuss/1473134/Python3-or-Union-Find | class Solution:
def equationsPossible(self, equations: List[str]) -> bool:
self.disjoint()
for i in equations:
if i[1]+i[2]=="==":
self.union(i[0],i[3])
for i in equations:
if i[1]+i[2]=="!=" and not self.verify(i[0],i[1]+i[2],i[3]):
return False
else:
continue
return True
def verify(self,a,sign,b):
p1=self.find(ord(a)-97)
p2=self.find(ord(b)-97)
if sign=="!=":
if p1==p2:
return False
elif sign=="==":
if p1!=p2:
return False
return True
def disjoint(self):
self.parent=[i for i in range(26)]
self.rank=[0 for i in range(26)]
def find(self,node):
if node==self.parent[node]:
return node
self.parent[node]=self.find(self.parent[node])
return self.parent[node]
def union(self,a,b):
p1=self.find(ord(a)-97)
p2=self.find(ord(b)-97)
if self.rank[p1]>self.rank[p2]:
self.parent[p2]=p1
elif self.rank[p2]>self.rank[p1]:
self.parent[p1]=p2
else:
self.parent[p2]=p1
self.rank[p1]+=1 | satisfiability-of-equality-equations | [Python3] | Union-Find | swapnilsingh421 | 0 | 48 | satisfiability of equality equations | 990 | 0.508 | Medium | 16,123 |
https://leetcode.com/problems/satisfiability-of-equality-equations/discuss/1465349/Python-solution-using-Union-Find | class Solution:
def equationsPossible(self, equations: List[str]) -> bool:
equalities = [s.split("==") for s in equations if s[1:3] == "=="]
inequalities =[s.split("!=") for s in equations if s[1:3] == "!="]
f = {}
def find(x):
f.setdefault(x, x)
if x != f[x]:
f[x] = find(f[x])
return f[x]
def union(x, y):
f[find(x)] = find(y)
for char1, char2 in equalities:
union(char1, char2)
for char1, char2 in inequalities:
if find(char1) == find(char2):
return False
return True | satisfiability-of-equality-equations | Python solution using Union Find | Vikram006 | 0 | 46 | satisfiability of equality equations | 990 | 0.508 | Medium | 16,124 |
https://leetcode.com/problems/satisfiability-of-equality-equations/discuss/961205/Python-top-percentile-elegant | class Solution:
def equationsPossible(self, equations: List[str]) -> bool:
equalities = filter(lambda _: "==" in _, equations)
inequalities = filter(lambda _: "!=" in _, equations)
sets = []
# Sorting equalities guarantees deterministic clustering
for x, _, __, y in sorted(equalities):
matching = None
for s in sets:
if x in s or y in s:
matching = s
if matching:
matching.add(x)
matching.add(y)
else:
sets.append({x, y})
for x, _, __, y in inequalities:
if x == y:
return False
for s in sets:
if x in s and y in s:
return False
return True | satisfiability-of-equality-equations | Python top-percentile, elegant | tyril | 0 | 72 | satisfiability of equality equations | 990 | 0.508 | Medium | 16,125 |
https://leetcode.com/problems/satisfiability-of-equality-equations/discuss/852605/Python-Easy-Disjoint-Union-Set | class Solution:
def __init__(self):
self.id_ = [i for i in range(26)]
def find(self,x):
while x != self.id_[x]:
self.id_[x] = self.id_[self.id_[x]]
x = self.id_[x]
return x
def union(self,x,y):
x = self.find(x)
y = self.find(y)
self.id_[x] = self.id_[y]
def equationsPossible(self, equations: List[str]) -> bool:
for a,sign,_,b in equations:
if sign == '=':
self.union(ord(a)-97,ord(b)-97)
for a,sign,_,b in equations:
if sign == '!':
if self.find(ord(a)-97) == self.find(ord(b)-97):
return False
return True | satisfiability-of-equality-equations | [Python} Easy Disjoint Union Set | realslimshady | 0 | 89 | satisfiability of equality equations | 990 | 0.508 | Medium | 16,126 |
https://leetcode.com/problems/broken-calculator/discuss/1033822/Easy-and-Clear-Solution-Python-3 | class Solution:
def brokenCalc(self, x: int, y: int) -> int:
if y<=x:
return x-y
else:
res=0
while x<y:
if y%2==1:
y+=1
else:
y=y//2
res+=1
res+=(x-y)
return res | broken-calculator | Easy & Clear Solution Python 3 | moazmar | 2 | 182 | broken calculator | 991 | 0.541 | Medium | 16,127 |
https://leetcode.com/problems/broken-calculator/discuss/2416694/Python-95.67-faster-or-Simplest-solution-with-explanation-or-Beg-to-Adv-or-Greedy | class Solution:
def brokenCalc(self, startValue: int, target: int) -> int:
res = 0 # taking a counter.
while target > startValue: # checking if target value is greater then startValue.
res += 1 # as if target is greater implies we`ll be having atleast one operation.
if target%2==0:
target //=2 # in case number is even.
else:
target += 1 # in case number odd.
return res + startValue - target# startValue - target is for (target<=staetValue). | broken-calculator | Python 95.67% faster | Simplest solution with explanation | Beg to Adv | Greedy | rlakshay14 | 0 | 54 | broken calculator | 991 | 0.541 | Medium | 16,128 |
https://leetcode.com/problems/broken-calculator/discuss/1988675/PYTHON-SOL-oror-LOG-SOL-oror-GO-BACKWARDS-oror-EXPLAINED-oror | class Solution:
def brokenCalc(self, startValue: int, target: int) -> int:
operations = 0
cpy = target
while True:
if target <= startValue:
break
if target %2 == 1:
target += 1
operations += 1
target = target // 2
operations += 1
way1 = operations + startValue - target
return way1 | broken-calculator | PYTHON SOL || LOG SOL || GO BACKWARDS || EXPLAINED || | reaper_27 | 0 | 51 | broken calculator | 991 | 0.541 | Medium | 16,129 |
https://leetcode.com/problems/broken-calculator/discuss/1897757/Python-3-or-Easy-solution-or-No-tricks-and-no-shortcuts-used | class Solution:
def brokenCalc(self, startValue: int, target: int) -> int:
tempTarget = target
tempStartValue = startValue
ct1_p1 = 0
while tempTarget > startValue:
if tempTarget%2 == 0:
tempTarget = tempTarget//2
else:
tempTarget += 1
ct1_p1 += 1
ct1_p2 = (startValue - tempTarget)
ct2_p1 = 0
while tempStartValue < target:
tempStartValue = tempStartValue*2
ct2_p1 += 1
ct2_p2 = (tempStartValue - target)
return min( ct1_p1+ ct1_p2, ct2_p1+ ct2_p2) | broken-calculator | Python 3 | Easy solution | No tricks and no shortcuts used | krunalk013 | 0 | 72 | broken calculator | 991 | 0.541 | Medium | 16,130 |
https://leetcode.com/problems/broken-calculator/discuss/1878573/Python-Easy-Solution-with-Explanation | class Solution:
def brokenCalc(self, startValue: int, target: int) -> int:
step = 0
while target != startValue:
if target < startValue:
step = step + (startValue - target)
return step
else:
if target%2 == 0:
target = target//2
step += 1
else:
target = target+1
step+=1
return step | broken-calculator | Python Easy Solution with Explanation | EnergyBoy | 0 | 9 | broken calculator | 991 | 0.541 | Medium | 16,131 |
https://leetcode.com/problems/broken-calculator/discuss/1877899/Python-greedy-solution-or-With-Explanation-or-Complexity-Analysis | class Solution:
def brokenCalc(self, startValue: int, target: int) -> int:
if startValue == target:
return 0
# can only subtract
if startValue > target:
return startValue-target
# greedy, better to do division than plus
ops = 0
while target > startValue:
if target%2==0:
target//=2
else:
target+=1
ops += 1
return ops + startValue-target | broken-calculator | Python greedy solution | With Explanation | Complexity Analysis | diqing-SHU | 0 | 9 | broken calculator | 991 | 0.541 | Medium | 16,132 |
https://leetcode.com/problems/broken-calculator/discuss/1876589/Python-Iterative-Solution | class Solution:
def brokenCalc(self, startValue: int, target: int) -> int:
steps = 0
if startValue == target:
return steps
while target > startValue:
steps += 1
if target % 2 == 1:
target += 1
else:
target //= 2
return steps + startValue - target | broken-calculator | Python Iterative Solution | pradeep288 | 0 | 25 | broken calculator | 991 | 0.541 | Medium | 16,133 |
https://leetcode.com/problems/broken-calculator/discuss/1876091/Python3Java-Simple-Solution-oror-Greedy | class Solution:
def brokenCalc(self, startValue: int, target: int) -> int:
ans = 0
while startValue < target:
if target % 2 == 0:
ans += 1
target //= 2
else:
ans += 2
target = (target+1)//2
return ans + startValue - target | broken-calculator | [Python3/Java] Simple Solution || Greedy | abhijeetmallick29 | 0 | 28 | broken calculator | 991 | 0.541 | Medium | 16,134 |
https://leetcode.com/problems/broken-calculator/discuss/1875847/Python3-easy-to-understand-O(1)-space-and-O(n)-time | class Solution:
def brokenCalc(self, startValue: int, target: int) -> int:
ops = 0
while target!=startValue:
if target>startValue and target%2==0:
ops+=1
target//=2
elif target>startValue:
diff = target
target+=1
ops+=1
elif target<startValue:
ops += startValue-target
target=startValue
return ops | broken-calculator | Python3 easy to understand O(1) space and O(n) time | shubham3 | 0 | 28 | broken calculator | 991 | 0.541 | Medium | 16,135 |
https://leetcode.com/problems/broken-calculator/discuss/1875636/Python-BFS-Solution | class Solution:
def brokenCalc(self, startValue: int, target: int) -> int:
if startValue >= target:
return startValue - target
queue = [(target, 0)]
visited = {}
while queue:
val, count = queue.pop(0)
if val + 1 == startValue or (val // 2 == startValue and val % 2 == 0):
return count + 1
if val + 1 not in visited:
visited[val + 1] = True
queue.append((val+1, count + 1))
if val % 2 == 0 and val // 2 not in visited:
if val // 2 < startValue:
return count + startValue - val//2 + 1
else:
visited[val//2] = True
queue.append((val // 2, count + 1)) | broken-calculator | Python BFS Solution | atiq1589 | 0 | 42 | broken calculator | 991 | 0.541 | Medium | 16,136 |
https://leetcode.com/problems/broken-calculator/discuss/1875393/Python3-oror-TC%3A-O(log(target))-oror-SC%3AO(1)oror-Greedy | class Solution:
def brokenCalc(self, startValue: int, target: int) -> int:
#traverse backwards, so we have two options, addition and division
steps = 0
while target > startValue:
if target & 1:
target += 1
else:
target = target // 2
steps += 1
return steps + startValue - target | broken-calculator | Python3 || TC: O(log(target)) || SC:O(1)|| Greedy | s_m_d_29 | 0 | 29 | broken calculator | 991 | 0.541 | Medium | 16,137 |
https://leetcode.com/problems/broken-calculator/discuss/1875213/Faster-Than-Faster-Python-Easy-Solution-Using-Greedy-Approach | class Solution:
def brokenCalc(self, startValue: int, target: int) -> int:
result = 0
while True:
if target <= startValue:
result = result + startValue - target
break
if target % 2 == 0:
target = target // 2
result = result + 1
else:
target = target + 1
result = result + 1
return result | broken-calculator | Faster Than Faster ✔✌🔥🔥 [Python] Easy Solution Using Greedy Approach | ASHOK_KUMAR_MEGHVANSHI | 0 | 44 | broken calculator | 991 | 0.541 | Medium | 16,138 |
https://leetcode.com/problems/broken-calculator/discuss/1875191/Double-until-Exceed-and-then-Subtract | class Solution:
def brokenCalc(self, startValue: int, target: int) -> int:
if startValue >= target:
return startValue - target
count=0
while startValue < target:
count += 1
startValue *= 2
ans=count
need_substract=startValue-target
#-2:1 operation, -4 1 operation, ... ,-2^count 1op
while need_substract>0 and count>0:
if need_substract // 2**count:
ans += need_substract // 2**count
need_substract -= 2**count * (need_substract // 2**count)
else:
count -= 1
ans += need_substract
return ans | broken-calculator | Double until Exceed and then Subtract | k3232908 | 0 | 13 | broken calculator | 991 | 0.541 | Medium | 16,139 |
https://leetcode.com/problems/broken-calculator/discuss/1874840/python-ez-greedy-solution | class Solution:
def brokenCalc(self, startValue: int, target: int) -> int:
step = 0
while target > startValue:
if target % 2 == 0:
target /= 2
else:
target += 1
step += 1
step += startValue - target
return int(step) | broken-calculator | python ez greedy solution | yingziqing123 | 0 | 50 | broken calculator | 991 | 0.541 | Medium | 16,140 |
https://leetcode.com/problems/broken-calculator/discuss/1874814/Easy-Commented-Solution-in-Python | class Solution:
def brokenCalc(self, startValue: int, target: int) -> int:
#instead of going from startValue to target we will go from target to startValue
#in this case our operation would change
#instead of multiplying we will be divinding and if the number is odd then we will first add then divide
#incase of subtracting we will be adding
res = 0
while target > startValue:
res += 1
if target % 2 == 0:
target //= 2
else:
target += 1
return res + (startValue - target) | broken-calculator | Easy Commented Solution in Python | Jazzyb1999 | 0 | 42 | broken calculator | 991 | 0.541 | Medium | 16,141 |
https://leetcode.com/problems/broken-calculator/discuss/1874768/python-3-oror-simple-iterative-solution-oror-O(logn)O(1) | class Solution:
def brokenCalc(self, startValue: int, target: int) -> int:
res = 0
while target > startValue:
res += 1
if target % 2:
target += 1
else:
target //= 2
return res + startValue - target | broken-calculator | python 3 || simple iterative solution || O(logn)/O(1) | dereky4 | 0 | 64 | broken calculator | 991 | 0.541 | Medium | 16,142 |
https://leetcode.com/problems/broken-calculator/discuss/1077397/Simple-Python-Sol-(faster-than-99) | class Solution:
def brokenCalc(self, X: int, Y: int) -> int:
if X >= Y:
return X - Y
if Y % 2 == 0:
return 1 + self.brokenCalc(X, Y // 2)
if Y % 2 == 1:
return 2 + self.brokenCalc(X, (Y + 1) // 2) | broken-calculator | Simple Python Sol (faster than 99%) | JulesCui | 0 | 111 | broken calculator | 991 | 0.541 | Medium | 16,143 |
https://leetcode.com/problems/broken-calculator/discuss/985294/Python3-greedy-O(logN) | class Solution:
def brokenCalc(self, X: int, Y: int) -> int:
ans = 0
while X < Y:
if Y&1: Y += 1
else: Y //= 2
ans += 1
return ans + X - Y | broken-calculator | [Python3] greedy O(logN) | ye15 | 0 | 77 | broken calculator | 991 | 0.541 | Medium | 16,144 |
https://leetcode.com/problems/broken-calculator/discuss/1076095/Python-or-Fast-and-Easy-or-Beats-97 | class Solution:
def brokenCalc(self, X: int, Y: int) -> int:
c = 0
while Y>X:
if Y%2: Y += 1
else: Y //= 2
c += 1
return c + (X - Y) | broken-calculator | Python | Fast & Easy | Beats 97% | SlavaHerasymov | -1 | 88 | broken calculator | 991 | 0.541 | Medium | 16,145 |
https://leetcode.com/problems/subarrays-with-k-different-integers/discuss/1215277/Python-Sliding-Window-or-Set-%2B-HashMap | class Solution:
def subarraysWithKDistinct(self, nums: List[int], k: int) -> int:
def window(nums, k):
left = 0
right = 0
res = 0
in_set = set()
hash_map = collections.Counter()
while right < len(nums):
in_set.add(nums[right])
hash_map[nums[right]] += 1
while len(in_set) > k:
hash_map[nums[left]] -= 1
if hash_map[nums[left]] == 0:
in_set.remove(nums[left])
left += 1
res += (right - left + 1)
right += 1
return res
return window(nums, k) - window(nums, k - 1) | subarrays-with-k-different-integers | [Python] Sliding Window | Set + HashMap | Sai-Adarsh | 5 | 813 | subarrays with k different integers | 992 | 0.545 | Hard | 16,146 |
https://leetcode.com/problems/subarrays-with-k-different-integers/discuss/1988735/PYTHON-SOL-oror-FASTER-THAN-99.59-oror-SIMPLE-oror-EXPLAINED-oror-SLIDING-WINDOW-oror-LINEAR-TIME-oror | class Solution:
def subarraysWithKDistinct(self, nums: List[int], k: int) -> int:
ans = 0
n = len(nums)
latest = {}
unique = 0
prev = 0
for i in range(n):
if nums[i] not in latest:
unique += 1
latest[nums[i]] = i
if unique > k :
while True:
if latest[nums[prev]] == prev:
latest.pop(nums[prev])
prev += 1
unique -= 1
break
else:
prev += 1
if unique == k:
ans += 1
tmp = prev
while True:
if latest[nums[tmp]] != tmp:
ans += 1
tmp += 1
else:
break
return ans | subarrays-with-k-different-integers | PYTHON SOL || FASTER THAN 99.59% || SIMPLE || EXPLAINED || SLIDING WINDOW || LINEAR TIME || | reaper_27 | 3 | 273 | subarrays with k different integers | 992 | 0.545 | Hard | 16,147 |
https://leetcode.com/problems/subarrays-with-k-different-integers/discuss/1312341/Python3-sliding-window-%2B-queue | class Solution:
def subarraysWithKDistinct(self, nums: List[int], k: int) -> int:
ans = ii = 0
freq = defaultdict(int)
queue = deque()
for i, x in enumerate(nums):
freq[x] += 1
queue.append(i)
if len(freq) > k:
ii = queue[0]+1
freq.pop(nums[queue.popleft()])
while freq[nums[queue[0]]] > 1: freq[nums[queue.popleft()]] -= 1
if len(freq) == k: ans += queue[0] - ii + 1
return ans | subarrays-with-k-different-integers | [Python3] sliding window + queue | ye15 | 3 | 419 | subarrays with k different integers | 992 | 0.545 | Hard | 16,148 |
https://leetcode.com/problems/subarrays-with-k-different-integers/discuss/853831/Simple-Python-Solution | class Solution:
def helper(self,A,B):
count = 0
left = 0
right = 0
d = {}
while right<len(A):
if A[right] not in d:
d[A[right]] = 0
d[A[right]] += 1
while len(d)>B:
d[A[left]] -= 1
if d[A[left]] == 0:
d.pop(A[left])
left += 1
count += right-left+1
right += 1
return count
def subarraysWithKDistinct(self, A: List[int], B: int) -> int:
return self.helper(A,B)-self.helper(A,B-1) | subarrays-with-k-different-integers | Simple Python Solution | Ayu-99 | 2 | 438 | subarrays with k different integers | 992 | 0.545 | Hard | 16,149 |
https://leetcode.com/problems/subarrays-with-k-different-integers/discuss/1993417/Sliding-window-with-little-help-(weird-but-effective | class Solution:
def subarraysWithKDistinct(self, nums: List[int], k: int) -> int:
ans = 0
n = len(nums)
next = [-1] * n
t_record = dict()
for i in range(n - 1, -1, -1):
if nums[i] in t_record:
next[i] = t_record[nums[i]]
t_record[nums[i]] = i
left = 0
inside = set()
for right in range(n):
inside.add(nums[right])
while len(inside) > k:
if next[left] == -1 or next[left] > right:
inside.remove(nums[left])
left += 1
if len(inside) == k:
cnt = left
while next[cnt] != -1 and next[cnt] <= right:
cnt += 1
ans += cnt - left + 1
return ans | subarrays-with-k-different-integers | Sliding window with little help (weird but effective | luyi4me | 0 | 146 | subarrays with k different integers | 992 | 0.545 | Hard | 16,150 |
https://leetcode.com/problems/subarrays-with-k-different-integers/discuss/1659423/Sliding-Window-and-HashMap | class Solution:
def subarraysWithKDistinct(self, l: List[int], k: int) -> int:
def aps (l,k):
if k==0:
return 0
d={}
for i in l:
d[i]=0
j=diff=ans=0
for i in range(len(l)):
d[l[i]]+=1
if d[l[i]]==1:
diff+=1
if diff<=k:
ans+=(i-j+1)
if diff > k:
while k < diff and j < i :
d[l[j]]-=1
if d[l[j]]==0:
diff-=1
j+=1
ans+=(i-j+1)
return ans
return aps(l,k)-aps(l,k-1) | subarrays-with-k-different-integers | Sliding Window and HashMap | gamitejpratapsingh998 | 0 | 381 | subarrays with k different integers | 992 | 0.545 | Hard | 16,151 |
https://leetcode.com/problems/subarrays-with-k-different-integers/discuss/1502477/Python3-Sliding-widow-solution | class Solution:
def atMostK(self, nums, k):
good_count = 0
counter = collections.Counter()
begin = 0
for end in range(len(nums)):
if counter[nums[end]] == 0:
k -= 1
counter[nums[end]] += 1
while k < 0:
counter[nums[begin]] -= 1
if counter[nums[begin]] == 0:
k += 1
begin += 1
good_count += end - begin + 1
return good_count
def subarraysWithKDistinct(self, nums: List[int], k: int) -> int:
return self.atMostK(nums, k) - self.atMostK(nums, k - 1) | subarrays-with-k-different-integers | [Python3] Sliding widow solution | maosipov11 | 0 | 283 | subarrays with k different integers | 992 | 0.545 | Hard | 16,152 |
https://leetcode.com/problems/cousins-in-binary-tree/discuss/1527334/Python-BFS%3A-Easy-to-understand-solution-w-Explanation | class Solution:
def isCousins(self, root: Optional[TreeNode], x: int, y: int) -> bool:
# Check if root node is x or y
if root.val == x or root.val == y:
return False
# Prepare for BFS, initialise variables
curr, flag = [root.left, root.right], False
while curr:
tmp = []
# Check nodes two-by-two
for i in range(0, len(curr), 2):
# Case 1: x and y are both found
# This indicates that they have the same parent
if curr[i] and curr[i+1] and \
((curr[i].val == x and curr[i+1].val == y) or \
(curr[i+1].val == x and curr[i].val == y)):
return False
# Case 2: Either one of x or y is found
elif (curr[i] and (curr[i].val == x or curr[i].val == y)) or \
(curr[i+1] and (curr[i+1].val == x or curr[i+1].val == y)):
if flag:
# Previously, the other node has been found in the same depth
# This is our success condition, return True
return True
# Otherwise, this is the first node in the current depth to be found
flag = True
# Simultaneously, we can prepare the nodes for the subsequent depth
# Note to append both left and right regardless of existence
if curr[i]:
tmp.append(curr[i].left)
tmp.append(curr[i].right)
if curr[i+1]:
tmp.append(curr[i+1].left)
tmp.append(curr[i+1].right)
# Before we proceed to the next depth, check:
if flag:
# One of the nodes has already been found
# This means that the other node cannot be of the same depth
# By definition, this means that the two nodes are not cousins
return False
curr = tmp # Assign the new nodes as the current ones
# The program will never reach here since x and y are guaranteed to be found
# But you can return False if you want | cousins-in-binary-tree | Python BFS: Easy-to-understand solution w Explanation | zayne-siew | 8 | 423 | cousins in binary tree | 993 | 0.542 | Easy | 16,153 |
https://leetcode.com/problems/cousins-in-binary-tree/discuss/1165675/Python-BFS-Level-Order-Traversal-oror-Iterative | class Solution:
def isCousins(self, root: TreeNode, x: int, y: int) -> bool:
q = [root]
while(q):
toggle = 0
parents = []
for i in range(len(q)): # Level wise exploration starts here
temp = q[0] # storing the first element in a temp variable
q.pop(0) # Dequeuing the first element and exploring its neighbours below
if(temp.left):
q.append(temp.left)
if(temp.left.val==x or temp.left.val==y):
toggle += 1
parents.append(temp)
if(temp.right):
q.append(temp.right)
if(temp.right.val==x or temp.right.val==y):
toggle += 1
parents.append(temp)
# Level wise exploration ends here
# if toggle == 2 that means both x and y are on same level/depth
if((toggle==2) and (parents[0] != parents[1])):
return True # x and y are cousins
return False | cousins-in-binary-tree | Python BFS - Level Order Traversal || Iterative | avinash0007 | 2 | 229 | cousins in binary tree | 993 | 0.542 | Easy | 16,154 |
https://leetcode.com/problems/cousins-in-binary-tree/discuss/2000463/Python-Recursive-DFS-Clean-and-Simple! | class Solution:
def isCousins(self, root, x, y):
self.x, self.y = x, y
self.foundLevel, self.foundParent = None, None
return self.dfs(root, 0, None)
def dfs(self, node, level, parent):
if node.val == self.x or node.val == self.y:
if self.foundLevel and self.foundParent:
return level == self.foundLevel and parent != self.foundParent
else:
self.foundLevel = level; self.foundParent = parent
left = self.dfs(node.left, level+1, node.val) if node.left else False
right = self.dfs(node.right, level+1, node.val) if node.right else False
return left or right | cousins-in-binary-tree | Python - Recursive DFS - Clean and Simple! | domthedeveloper | 1 | 121 | cousins in binary tree | 993 | 0.542 | Easy | 16,155 |
https://leetcode.com/problems/cousins-in-binary-tree/discuss/618715/Python3-tree-traversal-(DFS-and-BFS) | class Solution:
def isCousins(self, root: TreeNode, x: int, y: int) -> bool:
def fn(node, k, parent):
"""Traverse the subtree rooted at node"""
if node is None: return
if node.val in (x, y): ans[node.val] = (k, parent)
fn(node.left, k+1, node)
fn(node.right, k+1, node)
ans = dict()
fn(root, 0, None)
return ans[x][0] == ans[y][0] and ans[x][1] != ans[y][1] | cousins-in-binary-tree | [Python3] tree traversal (DFS & BFS) | ye15 | 1 | 48 | cousins in binary tree | 993 | 0.542 | Easy | 16,156 |
https://leetcode.com/problems/cousins-in-binary-tree/discuss/618715/Python3-tree-traversal-(DFS-and-BFS) | class Solution:
def isCousins(self, root: TreeNode, x: int, y: int) -> bool:
ans = dict()
stack = [(root, 0, None)]
while stack:
node, k, parent = stack.pop()
if not node: continue
if node.val in (x, y): ans[node.val] = (k, parent)
stack.append((node.left, k+1, node))
stack.append((node.right, k+1, node))
return ans[x][0] == ans[y][0] and ans[x][1] != ans[y][1] | cousins-in-binary-tree | [Python3] tree traversal (DFS & BFS) | ye15 | 1 | 48 | cousins in binary tree | 993 | 0.542 | Easy | 16,157 |
https://leetcode.com/problems/cousins-in-binary-tree/discuss/618715/Python3-tree-traversal-(DFS-and-BFS) | class Solution:
def isCousins(self, root: Optional[TreeNode], x: int, y: int) -> bool:
queue = [(root, None)]
while queue:
newq = []
seen = 0
for n, p in queue:
if n.val in (x, y):
if not seen: seen = p
else: return seen != p
if n.left: newq.append((n.left, n))
if n.right: newq.append((n.right, n))
if seen: return False
queue = newq | cousins-in-binary-tree | [Python3] tree traversal (DFS & BFS) | ye15 | 1 | 48 | cousins in binary tree | 993 | 0.542 | Easy | 16,158 |
https://leetcode.com/problems/cousins-in-binary-tree/discuss/2663515/Python3-solution-or-DFS-with-recursion | class Solution:
def isCousins(self, root: Optional[TreeNode], x: int, y: int) -> bool:
self.d1 = self.parent1 = self.d2 = self.parent2 = -1
def DFS(r, depth, parent):
if r:
if r.val == x:
self.d1, self.parent1 = depth, parent
return
if r.val == y:
self.d2, self.parent2 = depth, parent
return
DFS(r.left, depth + 1, r.val)
DFS(r.right, depth + 1, r.val)
DFS(root, 0, None)
return self.d1 == self.d2 and self.parent1 != self.parent2 | cousins-in-binary-tree | Python3 solution | DFS with recursion | mediocre-coder | 0 | 12 | cousins in binary tree | 993 | 0.542 | Easy | 16,159 |
https://leetcode.com/problems/cousins-in-binary-tree/discuss/2407545/Python3-or-BFS-and-hash-map-or-minimal-space-usage | class Solution:
def isCousins(self, root: Optional[TreeNode], x: int, y: int) -> bool:
h = defaultdict(list)
q = deque([(root,0,-1)])
while q:
node, level, parent = q.popleft()
if node:
if node.val == x or node.val == y:
h[node.val] = (parent, level) # optimize by only storing what you care about
q.append((node.left, level+1, node.val))
q.append((node.right, level+1, node.val))
# Check if x and y in the hash map and if they are in the same level and have a different parent
# Option 1: 1 liner approach
# return (x in h and y in h) and (h[x][1] == h[y][1]) and (h[x][0] != h[y][0])
# Option 2: if you prefer to spell steps out for readability
if x in h and y in h:
parent_x, level_x = h[x]
parent_y, level_y = h[y]
if (level_x == level_y) and (parent_x != parent_y):
return True
return False | cousins-in-binary-tree | Python3 | BFS and hash map | minimal space usage | Ploypaphat | 0 | 32 | cousins in binary tree | 993 | 0.542 | Easy | 16,160 |
https://leetcode.com/problems/cousins-in-binary-tree/discuss/1771061/Python3-BFS-solution | class Solution:
def isCousins(self, root: Optional[TreeNode], x: int, y: int) -> bool:
from collections import deque
q=deque()
q.append((root,None,0))
mydict={}
while q:
node,parent,level=q.popleft()
mydict[node.val]=(parent,level)
if node.left:
q.append((node.left,node,level+1))
if node.right:
q.append((node.right,node,level+1))
val1=mydict[x]
val2=mydict[y]
return val1[0]!=val2[0] and val1[1]==val2[1] | cousins-in-binary-tree | Python3 BFS solution | Karna61814 | 0 | 40 | cousins in binary tree | 993 | 0.542 | Easy | 16,161 |
https://leetcode.com/problems/cousins-in-binary-tree/discuss/1691228/Python3%3A-BFS-and-DFS-approach | class Solution:
def isCousins(self, root: Optional[TreeNode], x: int, y: int) -> bool:
f = [True]
def finddepthofelement(root, element):
if root == None:
return 10e5
else:
if root.left and root.right:
if (root.left.val == x and root.right.val == y) or (root.left.val == y and root.right.val == x):
f[0] = False
return 0
elif (root.left.val == element) or (root.right.val == element):
return 1
else:
return 1+ min(finddepthofelement(root.right, element), finddepthofelement(root.left, element))
elif root.left:
if root.left.val == element:
return 1
else:
return 1 + finddepthofelement(root.left, element)
elif root.right:
if root.right.val == element:
return 1
else:
return 1 + finddepthofelement(root.right, element)
else:
return 10e5
if root == None:
return False
else:
xx = finddepthofelement(root, x)
if f[0] == False:
return False
yy = finddepthofelement(root,y)
print(xx, yy)
if xx == yy:
return True
else:
return False | cousins-in-binary-tree | Python3: BFS and DFS approach | devansh_raj | 0 | 100 | cousins in binary tree | 993 | 0.542 | Easy | 16,162 |
https://leetcode.com/problems/cousins-in-binary-tree/discuss/1601452/Python-3-recursion | class Solution:
def isCousins(self, root: Optional[TreeNode], x: int, y: int) -> bool:
self.x_depth = self.y_depth = math.inf
self.x_parent = self.y_parent = None
def helper(root, depth, parent):
if root is None or depth > self.x_depth or depth > self.y_depth:
return False
if root.val == x:
self.x_depth = depth
self.x_parent = parent
return (self.x_depth == self.y_depth and
self.x_parent != self.y_parent)
if root.val == y:
self.y_depth = depth
self.y_parent = parent
return (self.x_depth == self.y_depth and
self.x_parent != self.y_parent)
return (helper(root.left, depth + 1, root) or
helper(root.right, depth + 1, root))
return helper(root, 0, None) | cousins-in-binary-tree | Python 3 recursion | dereky4 | 0 | 143 | cousins in binary tree | 993 | 0.542 | Easy | 16,163 |
https://leetcode.com/problems/cousins-in-binary-tree/discuss/1533814/Simple-python3-solution-using-BFS | class Solution:
def isCousins(self, root: Optional[TreeNode], x: int, y: int) -> bool:
mydict = {}
q = collections.deque()
q.append(root)
level = 0
while q:
items = len(q)
for i in range(items):
que = q.popleft()
if que.val == x:
level_of_x = level
if que.val == y:
level_of_y = level
if que.left:
mydict[que.left.val] = que.val
q.append(que.left)
if que.right:
mydict[que.right.val] = que.val
q.append(que.right)
level = level+1
if level_of_x == level_of_y and mydict[x] != mydict[y]:
return True
else:
return False | cousins-in-binary-tree | Simple python3 solution using BFS | sonali1597 | 0 | 63 | cousins in binary tree | 993 | 0.542 | Easy | 16,164 |
https://leetcode.com/problems/cousins-in-binary-tree/discuss/1517368/Python3-bfs-solution | class Solution:
def isCousins(self, root: Optional[TreeNode], x: int, y: int) -> bool:
q = [root]
while q:
z = []
n = len(q)
for j in range(n):
i = q.pop(0)
if i.left and i.right and ((i.left.val == x and i.right.val == y) or (i.left.val == y and i.right.val == x)):
return False
if i.left:
z.append(i.left.val)
q.append(i.left)
if i.right:
z.append(i.right.val)
q.append(i.right)
if x in z and y in z:
return True
return False | cousins-in-binary-tree | Python3 bfs solution | EklavyaJoshi | 0 | 27 | cousins in binary tree | 993 | 0.542 | Easy | 16,165 |
https://leetcode.com/problems/cousins-in-binary-tree/discuss/1444411/Python-using-level-order-traversal | class Solution:
def isCousins(self, root: TreeNode, x: int, y: int) -> bool:
q=[root]
depth=0
c1,c2=0,0
while q:
new=[]
depth+=1
for i in q:
if i.left and i.right:
if i.left.val==x and i.right.val==y or i.left.val==y and i.right.val==x:
return False
if i.val==x:
c1=depth
if i.val==y:
c2=depth
if i.left:
new.append(i.left)
if i.right:
new.append(i.right)
print(c1,c2,i.val)
q=new
if c1==c2 and c1>0 and c2>0:
return True
return False | cousins-in-binary-tree | Python - using level order traversal | prajwalahluwalia | 0 | 28 | cousins in binary tree | 993 | 0.542 | Easy | 16,166 |
https://leetcode.com/problems/cousins-in-binary-tree/discuss/1398745/Python3-Sets-with-BFS | class Solution:
def isCousins(self, root: Optional[TreeNode], x: int, y: int) -> bool:
# Easiest way is breadth first search
def BFS(node, xy):
if node is None:
return False
queue = [node]
values = [node.val]
prevCount = 1
while queue:
for _ in range(prevCount):
curr = queue.pop(0)
values.pop(0)
if curr.left:
queue.append(curr.left)
values.append(curr.left.val)
if curr.right:
queue.append(curr.right)
values.append(curr.right.val)
if curr.left and curr.right and curr.left.val in xy and curr.right.val in xy:
return False
prevCount = len(queue)
if xy.issubset(set(values)):
return True
return False
return BFS(root, set([x,y])) | cousins-in-binary-tree | [Python3] Sets with BFS | whitehatbuds | 0 | 113 | cousins in binary tree | 993 | 0.542 | Easy | 16,167 |
https://leetcode.com/problems/cousins-in-binary-tree/discuss/1342676/Python-Simple-DFS-%2B-HashMap | class Solution:
def isCousins(self, root: TreeNode, x: int, y: int) -> bool:
depthParent = {} # key: node value. value: (depth, parent node value)
def getDepth(node, depth, parent=None):
if node:
getDepth(node.left, depth + 1, node)
getDepth(node.right, depth + 1, node)
depthParent[node.val] = (depth, parent.val if parent else None)
getDepth(root, 0)
return True if depthParent[x][0] == depthParent[y][0] and depthParent[x][1] != depthParent[y][1] else False | cousins-in-binary-tree | [Python] Simple DFS + HashMap | genefever | 0 | 72 | cousins in binary tree | 993 | 0.542 | Easy | 16,168 |
https://leetcode.com/problems/cousins-in-binary-tree/discuss/1255775/Python-traditional-recursive-solution | class Solution:
def isCousins(self, root: TreeNode, x: int, y: int) -> bool:
self.xDepth = float('inf')
self.yDepth = float('inf')
self.xParent = float('inf')
self.yParent = float('inf')
if not root:
return False
def helper(root, height,parent):
if not root:
return -1
helper(root.left, height + 1, root.val)
if root.val == x:
self.xDepth = height
self.xParent = parent
if root.val == y:
self.yDepth = height
self.yParent = parent
helper(root.right, height + 1,root.val)
helper(root,1, root.val)
if self.xDepth == self.yDepth and self.xParent != self.yParent:
return True
else:
return False | cousins-in-binary-tree | Python traditional recursive solution | dee7 | 0 | 115 | cousins in binary tree | 993 | 0.542 | Easy | 16,169 |
https://leetcode.com/problems/cousins-in-binary-tree/discuss/1068712/Python-Recursive | class Solution:
def __init__(self):
self.track = collections.defaultdict(tuple)
def dfs(self,root,level,parent):
if root == None:
return None
self.track[root.val] = (level,parent)
self.dfs(root.left,level+1,root.val)
self.dfs(root.right,level+1,root.val)
def isCousins(self, root: TreeNode, x: int, y: int) -> bool:
self.dfs(root,1,-1)
return self.track[x][0] == self.track[y][0] and self.track[x][1] != self.track[y][1] | cousins-in-binary-tree | Python Recursive | Akarsh_B | 0 | 47 | cousins in binary tree | 993 | 0.542 | Easy | 16,170 |
https://leetcode.com/problems/cousins-in-binary-tree/discuss/762750/Straightforward-Python-Solution-using-Stack-and-namedtuple | class Solution:
def isCousins(self, root: TreeNode, x: int, y: int) -> bool:
lookup = {}
stack = [(root, 0, None)]
while stack:
node, depth, parent = stack.pop()
if node.val in (x, y):
lookup[node.val] = (depth, parent)
if node.left:
stack.append((node.left, depth+1, node.val))
if node.right:
stack.append((node.right, depth+1, node.val))
if lookup[x][0] == lookup[y][0] and lookup[x][1] != lookup[y][1]:
return True | cousins-in-binary-tree | Straightforward Python Solution using Stack and namedtuple | parkershamblin | 0 | 68 | cousins in binary tree | 993 | 0.542 | Easy | 16,171 |
https://leetcode.com/problems/cousins-in-binary-tree/discuss/625660/Intuitive-approach-by-adding-depth-and-parent-information-to-each-node | class Solution:
def isCousins(self, root: TreeNode, x: int, y: int) -> bool:
# 0) Build depth,parent for each node
root.depth = 0
root.parent = -1
queue = [root]
n2n_dict = {}
while queue:
n = queue.pop(0)
n2n_dict[n.val] = n
if n.left:
n.left.depth = n.depth + 1
n.left.parent = n.val
queue.append(n.left)
if n.right:
n.right.depth = n.depth + 1
n.right.parent = n.val
queue.append(n.right)
# 1) Retrieve corresponding nodes and check their depth and parent attributes.
x_node = n2n_dict[x]
y_node = n2n_dict[y]
return x_node.depth == y_node.depth and x_node.parent != y_node.parent | cousins-in-binary-tree | Intuitive approach by adding depth and parent information to each node | puremonkey2001 | 0 | 37 | cousins in binary tree | 993 | 0.542 | Easy | 16,172 |
https://leetcode.com/problems/cousins-in-binary-tree/discuss/618475/Python-Recursive-and-Iterative-approaches | class Solution:
def isCousins(self, root: TreeNode, x: int, y: int) -> bool:
def dfs(node, parent, depth):
# don't need to traverse till the end if both x, y are traversed.
if not node or len(node_dict) == 2:
return
if node.val == x or node.val == y:
node_dict[node.val] = (parent, depth)
dfs(node.left, node, depth + 1)
dfs(node.right, node, depth + 1)
node_dict = defaultdict(tuple)
dfs(root, None, 0)
return node_dict[x][0] != node_dict[y][0] and node_dict[x][1] == node_dict[y][1] | cousins-in-binary-tree | [Python] Recursive and Iterative approaches | var42 | 0 | 117 | cousins in binary tree | 993 | 0.542 | Easy | 16,173 |
https://leetcode.com/problems/cousins-in-binary-tree/discuss/618475/Python-Recursive-and-Iterative-approaches | class Solution:
def isCousins(self, root: TreeNode, x: int, y: int) -> bool:
node_data = collections.defaultdict(list)
# tuple: (node, parent, depth)
queue = collections.deque([(root, None, 0)])
while queue:
if len(node_data) > 2:
break
node, parent, depth = queue.popleft()
if node.val == x or node.val == y:
node_data[node.val] = [parent, depth]
if node.left:
queue.append((node.left, node.val, depth + 1))
if node.right:
queue.append((node.right, node.val, depth + 1))
return node_data[x][0] != node_data[y][0] and node_data[x][1] == node_data[y][1] | cousins-in-binary-tree | [Python] Recursive and Iterative approaches | var42 | 0 | 117 | cousins in binary tree | 993 | 0.542 | Easy | 16,174 |
https://leetcode.com/problems/cousins-in-binary-tree/discuss/618273/PYTHON-3-Level-Order-Traversal-or-BFS-or-Dictionary | class Solution:
def isCousins(self, root: TreeNode, x: int, y: int) -> bool:
dic = {}
def levelOrder(node , level , parent):
if not node:
return 0
dic[node.val] = [level , parent]
levelOrder(node.left , level + 1 , node.val)
levelOrder(node.right , level + 1 , node.val)
levelOrder(root , 0 , -1)
return dic[x][0] == dic[y][0] and dic[x][1] != dic[y][1] | cousins-in-binary-tree | [PYTHON 3] Level Order Traversal | BFS | Dictionary | mohamedimranps | 0 | 37 | cousins in binary tree | 993 | 0.542 | Easy | 16,175 |
https://leetcode.com/problems/cousins-in-binary-tree/discuss/618131/Python3-DFS-Simplest-beating-88 | class Solution:
def isCousins(self, root: TreeNode, x: int, y: int) -> bool:
def dfs(parent,curr, level, x):
if not curr:
return []
if curr.val == x:
return [level, parent]
return dfs(curr, curr.left, level+1, x) + dfs(curr, curr.right, level+1, x)
level_x, parent_x = dfs(None, root, 0, x)
level_y, parent_y = dfs(None, root, 0, y)
return (level_x == level_y) and (parent_x != parent_y) | cousins-in-binary-tree | [Python3] DFS Simplest, beating 88% | purushottam3 | 0 | 25 | cousins in binary tree | 993 | 0.542 | Easy | 16,176 |
https://leetcode.com/problems/cousins-in-binary-tree/discuss/618053/python-97.22 | class Solution:
def isCousins(self, root: TreeNode, x: int, y: int) -> bool:
def fest(b,a,c,d):
if b:
if b.val==a:
return [c,d]
c=b.val
return fest(b.left,a,c,d+1) or fest(b.right,a,c,d+1)
return fest(root,x,False,0)[0]!=fest(root,y,False,0)[0] and fest(root,x,False,0)[1]==fest(root,y,False,0)[1] | cousins-in-binary-tree | python 97.22% | kisdown | 0 | 93 | cousins in binary tree | 993 | 0.542 | Easy | 16,177 |
https://leetcode.com/problems/cousins-in-binary-tree/discuss/297164/Python-faster-than-96-20-ms | class Solution(object):
def isCousins(self, root, x, y):
"""
:type root: TreeNode
:type x: int
:type y: int
:rtype: bool
"""
def f(root, v, p):
if root.val == v:
_d = 1
_p = p
return _d, _p
if root.left!=None:
l_d, l_p = f(root.left, v, root.val)
if l_d!=None:
return l_d+1, l_p
if root.right!=None:
r_d, r_p = f(root.right, v, root.val)
if r_d!=None:
return r_d+1, r_p
return None, p
_x = f(root, x, None)
_y = f(root, y, None)
return (_x[0] == _y[0]) and (_x[1] != _y[1]) | cousins-in-binary-tree | Python - faster than 96%, 20 ms | il_buono | 0 | 398 | cousins in binary tree | 993 | 0.542 | Easy | 16,178 |
https://leetcode.com/problems/rotting-oranges/discuss/1546489/Python-BFS%3A-Easy-to-understand-with-Explanation | class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
visit, curr = set(), deque()
# find all fresh and rotten oranges
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == 1:
visit.add((i, j))
elif grid[i][j] == 2:
curr.append((i, j))
result = 0
while visit and curr:
# BFS iteration
for _ in range(len(curr)):
i, j = curr.popleft() # obtain recent rotten orange
for coord in ((i-1, j), (i+1, j), (i, j-1), (i, j+1)):
if coord in visit: # check if adjacent orange is fresh
visit.remove(coord)
curr.append(coord)
result += 1
# check if fresh oranges remain and return accordingly
return -1 if visit else result | rotting-oranges | Python BFS: Easy-to-understand with Explanation | zayne-siew | 59 | 3,900 | rotting oranges | 994 | 0.525 | Medium | 16,179 |
https://leetcode.com/problems/rotting-oranges/discuss/280964/python-44-ms-faster-than-99.87 | class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
rotten = []
# build initial array of rotten oranges
rows = len(grid)
columns = len(grid[0])
for i in range(rows):
for j in range(columns):
if grid[i][j] == 2:
rotten.append((i, j))
# get unvisited neighbors of all rotten oranges
def add_neighbors(rotten):
neighbors = []
for i, j in rotten:
if i > 0 and grid[i - 1][j] == 1:
neighbors.append((i - 1, j))
grid[i-1][j] = 2
if j > 0 and grid[i][j - 1] == 1:
neighbors.append((i, j - 1))
grid[i][j-1] = 2
if i < rows - 1 and grid[i + 1][j] == 1:
neighbors.append((i + 1, j))
grid[i + 1][j] = 2
if j < columns - 1 and grid[i][j + 1] == 1:
neighbors.append((i, j + 1))
grid[i][j+1] = 2
return neighbors
minutes = 0
while (1):
rotten = add_neighbors(rotten)
if len(rotten) == 0:
break
minutes += 1
for i in range(rows):
for j in range(columns):
if grid[i][j] == 1:
return -1
return minutes | rotting-oranges | python 44 ms, faster than 99.87% | talistern21 | 13 | 2,300 | rotting oranges | 994 | 0.525 | Medium | 16,180 |
https://leetcode.com/problems/rotting-oranges/discuss/1786056/Python-3-(70ms)-or-BFS-Solution | class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
visit, curr = set(), deque()
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == 1:
visit.add((i, j))
elif grid[i][j] == 2:
curr.append((i, j))
result = 0
while visit and curr:
for _ in range(len(curr)):
i, j = curr.popleft()
for coord in ((i-1, j), (i+1, j), (i, j-1), (i, j+1)):
if coord in visit:
visit.remove(coord)
curr.append(coord)
result += 1
return -1 if visit else result | rotting-oranges | Python 3 (70ms) | BFS Solution | MrShobhit | 4 | 332 | rotting oranges | 994 | 0.525 | Medium | 16,181 |
https://leetcode.com/problems/rotting-oranges/discuss/1461265/Well-Explained-oror-Easy-approach-oror-94faster | class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
m,n,l = len(grid),len(grid[0]),0
rot = []
for i in range(m):
for j in range(n):
if grid[i][j]==2:
rot.append([i,j,l])
def convert(i,j,l):
nonlocal rot
if i<0 or i>=m or j<0 or j>=n or grid[i][j]==0:
return
if grid[i][j]==1:
rot.append([i,j,l+1])
grid[i][j]=0
while rot:
a,b,l = rot.pop(0)
grid[a][b] = 0
convert(a+1,b,l)
convert(a-1,b,l)
convert(a,b+1,l)
convert(a,b-1,l)
# Checking any 1 exist in grid
for r in grid:
if 1 in r:
return -1
return l | rotting-oranges | 📌📌 Well-Explained || Easy-approach || 94%faster 🐍 | abhi9Rai | 4 | 328 | rotting oranges | 994 | 0.525 | Medium | 16,182 |
https://leetcode.com/problems/rotting-oranges/discuss/424012/Python3-BFS-solution-with-comments-faster-than-99 | class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
row, col = len(grid), len(grid[0])
visited = set()
queue, new_queue = [], []
dirs = [(1, 0), (-1, 0), (0, 1), (0, -1)]
# first find all initial rotten oranges
for i in range(row):
for j in range(col):
if grid[i][j] == 2:
queue.append((i, j))
time = 0
# bfs
while queue:
node = queue.pop(0)
visited.add(node)
for dir in dirs:
new_row = node[0] + dir[0]
new_col = node[1] + dir[1]
if 0 <= new_row < row and 0 <= new_col < col and grid[new_row][new_col] == 1 and (new_row, new_col) not in visited:
grid[new_row][new_col] = 2
visited.add((new_row, new_col))
new_queue.append((new_row, new_col))
if len(queue) == 0 and len(new_queue) > 0:
time += 1
queue = new_queue
new_queue = []
# final check
for i in range(row):
for j in range(col):
if grid[i][j] == 1:
return -1
return time | rotting-oranges | Python3 BFS solution with comments faster than 99% | yanshengjia | 3 | 870 | rotting oranges | 994 | 0.525 | Medium | 16,183 |
https://leetcode.com/problems/rotting-oranges/discuss/2721269/Python-oror-BFS-oror-Beginners-friendly-oror-Easy | class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
q,ones = [],0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j]==2:
q.append([[i,j],0])
if grid[i][j]==1:
ones+=1
x = [-1,0,1,0]
y = [0,1,0,-1]
ans,cnt = 0,0
while q:
curr = q.pop(0)
for i in range(4):
nr = curr[0][0]+x[i]
nc = curr[0][1]+y[i]
t = curr[1]
ans = max(ans,t)
if nr>=0 and nr<len(grid) and nc>=0 and nc<len(grid[0]) and grid[nr][nc]==1:
q.append([[nr,nc],t+1])
grid[nr][nc] = 2
cnt+=1
if cnt!=ones:
return -1
return ans | rotting-oranges | Python || BFS || Beginners friendly || Easy | its_iterator | 2 | 124 | rotting oranges | 994 | 0.525 | Medium | 16,184 |
https://leetcode.com/problems/rotting-oranges/discuss/1634092/Python-BFS-Solution | class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
# add rotten oranges to a queue and keep track of fresh oranges
queue = []
num_fresh = 0
minute = 0
# initialize the queue with rotten oranges
for m in range(len(grid)):
for n in range(len(grid[0])):
if grid[m][n] == 2:
queue.append((m, n))
elif grid[m][n] == 1:
num_fresh += 1
if num_fresh == 0:
return 0 # no fresh oranges to begin with
if len(queue) == 0:
return -1 # no rotten oranges to begin with
while queue:
# BFS == level order traversal (same technique!)
num_rotten = len(queue)
minute += 1
for i in range(num_rotten):
(m, n) = queue.pop(0) # get the next rotten orange from the queue
# get four directions in the grid
left = 0 if n == 0 else n - 1
right = len(grid[0]) - 1 if n == len(grid[0]) - 1 else n + 1
up = 0 if m == 0 else m - 1
down = len(grid) - 1 if m == len(grid) - 1 else m + 1
# check if the neighbors are rotten
if grid[m][left] == 1:
grid[m][left] = 2
num_fresh -= 1
queue.append((m, left))
if grid[m][right] == 1:
grid[m][right] = 2
num_fresh -= 1
queue.append((m, right))
if grid[up][n] == 1:
grid[up][n] = 2
num_fresh -= 1
queue.append((up, n))
if grid[down][n] == 1:
grid[down][n] = 2
num_fresh -= 1
queue.append((down, n))
# if there are fresh oranges remaining, return -1
if num_fresh > 0:
return -1
return minute - 1 | rotting-oranges | Python BFS Solution | dahal_ | 2 | 152 | rotting oranges | 994 | 0.525 | Medium | 16,185 |
https://leetcode.com/problems/rotting-oranges/discuss/1546575/Python-or-90-time-and-space-or-2-ways | class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
minutes = 0
m, n = len(grid), len(grid[0])
visited = set()
while True:
changed = False
rotten = []
for i in range(m):
for j in range(n):
if grid[i][j] == 2 and (i,j) not in visited:
rotten.append( [i,j] )
visited.add( (i,j) )
for i,j in rotten:
if i-1 >= 0 and grid[i-1][j] == 1:
grid[i-1][j] = 2
changed = True
if i+1 < m and grid[i+1][j] == 1:
grid[i+1][j] = 2
changed = True
if j-1 >= 0 and grid[i][j-1] == 1:
grid[i][j-1] = 2
changed = True
if j+1 < n and grid[i][j+1] == 1:
grid[i][j+1] = 2
changed = True
minutes += 1
if not changed:
if 1 in sum(grid, []):
return -1
return minutes-1 | rotting-oranges | Python | 90 % time and space | 2 ways | mshanker | 2 | 59 | rotting oranges | 994 | 0.525 | Medium | 16,186 |
https://leetcode.com/problems/rotting-oranges/discuss/1546575/Python-or-90-time-and-space-or-2-ways | class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
minutes = 0
m, n = len(grid), len(grid[0])
rotten = []
fresh = []
for i in range(m):
for j in range(n):
if grid[i][j] == 2:
rotten.append( [i,j] )
if grid[i][j] == 1:
fresh.append([i,j])
while True:
changed = []
for i,j in rotten:
for k in [[i-1, j], [i, j-1], [i+1, j], [i, j+1]]:
if k in fresh:
changed.append(k)
fresh.remove(k)
minutes += 1
if not changed:
return -1 if fresh else minutes-1
rotten = changed | rotting-oranges | Python | 90 % time and space | 2 ways | mshanker | 2 | 59 | rotting oranges | 994 | 0.525 | Medium | 16,187 |
https://leetcode.com/problems/rotting-oranges/discuss/1437571/Python-Clean-and-concise-BFS-solution | class Solution(object):
def orangesRotting(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
rows = len(grid)
if rows == 0: return -1
cols = len(grid[0])
# Track fresh oranges
fresh = 0
# Track bad oranges lvl by lvl
rotten = deque()
minutes_passed = 0
directions = [[-1, 0], [1, 0], [0, -1], [0, 1]]
# Traverse grid and update rotten
for r in range(rows):
for c in range(cols):
if grid[r][c] == 2: rotten.append((r,c))
elif grid[r][c] == 1: fresh += 1
# BFS
while rotten and fresh > 0:
# Each lvl is one minute
minutes_passed += 1
for _ in range(len(rotten)):
x, y = rotten.popleft()
# Visit neighbors
for dx, dy in directions:
new_x, new_y = x + dx, y + dy
# Ignore out of bounds
if new_x < 0 or new_x == rows or new_y < 0 or new_y == cols:
continue
# Ignore empty or visited
if grid[new_x][new_y] == 0 or grid[new_x][new_y] == 2:
continue
# Mark as rotten
grid[new_x][new_y] = 2
# Update good
fresh -= 1
rotten.append((new_x, new_y))
return minutes_passed if fresh == 0 else -1 | rotting-oranges | [Python] Clean and concise BFS solution | jsanchez78 | 2 | 196 | rotting oranges | 994 | 0.525 | Medium | 16,188 |
https://leetcode.com/problems/rotting-oranges/discuss/2643520/Python-BFS | class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
fresh,time=0,0
q=deque()
R,C=len(grid),len(grid[0])
for r in range(R):
for c in range(C):
if grid[r][c]==1:
fresh+=1
if grid[r][c]==2:
q.append([r,c])
directions=[[0,1],[0,-1],[1,0],[-1,0]]
while q and fresh>0:
for i in range(len(q)):
r,c=q.popleft()
for dr,dc in directions:
rows,cols=dr+r,dc+c
if rows<0 or rows==len(grid) or cols<0 or cols==len(grid[0]) or grid[rows][cols]!=1:
continue
grid[rows][cols]=2
q.append([rows,cols])
fresh-=1
time+=1
return time if fresh==0 else -1 | rotting-oranges | [Python] BFS | gauravtiwari91 | 1 | 35 | rotting oranges | 994 | 0.525 | Medium | 16,189 |
https://leetcode.com/problems/rotting-oranges/discuss/2560361/Python-Solution-with-comments-or-Using-BFS-or-faster-than-96-or-O(n.m) | class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
q = deque()
time, fresh = 0, 0
R = len(grid)
C = len(grid[0])
for r in range(R):
for c in range(C):
if grid[r][c] == 1:
fresh += 1 #get count of all fresh oranges
if grid[r][c] == 2 :
q.append([r, c]) #Add the rotting oranges to the queue
while q and fresh > 0: #checking if no rotten left and no fresh left
for i in range(len(q)): #adding the adjacent ones to the queue
r, c = q.popleft()
for dr, dc in [[1, 0],[-1, 0],[0, 1],[0, -1]]:
row = dr + r
col = dc + c
if row < 0 or col < 0 or row == R or col == C or grid[row][col] != 1 : #grid is not a fresh orange
continue
grid[row][col] = 2 #marking it as rotten
q.append([row, col]) #adding it to queue as its rotten
fresh -= 1 #decrementing the count of rotten ones
time += 1
return time if fresh == 0 else -1 | rotting-oranges | Python Solution with comments | Using BFS | faster than 96% | O(n.m) | nikhitamore | 1 | 53 | rotting oranges | 994 | 0.525 | Medium | 16,190 |
https://leetcode.com/problems/rotting-oranges/discuss/2474675/Python-Accurate-Solution-oror-Documented | class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
q = collections.deque()
count = 0 # count the fresh oranges
# add all rotten-orange cell co-ordinates into queue
for x in range(len(grid)):
for j in range(len(grid[0])):
if grid[x][j] == 2: # if rotten orange cell,
q.append((x, j, 0)) # - add coordinate with level 0
elif grid[x][j] == 1: # if fresh orange cell,
count += 1 # - increment count of fresh oranges
level = 0 # level counter
dirs = [(0, 1), (1, 0), (0, -1), (-1, 0)] # 4 directions
while q: # while queue not empty
x, y, level = q.popleft() # take rotten-orange cell from queue
for dx, dy in dirs:
i, j = x+dx, y+dy
if not (0 <= i < len(grid) and # if out of bounds
0 <= j < len(grid[x])): # - do nothing
continue
if grid[i][j] == 1: # if fresh orange cell, it will become rotten
count -= 1 # decrement fresh orange count
grid[i][j] = 2 # mark the cell as rotten
q.append((i, j, level+1)) # add new rotten cell with current-level+1
# if count become 0, means all fresh oranges become rotten, so return level, else -1 (impossible)
return level if count == 0 else -1 | rotting-oranges | [Python] Accurate Solution || Documented | Buntynara | 1 | 58 | rotting oranges | 994 | 0.525 | Medium | 16,191 |
https://leetcode.com/problems/rotting-oranges/discuss/2152846/python-3-oror-simple-bfs | class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
fresh = 0
q = collections.deque()
for i, row in enumerate(grid):
for j, orange in enumerate(row):
if orange == 1:
fresh += 1
elif orange == 2:
q.append((i, j, 0))
if not fresh:
return 0
directions = ((-1, 0), (1, 0), (0, -1), (0, 1))
while q:
i, j, mins = q.popleft()
mins += 1
for di, dj in directions:
newI, newJ = i + di, j + dj
if (newI == -1 or newI == m or
newJ == -1 or newJ == n or
grid[newI][newJ] != 1):
continue
grid[newI][newJ] = 2
fresh -= 1
q.append((newI, newJ, mins))
return mins - 1 if not fresh else -1 | rotting-oranges | python 3 || simple bfs | dereky4 | 1 | 173 | rotting oranges | 994 | 0.525 | Medium | 16,192 |
https://leetcode.com/problems/rotting-oranges/discuss/1986644/Python3-Runtime%3A-46ms-97.35-Memory%3A-13.8mb-92.44 | class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
if len(grid) == 0:
return -1
rottenOranges = list()
freshOranges = set()
for r in range(len(grid)):
for c in range(len(grid[r])):
if grid[r][c] == 1:
freshOranges.add((r, c))
elif grid[r][c] == 2:
rottenOranges.append((r, c))
timeToBeRotten = 0
while len(rottenOranges) > 0 and len(freshOranges) > 0:
for i in range(len(rottenOranges)):
r, c = rottenOranges.pop(0)
DIRS = (
(r - 1, c),
(r + 1, c),
(r, c + 1),
(r, c - 1),
)
for cordination in DIRS:
if cordination in freshOranges:
freshOranges.remove(cordination)
rottenOranges.append(cordination)
timeToBeRotten += 1
return timeToBeRotten if len(freshOranges) == 0 else -1 | rotting-oranges | Python3 Runtime: 46ms 97.35% Memory: 13.8mb 92.44% | arshergon | 1 | 57 | rotting oranges | 994 | 0.525 | Medium | 16,193 |
https://leetcode.com/problems/rotting-oranges/discuss/1930388/PYTHON-DFS | class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
column_length = len(grid[0])
row_length = len(grid)
initial_rotten = []
for col in range(column_length):
for row in range(row_length):
if grid[row][col] == 2:
initial_rotten.append([(row, col)])
max_minutes = 0
stack = [] # [[(0, 0), (1, 0)], [(4, 5)]]
for rotten in initial_rotten:
stack.append(rotten)
while stack:
current = stack.pop() # [(0, 0), (1, 0)]
max_minutes = max(max_minutes, len(current) - 1) # First orange was already rotten.
current_orange = current[-1] # (1, 0)
neighbors = self.find_fresh_oranges(current_orange, grid) # [(0, 0), (1, 0), ...]
for neigh in neighbors: # Append the new orange location, and then rot that orange
row, col = neigh
to_stack = current[:]
to_stack.append((row, col))
stack.insert(0, to_stack)
grid[row][col] = 2 # Rotting!
for col in range(column_length):
for row in range(row_length):
if grid[row][col] == 1:
return -1
return max_minutes
def find_fresh_oranges(self, current_orange, grid):
row, col = current_orange
column_length = len(grid[0])
row_length = len(grid)
in_bound_positions = [] # [(0, 0), (1, 0), ...]
to_return = [] # [(0, 0), (1, 0), ...]
positions = [
(1, 0),
(0, 1),
(-1, 0),
(0, -1)
]
for iy, ix in positions:
new_iy = iy + row
new_ix = ix + col
if 0 <= new_iy < row_length and 0 <= new_ix < column_length:
in_bound_positions.append((new_iy, new_ix))
for row, col in in_bound_positions:
if grid[row][col] == 1: # 1 is the fresh orange
to_return.append((row, col))
return to_return | rotting-oranges | [PYTHON] DFS | authier | 1 | 242 | rotting oranges | 994 | 0.525 | Medium | 16,194 |
https://leetcode.com/problems/rotting-oranges/discuss/1337575/easy-python | class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
fresh=[]
rotten=[]
newrotten=[]
row=len(grid)
col=len(grid[0])
for i in range(row):
for j in range(col):
if grid[i][j]==1:
fresh.append((i,j))
elif grid[i][j]==2:
rotten.append((i,j))
directions=[(1,0),(0,1),(0,-1),(-1,0)]
mins=0
while len(fresh)>0 and len(rotten)>0:
for i,j in rotten:
for k,l in directions:
if 0<=i+k<row and 0<=j+l<col:
if (i+k,j+l) in fresh:
fresh.remove((i+k,j+l))
newrotten.append((i+k,j+l))
rotten=newrotten
newrotten=[]
mins+=1
if len(fresh)==0:
return mins
else:
return -1 | rotting-oranges | easy python | pavanto3d | 1 | 43 | rotting oranges | 994 | 0.525 | Medium | 16,195 |
https://leetcode.com/problems/rotting-oranges/discuss/749751/Easy-Python-BFS-Solution-beats-99-with-Description-and-Comments! | class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
rows = len(grid)
cols = len(grid[0])
q = collections.deque([])
oranges = 0
# Populate our deque with the rotting orange locations and get orange count.
for row in range(rows):
for col in range(cols):
if grid[row][col] == 1:
oranges += 1
elif grid[row][col] == 2:
q.append((row, col, 0))
# Our possible directions to move through the grid.
directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
# Keep our highest observed time (which will in fact be the min time taken).
minutes = 0
# While we have items in our q or we run out of oranges.
while q and oranges:
# Pop our current info off the queue
row, col, mins = q.popleft()
# Look for our possible moves from our current location using our given directions.
for r, c in directions:
nr = row + r
nc = col + c
# Validate that the new location would be on the board and that the location contains an orange.
if nr >= 0 and nr < rows and nc >= 0 and nc < cols and grid[nr][nc] == 1:
# If it meets our criteria then we'll mark it rotten, deduct 1 from our orange count, record mins, and add to q.
grid[nr][nc] = 2
oranges -= 1
minutes = max(minutes, mins+1)
q.append((nr, nc, mins + 1))
# We return our minutes if we have removed all fresh oranges else -1 because we know not all oranges could rot.
return minutes if oranges == 0 else -1 | rotting-oranges | Easy Python BFS Solution beats 99% with Description and Comments! | Pythagoras_the_3rd | 1 | 153 | rotting oranges | 994 | 0.525 | Medium | 16,196 |
https://leetcode.com/problems/rotting-oranges/discuss/433979/Python3-BFS-faster-than-90 | class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
numMinutes = 0
twosPositions = []
zerosPositions = []
rows = len(grid)
cols = len(grid[0])
for row in range(rows):
for col in range(cols):
if grid[row][col] == 0:
zerosPositions.append((row, col))
if grid[row][col] == 2:
twosPositions.append((row, col))
didRotOranges = True
while len(twosPositions) + len(zerosPositions) < (rows * cols) and didRotOranges:
didRotOranges = False
rottingOranges = []
for item in twosPositions:
row = item[0]
col = item[1]
if row > 0 and grid[row - 1][col] == 1:
grid[row - 1][col] = 2
rottingOranges.append((row - 1, col))
if row < rows - 1 and grid[row + 1][col] == 1:
grid[row + 1][col] = 2
rottingOranges.append((row + 1, col))
if col > 0 and grid[row][col - 1] == 1:
grid[row][col - 1] = 2
rottingOranges.append((row, col - 1))
if col < cols - 1 and grid[row][col + 1] == 1:
grid[row][col + 1] = 2
rottingOranges.append((row, col + 1))
if len(rottingOranges) > 0:
didRotOranges = True
twosPositions.extend(rottingOranges)
numMinutes += 1
return numMinutes if len(twosPositions) + len(zerosPositions) == (rows * cols) else -1 | rotting-oranges | Python3 --BFS-- faster than 90% | sishar4 | 1 | 222 | rotting oranges | 994 | 0.525 | Medium | 16,197 |
https://leetcode.com/problems/rotting-oranges/discuss/382204/Solution-in-Python-3-(beats-~99)-(nine-lines) | class Solution:
def orangesRotting(self, G: List[List[int]]) -> int:
M, N, S, E, c = len(G), len(G[0]), [], sum(G,[]).count(1), 0
R = [(i,j) for i,j in itertools.product(range(M),range(N)) if G[i][j] == 2]
while E != 0:
for [i,j] in R:
for a,b in (i-1,j),(i,j+1),(i+1,j),(i,j-1):
if 0 <= a < M and 0 <= b < N and G[a][b] == 1: G[a][b], E, _ = 2, E - 1, S.append([a,b])
if len(S) == 0: return -1
R, S, c = S, [], c + 1
return c
- Junaid Mansuri
(LeetCode ID)@hotmail.com | rotting-oranges | Solution in Python 3 (beats ~99%) (nine lines) | junaidmansuri | 1 | 647 | rotting oranges | 994 | 0.525 | Medium | 16,198 |
https://leetcode.com/problems/rotting-oranges/discuss/2839563/Easiest-Python-Solution-oror-Fully-Explained-with-COMMENTS | class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
# number of rows
rows = len(grid)
if rows == 0: # check if grid is empty
return -1
# number of columns
cols = len(grid[0])
# keep track of fresh oranges
fresh_cnt = 0
# queue with rotten oranges (for BFS)
rotten = []
# visit each cell in the grid
for r in range(rows):
for c in range(cols):
if grid[r][c] == 2:
# add the rotten orange coordinates to the queue
rotten.append((r, c))
elif grid[r][c] == 1:
# update fresh oranges count
fresh_cnt += 1
# keep track of minutes passed.
minutes_passed = 0
# If there are rotten oranges in the queue and there are still fresh oranges in the grid keep looping
while rotten and fresh_cnt > 0:
# update the number of minutes passed
# it is safe to update the minutes by 1, since we visit oranges level by level in BFS traversal.
minutes_passed += 1
# process rotten oranges on the current level
for _ in range(len(rotten)):
x, y = rotten.pop(0)
# visit all the adjacent cells
for dx, dy in [(1,0), (-1,0), (0,1), (0,-1)]:
# calculate the coordinates of the adjacent cell
xx, yy = x + dx, y + dy
# ignore the cell if it is out of the grid boundary
if xx < 0 or xx == rows or yy < 0 or yy == cols:
continue
# ignore the cell if it is empty '0' or visited before '2'
if grid[xx][yy] == 0 or grid[xx][yy] == 2:
continue
# update the fresh oranges count
fresh_cnt -= 1
# mark the current fresh orange as rotten
grid[xx][yy] = 2
# add the current rotten to the queue
rotten.append((xx, yy))
# return the number of minutes taken to make all the fresh oranges to be rotten
# return -1 if there are fresh oranges left in the grid (there were no adjacent rotten oranges to make them rotten)
return minutes_passed if fresh_cnt == 0 else -1
# minute=0
# for i in range(len(grid)):
# for j in range(len(grid[0])):
# if (i<len(grid)-1 or j<len(grid[0])-1) and grid[i][j]==2:
# if (grid[i+1][j]==1 or grid[i][j+1]==1):
# if grid[i+1][j]==1:
# grid[i+1][j]=2
# if grid[i][j+1]==1:
# grid[i][j+1]=2
# minute+=1
# if grid[i][j]==1:
# if i>0 and grid[i-1][j]==2:
# grid[i][j]=2
# minute+=1
# elif j>0 and grid[i][j-1]==2:
# grid[i][j]=2
# minute+=1
# elif i<len(grid)-1 and grid[i+1][j]==2:
# grid[i][j]=2
# minute+=1
# elif j<len(grid[0])-1 and grid[i][j+1]==2:
# grid[i][j]=2
# minute+=1
# return minute | rotting-oranges | ✔Easiest Python Solution || 💯Fully Explained with COMMENTS🆗💭 | AdityaTrivedi88 | 0 | 1 | rotting oranges | 994 | 0.525 | Medium | 16,199 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.