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/lemonade-change/discuss/460465/Python%3A128-ms-99.9212.7-MB-100.00-super-easy-to-understand-with-explanation | class Solution:
def lemonadeChange(self, bills: List[int]) -> bool:
# meet 20 , give 10 prior to 5.
bill_5, bill_10, bill_20 = 0, 0, 0
for bill in bills:
if bill == 5:
bill_5 += 1
elif bill == 10:
bill_10 += 1
bill_5 -= 1
elif bill == 20:
if bill_10:
bill_10 -= 1
bill_5 -= 1
else:
bill_5 -= 3
if bill_5 < 0:
return False
return True | lemonade-change | Python:128 ms, 99.92%/12.7 MB, 100.00%, super easy to understand, with explanation | SilverCHN | 0 | 103 | lemonade change | 860 | 0.528 | Easy | 14,000 |
https://leetcode.com/problems/score-after-flipping-matrix/discuss/940701/Python3-Greedy-O(MN) | class Solution:
def matrixScore(self, A: List[List[int]]) -> int:
m, n = len(A), len(A[0])
for i in range(m):
if A[i][0] == 0:
for j in range(n): A[i][j] ^= 1
for j in range(n):
cnt = sum(A[i][j] for i in range(m))
if cnt < m - cnt:
for i in range(m): A[i][j] ^= 1
return sum(int("".join(map(str, A[i])), 2) for i in range(m)) | score-after-flipping-matrix | [Python3] Greedy O(MN) | ye15 | 14 | 385 | score after flipping matrix | 861 | 0.751 | Medium | 14,001 |
https://leetcode.com/problems/score-after-flipping-matrix/discuss/843685/Python-3-or-Greedy-and-Optimization-(5-lines)-or-Explanation | class Solution:
def matrixScore(self, A: List[List[int]]) -> int:
m, n = len(A), len(A[0])
col = [0] * n # a list to count 1 in each column
for i in range(m):
for j in range(n-1, -1, -1): # start from the right, so we can use A[i][0] as a reference
A[i][j] = (1-A[i][j]) if not A[i][0] else A[i][j] # flip row if start of this row is 0
col[j] += A[i][j]
for j in range(1, n): # flip column when necessary
if (m % 2 and col[j] <= m // 2) or (not m % 2 and col[j] < m // 2):
for i in range(m): A[i][j] = 1-A[i][j]
return sum(sum(2**(n-1-j) * A[i][j] for j in range(n)) for i in range(m)) # calculate the sum | score-after-flipping-matrix | Python 3 | Greedy & Optimization (5 lines) | Explanation | idontknoooo | 4 | 373 | score after flipping matrix | 861 | 0.751 | Medium | 14,002 |
https://leetcode.com/problems/score-after-flipping-matrix/discuss/843685/Python-3-or-Greedy-and-Optimization-(5-lines)-or-Explanation | class Solution:
def matrixScore(self, A: List[List[int]]) -> int:
m, n, ans = len(A), len(A[0]), 0
for c in range(n):
col = sum(A[r][c] == A[r][0] for r in range(m))
ans += max(col, m-col) * 2 ** (n-1-c)
return ans | score-after-flipping-matrix | Python 3 | Greedy & Optimization (5 lines) | Explanation | idontknoooo | 4 | 373 | score after flipping matrix | 861 | 0.751 | Medium | 14,003 |
https://leetcode.com/problems/score-after-flipping-matrix/discuss/1310161/Python3-O(m*n)-step-by-step-illustration | class Solution:
def matrixScore(self, grid: List[List[int]]) -> int:
rows = len(grid)
cols = len(grid[0])
ones = [0] * cols
# flip rows
for r in range(rows):
row = grid[r]
flip = row[0] == 0
for c in range(cols):
if flip:
row[c] = 1 if row[c] == 0 else 0 # flip
if row[c] == 1:
ones[c] += 1 # count number of 1s
half = rows / 2
# flip cols
for c in range(cols):
if ones[c] >= half:
continue
for r in range(rows):
grid[r][c] = 1 if grid[r][c] == 0 else 0 # flip
# calculate
res = 0
for r in range(rows):
for c in range(cols):
res += grid[r][c] * 2 ** (cols - c - 1)
return res | score-after-flipping-matrix | Python3 O(m*n) step by step illustration | iameugenejo | 2 | 74 | score after flipping matrix | 861 | 0.751 | Medium | 14,004 |
https://leetcode.com/problems/score-after-flipping-matrix/discuss/2777828/Simple-Approach-beats-97-O(n) | class Solution:
def matrixScore(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
ans = [0] * n
for r in grid:
if r[0]:
for i in range(n):
ans[i] += r[i]
else:
for i in range(n):
ans[i] += 1-r[i]
ret = 0
for i in range(n):
ret += max(ans[-1-i], m-ans[-1-i]) * (1<<i)
return ret | score-after-flipping-matrix | Simple Approach beats 97% O(n) | Mencibi | 1 | 46 | score after flipping matrix | 861 | 0.751 | Medium | 14,005 |
https://leetcode.com/problems/score-after-flipping-matrix/discuss/1832391/WEEB-EXPLAINS-PYTHONC%2B%2B-(GREEDY-SOLUTION) | class Solution:
def matrixScore(self, grid: List[List[int]]) -> int:
row, col = len(grid), len(grid[0])
for x in range(row):
if grid[x][0] == 0:
for y in range(col):
if grid[x][y] == 1:
grid[x][y] = 0
else:
grid[x][y] = 1
for y in range(col):
onesCount = 0
for x in range(row):
if grid[x][y] == 1:
onesCount += 1
if onesCount < row - onesCount: # less ones than zeros
for x in range(row):
if grid[x][y] == 1:
grid[x][y] = 0
else:
grid[x][y] = 1
result = 0
for i in range(row):
for j in range(col):
if grid[i][j] == 1:
result += 2**(col-j-1)
return result | score-after-flipping-matrix | WEEB EXPLAINS PYTHON/C++ (GREEDY SOLUTION) | Skywalker5423 | 1 | 53 | score after flipping matrix | 861 | 0.751 | Medium | 14,006 |
https://leetcode.com/problems/score-after-flipping-matrix/discuss/1656780/Python3-oror-O(m*n)-time-oror-O(1)-space-oror-With-explanation | class Solution:
def matrixScore(self, grid: List[List[int]]) -> int:
rows = len(grid)
cols = len(grid[0])
# for rows MSB is importnat
for r in range(rows):
if grid[r][0] == 0:
for c in range(cols):
if grid[r][c] == 0:
grid[r][c] = 1
else:
grid[r][c] = 0
# for cols no of ones are important
for c in range(cols):
zero = 0
for r in range(rows):
if grid[r][c] == 0:
zero += 1
ones = rows - zero
if zero > ones:
for r in range(rows):
if grid[r][c] == 0:
grid[r][c] = 1
else:
grid[r][c] = 0
score = 0
for r in range(rows):
mul = 1
for c in range(cols-1,-1,-1):
score += (grid[r][c] * mul)
mul *= 2
return score
#TC -->O(m*n)
#SC --> O(n) | score-after-flipping-matrix | Python3 || O(m*n) time || O(1) space || With explanation | s_m_d_29 | 1 | 84 | score after flipping matrix | 861 | 0.751 | Medium | 14,007 |
https://leetcode.com/problems/score-after-flipping-matrix/discuss/2434798/Python3-or-Greedy | class Solution:
def matrixScore(self, grid: List[List[int]]) -> int:
def flipRow(row):
for ind,c in enumerate(row):
row[ind]^=1
def binaryToDecimal(row):
val=0
for i in range(n-1,-1,-1):
val+=(2**(n-i-1))*row[i]
return val
m,n=len(grid),len(grid[0])
ans=0
for r in range(m):
if grid[r][0]==0:
flipRow(grid[r])
z_cnt=[0 for i in range(n)]
for c in range(n):
for r in range(m):
if grid[r][c]==0:
z_cnt[c]+=1
for c in range(n):
if z_cnt[c]>m//2:
for r in range(m):
grid[r][c]^=1
for r in grid:
ans+=binaryToDecimal(r)
return ans | score-after-flipping-matrix | [Python3] | Greedy | swapnilsingh421 | 0 | 10 | score after flipping matrix | 861 | 0.751 | Medium | 14,008 |
https://leetcode.com/problems/score-after-flipping-matrix/discuss/2348155/Moderately-fast-python-solution-easy-to-understand | class Solution:
def calcScore(self):
score = 0
for row in self.grid:
for i in range(self.width):
score += row[i] * (2 ** (self.width - i - 1))
return score
def flipRow(self, row):
for i in range(self.width):
self.grid[row][i] = int(not self.grid[row][i])
def flipCol(self, col):
for i in range(self.height):
self.grid[i][col] = int(not self.grid[i][col])
def colSum(self, col):
total = 0
for i in range(self.height):
total += self.grid[i][col]
return total
def matrixScore(self, grid: List[List[int]]) -> int:
self.grid = grid
self.height = len(grid)
self.width = len(grid[0])
for r in range(self.height):
if not self.grid[r][0]:
if not self.grid[r][0]:
self.flipRow(r)
for c in range(1, self.width):
colSum = self.colSum(c)
if colSum < ceil(self.height/2):
self.flipCol(c)
return self.calcScore() | score-after-flipping-matrix | Moderately fast python solution easy to understand | complete_noob | 0 | 36 | score after flipping matrix | 861 | 0.751 | Medium | 14,009 |
https://leetcode.com/problems/score-after-flipping-matrix/discuss/1500420/Python-O(mn)-time-O(1)-space%3A-when-to-flip-over | class Solution(object):
def matrixScore(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
m, n = len(grid), len(grid[0])
for i in range(m):
if grid[i][0] == 0:
for j in range(n):
grid[i][j] = 1-grid[i][j]
for j in range(n):
s = 0
for i in range(m):
s += grid[i][j]
if s <= (m-1)//2:
for i in range(m):
grid[i][j] = 1-grid[i][j]
res = 0
for j in range(n):
s = 0
for i in range(m):
s += grid[i][j]
res += 2**(n-1-j)*s
return res | score-after-flipping-matrix | Python O(mn) time, O(1) space: when to flip over? | byuns9334 | 0 | 116 | score after flipping matrix | 861 | 0.751 | Medium | 14,010 |
https://leetcode.com/problems/score-after-flipping-matrix/discuss/1424074/python-3-solution-oror-85-fast-oror | class Solution:
def matrixScore(self, grid: List[List[int]]) -> int:
m=len(grid)#rows
n=len(grid[0])#col
#checking if ist element in a row is 1 because that would maximise the sum in binary
for i in range(m):
if grid[i][0]==0:
for j in range(n):
if grid[i][j]==0:
grid[i][j]=1
else:
grid[i][j]=0
#the no of 1s in a column should be greator than no of 0s to maximise the sum
for j in range(n):
zero_col_count = 0
for i in range(m):
if not grid[i][j]:
zero_col_count += 1
if zero_col_count > m // 2:
for k in range(len(grid)):
grid[k][j] = 0 if grid[k][j] else 1
#converting the list to a string of binary digits and then converting it into integer and adding all lists present in grid to find the final sum
ans=0
for i in range(len(grid)):
grid[i]=map(str,grid[i])
str1="0b"+"".join(grid[i])
int1=int(str1,2)
ans=ans+int1
return ans | score-after-flipping-matrix | python 3 solution || 85% fast || | minato_namikaze | 0 | 95 | score after flipping matrix | 861 | 0.751 | Medium | 14,011 |
https://leetcode.com/problems/score-after-flipping-matrix/discuss/1048438/Python-O(M*N)-Most-Simple-Solution | class Solution:
def matrixScore(self, A: List[List[int]]) -> int:
for row in range(len(A)):
if A[row][0] == 0:
for col in range(len(A[0])):
A[row][col] ^= 1
for col in range(1, len(A[0])):
counts = 0
for row in range(len(A)):
if A[row][col] == 0:
counts += 1
if counts > len(A)//2:
for row in range(len(A)):
A[row][col] ^= 1
res = 0
for row in range(len(A)):
for col in range(len(A[0])):
A[row][col] = str(A[row][col])
res += int("".join(A[row]),2)
return res | score-after-flipping-matrix | Python O(M*N) Most Simple Solution | IKM98 | 0 | 92 | score after flipping matrix | 861 | 0.751 | Medium | 14,012 |
https://leetcode.com/problems/score-after-flipping-matrix/discuss/891365/Python3-36ms-w-comments | class Solution:
def matrixScore(self, A: List[List[int]]) -> int:
# best solution always has 1s in first column.
Av2 = []
for row in A:
if row[0]==0:
Av2.append([1 if i==0 else 0 for i in row])
else:
Av2.append(row)
scores = [0 for _ in A[0]] # ith entry => ith pos'n in each row
for row in Av2:
for pos,entry in enumerate(row):
scores[pos] += entry
score = 0
scores = scores[::-1] # because we want to multiply up.
multiplier = 1
l = len(A)
for i in scores:
print(i)
score += multiplier*max(i,l-i) # find the max so we know whether to switch the column or not
multiplier *= 2
return score | score-after-flipping-matrix | Python3 36ms w/ comments | TomFlatters | 0 | 74 | score after flipping matrix | 861 | 0.751 | Medium | 14,013 |
https://leetcode.com/problems/score-after-flipping-matrix/discuss/462937/Python-3-(two-lines)-(beats-100)-(24-ms)-(With-Explanation) | class Solution:
def matrixScore(self, G: List[List[int]]) -> int:
G, M, N = list(zip(*[[b^g[0]^1 for b in g] for g in G])), len(G), len(G[0])
return sum(max(sum(g),M-sum(g))*2**(N-i-1) for i,g in enumerate(G))
- Junaid Mansuri
- Chicago, IL | score-after-flipping-matrix | Python 3 (two lines) (beats 100%) (24 ms) (With Explanation) | junaidmansuri | 0 | 178 | score after flipping matrix | 861 | 0.751 | Medium | 14,014 |
https://leetcode.com/problems/shortest-subarray-with-sum-at-least-k/discuss/1515369/Python3-binary-search | class Solution:
def shortestSubarray(self, nums: List[int], k: int) -> int:
loc = {0: -1}
stack = [0] # increasing stack
ans, prefix = inf, 0
for i, x in enumerate(nums):
prefix += x
ii = bisect_right(stack, prefix - k)
if ii: ans = min(ans, i - loc[stack[ii-1]])
loc[prefix] = i
while stack and stack[-1] >= prefix: stack.pop()
stack.append(prefix)
return ans if ans < inf else -1 | shortest-subarray-with-sum-at-least-k | [Python3] binary search | ye15 | 4 | 350 | shortest subarray with sum at least k | 862 | 0.261 | Hard | 14,015 |
https://leetcode.com/problems/shortest-subarray-with-sum-at-least-k/discuss/1515369/Python3-binary-search | class Solution:
def shortestSubarray(self, nums: List[int], k: int) -> int:
ans = inf
queue = deque([(-1, 0)])
prefix = 0
for i, x in enumerate(nums):
prefix += x
while queue and prefix - queue[0][1] >= k: ans = min(ans, i - queue.popleft()[0])
while queue and queue[-1][1] >= prefix: queue.pop()
queue.append((i, prefix))
return ans if ans < inf else -1 | shortest-subarray-with-sum-at-least-k | [Python3] binary search | ye15 | 4 | 350 | shortest subarray with sum at least k | 862 | 0.261 | Hard | 14,016 |
https://leetcode.com/problems/shortest-subarray-with-sum-at-least-k/discuss/2544207/Python3-Solution-or-O(N) | class Solution:
def shortestSubarray(self, nums, k):
n, ans = len(nums), float('inf')
nums.append(0)
s = collections.deque([-1])
for i in range(n):
nums[i] += nums[i-1]
while s and ans + s[0] <= i: s.popleft()
while s and nums[s[0]] + k <= nums[i]: ans = i - s.popleft()
while s and nums[s[-1]] >= nums[i]: s.pop()
s.append(i)
return ans if ans != float('inf') else -1 | shortest-subarray-with-sum-at-least-k | ✔ Python3 Solution | O(N) | satyam2001 | 0 | 140 | shortest subarray with sum at least k | 862 | 0.261 | Hard | 14,017 |
https://leetcode.com/problems/shortest-subarray-with-sum-at-least-k/discuss/1801758/Python-easy-to-read-and-understand | class Solution:
def shortestSubarray(self, nums: List[int], k: int) -> int:
dq = [(-1, 0)]
sums, res = 0, float("inf")
for i, val in enumerate(nums):
sums += val
while dq and sums-dq[0][1] >= k:
res = min(res, i-dq[0][0])
dq.pop(0)
while dq and sums < dq[-1][1]:
dq.pop()
dq.append((i, sums))
return -1 if res == float("inf") else res | shortest-subarray-with-sum-at-least-k | Python easy to read and understand | sanial2001 | 0 | 345 | shortest subarray with sum at least k | 862 | 0.261 | Hard | 14,018 |
https://leetcode.com/problems/shortest-subarray-with-sum-at-least-k/discuss/388721/Solution-in-Python-3-(beats-100.00-)-(six-lines) | class Solution:
def shortestSubarray(self, A: List[int], K: int) -> int:
C, m, a = [0]+list(itertools.accumulate(A)), float('inf'), collections.deque()
for i, c in enumerate(C):
while a and C[a[-1]] >= c: a.pop()
while a and c - C[a[0]] >= K: m = min(m, i - a.popleft())
a.append(i)
return -1 if m == float('inf') else m
- Junaid Mansuri
(LeetCode ID)@hotmail.com | shortest-subarray-with-sum-at-least-k | Solution in Python 3 (beats 100.00 %) (six lines) | junaidmansuri | -7 | 1,400 | shortest subarray with sum at least k | 862 | 0.261 | Hard | 14,019 |
https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/discuss/1606006/Easy-to-understand-Python-graph-solution | class Solution:
def distanceK(self, root: TreeNode, target: TreeNode, k: int) -> List[int]:
graph=defaultdict(list)
#create undirected graph
stack=[root]
while stack:
node=stack.pop()
if node==target:
targetVal=node.val
if node.left:
graph[node.val].append(node.left.val)
graph[node.left.val].append(node.val)
stack.append(node.left)
if node.right:
graph[node.val].append(node.right.val)
graph[node.right.val].append(node.val)
stack.append(node.right)
#start BFS
q=deque([(targetVal,0)]) #startNode distance=0
seen=set()
seen.add(targetVal)
res=[]
while q:
node,depth=q.popleft()
if depth==k:
res.append(node)
if depth>k: break #no need to continue
for neigh in graph[node]:
if neigh not in seen:
q.append((neigh,depth+1))
seen.add(neigh)
return res | all-nodes-distance-k-in-binary-tree | Easy to understand Python 🐍 graph solution | InjySarhan | 6 | 439 | all nodes distance k in binary tree | 863 | 0.621 | Medium | 14,020 |
https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/discuss/1850052/Python-most-readable-solution-beats-99-(32ms) | class Solution:
def dfs_add_parent(self, node: TreeNode, parent: Optional[TreeNode] = None):
node.parent = parent
if node.right:
self.dfs_add_parent(node.right, node)
if node.left:
self.dfs_add_parent(node.left, node)
def distanceK(self, root: TreeNode, target: TreeNode, k: int) -> List[int]:
self.dfs_add_parent(root)
found_k_dist = []
visited = set()
def dfs_get_distance(node: TreeNode, current: int):
visited.add(node)
if current == k:
found_k_dist.append(node.val)
return
for neighbor in [node.parent, node.left, node.right]:
if neighbor and neighbor not in visited:
dfs_get_distance(neighbor, current + 1)
dfs_get_distance(target, 0)
return found_k_dist | all-nodes-distance-k-in-binary-tree | Python, most readable solution beats 99% (32ms) | H2Oaq | 3 | 223 | all nodes distance k in binary tree | 863 | 0.621 | Medium | 14,021 |
https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/discuss/1288889/Easy-%2B-Straightforward-Python-DFS | class Solution:
def distanceK(self, root: TreeNode, target: TreeNode, k: int) -> List[int]:
def helper(node, parent):
if not node:
return
node.parent = parent
helper(node.left, node)
helper(node.right, node)
helper(root, None)
ans = []
seen = set()
def trav(node, dist):
if not node or node in seen or dist > k:
return
seen.add(node)
if dist == k:
ans.append(node.val)
return
trav(node.parent, dist+1)
trav(node.left, dist+1)
trav(node.right, dist+1)
trav(target, 0)
return ans | all-nodes-distance-k-in-binary-tree | Easy + Straightforward Python DFS | Pythagoras_the_3rd | 3 | 403 | all nodes distance k in binary tree | 863 | 0.621 | Medium | 14,022 |
https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/discuss/2800508/python | class Solution:
def distanceK(self, root: TreeNode, target: TreeNode, k: int) -> List[int]:
parents = dict()
ans = []
def findParents(node):
if node.left:
parents[node.left.val] = node
findParents(node.left)
if node.right:
parents[node.right.val] = node
findParents(node.right)
findParents(root)
parents[root.val] = None
def findAns(node, froms, depth):
if not node:
return
if depth == k:
ans.append(node.val)
return
if node.left != froms:
findAns(node.left, node, depth + 1)
if node.right != froms:
findAns(node.right, node, depth + 1)
if parents[node.val] != froms:
findAns(parents[node.val], node, depth + 1)
findAns(target, None, 0)
return ans | all-nodes-distance-k-in-binary-tree | python | xy01 | 0 | 7 | all nodes distance k in binary tree | 863 | 0.621 | Medium | 14,023 |
https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/discuss/2800508/python | class Solution(object):
def distanceK(self, root, target, k):
ans = []
def dfs(node, par = None):
if not node:
return
node.par = par
dfs(node.left, node)
dfs(node.right, node)
dfs(root)
def findAns(node, froms, depth, k):
if not node:
return
if depth == k:
ans.append(node.val)
if node.left != froms:
findAns(node.left, node, depth + 1, k)
if node.right != froms:
findAns(node.right, node, depth + 1, k)
if node.par != froms:
findAns(node.par, node, depth + 1, k)
findAns(target, None, 0, k)
return ans | all-nodes-distance-k-in-binary-tree | python | xy01 | 0 | 7 | all nodes distance k in binary tree | 863 | 0.621 | Medium | 14,024 |
https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/discuss/2618563/PYTHON-EASY-SOLUTION-JUST-THINK-AND-USE-QUEUE-AND-PARENT-NODE-CONCEPT | class Solution:
def distanceK(self, root: TreeNode, target: TreeNode, k: int) -> List[int]:
def helper(node):
if not node:
return
if node.left:
node.left.parent=node
if node.right:
node.right.parent=node
helper(node.left)
helper(node.right)
helper(root)
root.parent=None
q=deque()
seto=set()
count=-1
if target:
q.append(target)
while q:
count+=1
list1=[]
for i in range(len(q)):
node=q.popleft()
list1.append(node.val)
seto.add(node.val)
if node.left and node.left.val not in seto:
q.append(node.left)
if node.right and node.right.val not in seto:
q.append(node.right)
if node.parent and node.parent.val not in seto:
q.append(node.parent)
if count==k:
return list1
return [] | all-nodes-distance-k-in-binary-tree | PYTHON EASY SOLUTION----------JUST THINK AND USE QUEUE AND PARENT NODE CONCEPT | mothvik | 0 | 25 | all nodes distance k in binary tree | 863 | 0.621 | Medium | 14,025 |
https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/discuss/2115950/Python-ugly-but-optimal-DFS-one-pass-with-early-termination | class Solution:
def distanceK(self, root: TreeNode, target: TreeNode, k: int) -> List[int]:
def dfs(node, dist):
if not node:
return None
if dist:
if dist == k:
result.append(node.val)
return None
else:
return dfs(node.left, dist + 1) or dfs(node.right, dist + 1)
else:
if node is target:
if k == 0:
result.append(node.val)
return None
else:
dfs(node.left, 1)
dfs(node.right, 1)
return 1
left = dfs(node.left, None)
if left:
if left == k:
result.append(node.val)
return None
else:
dfs(node.right, left + 1)
return left + 1
right = dfs(node.right, None)
if right:
if right == k:
result.append(node.val)
return None
else:
dfs(node.left, right + 1)
return right + 1
return None
result = []
dfs(root, None)
return result | all-nodes-distance-k-in-binary-tree | Python, ugly but optimal DFS one-pass with early termination | blue_sky5 | 0 | 19 | all nodes distance k in binary tree | 863 | 0.621 | Medium | 14,026 |
https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/discuss/1776389/Python3-Solution-with-using-BFS-and-hashmap | class Solution:
def dfs(self, node, node2parent, parent):
if not node:
return None
node2parent[node.val] = parent
self.dfs(node.left, node2parent, node)
self.dfs(node.right, node2parent, node)
def distanceK(self, root: TreeNode, target: TreeNode, k: int) -> List[int]:
node2parent = {}
self.dfs(root, node2parent, None)
# (target, 0) - node and dist from target
q = collections.deque([(target, 0)])
visited = set([target.val])
while q:
cur_dist = q[0][1]
if cur_dist == k:
return [node.val for node, _ in q]
node, _ = q.popleft()
neigbs = [node.left, node.right, node2parent[node.val]]
for neigb in neigbs:
if neigb and neigb.val not in visited:
q.append((neigb, cur_dist + 1))
visited.add(neigb.val)
return [] | all-nodes-distance-k-in-binary-tree | [Python3] Solution with using BFS and hashmap | maosipov11 | 0 | 43 | all nodes distance k in binary tree | 863 | 0.621 | Medium | 14,027 |
https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/discuss/1774587/python3-BFS-using-parent-dictionary | class Solution:
def distanceK(self, root: TreeNode, target: TreeNode, k: int) -> List[int]:
mydict={}
def Parents(root,parent):
if root==None:
return
mydict[root]=parent
Parents(root.left,root)
Parents(root.right,root)
Parents(root,None)
from collections import deque
q=deque()
q.append((target,0))
visited=set()
res=[]
while q:
node,depth=q.popleft()
if node not in visited:
if depth==k:
res.append(node.val)
visited.add(node)
if node.left:
q.append((node.left,depth+1))
if node.right:
q.append((node.right,depth+1))
if mydict[node]:
q.append((mydict[node],depth+1))
return res | all-nodes-distance-k-in-binary-tree | python3 BFS using parent dictionary | Karna61814 | 0 | 23 | all nodes distance k in binary tree | 863 | 0.621 | Medium | 14,028 |
https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/discuss/1653650/Inorder-Traversal-%2B-Find | class Solution:
def distanceK(self, root: TreeNode, target: TreeNode, k: int) -> List[int]:
def mapping_to_parent(node, parent):
if not node:
return None
mapping_to_parent(node.left, node)
node.parent = parent #these three lines are doing in order traversal
mapping_to_parent(node.right, node)
mapping_to_parent(root, None)
ans = []
visit = set()
#now we will traverse in the graph to find the Node at distance K
def find(node, dist):
if not node or node in visit:
return None
visit.add(node)
if dist == k:
ans.append(node.val)
find(node.parent, dist+1)
find(node.left, dist+1)
find(node.right, dist+1)
find(target, 0)
return ans | all-nodes-distance-k-in-binary-tree | Inorder Traversal + Find | Jazzyb1999 | 0 | 76 | all nodes distance k in binary tree | 863 | 0.621 | Medium | 14,029 |
https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/discuss/1535411/Python-Easy-to-understand-DFS-O(N)-Solution-95-Faster | class Solution:
## Time O(N) || Space O(N)
def __init__(self):
self.targetNode = None
def distanceK(self, root: TreeNode, target: TreeNode, k: int) -> List[int]:
parentNodes = {}
parentNodes = self.nodeToParents(root, parentNodes,None)
res = self.nodesAtDistanceK(target, k, parentNodes )
return res
## To find the nodes at distance K (stacking)
def nodesAtDistanceK(self, node, k, parentNodes):
queue = deque([(node, 0)])
visited = set()
result = []
while queue:
curNode, dist = queue.popleft()
visited.add(curNode.val)
if dist == k:
result.append(curNode.val)
continue
if curNode.left and curNode.left.val not in visited:
queue.append((curNode.left, dist+1))
if curNode.right and curNode.right.val not in visited:
queue.append((curNode.right, dist+1))
if parentNodes[curNode]:
if parentNodes[curNode].val not in visited:
queue.append((parentNodes[curNode], dist+1))
return result
## To get all the parent nodes in a dictonary(hashmap)
def nodeToParents(self,node, parentNodes, parent ):
if not node:
return
parentNodes[node] = parent
self.nodeToParents(node.left, parentNodes, node)
self.nodeToParents(node.right, parentNodes, node)
return parentNodes | all-nodes-distance-k-in-binary-tree | Python Easy to understand DFS O(N) Solution 95% Faster | Hiteshsaai | 0 | 101 | all nodes distance k in binary tree | 863 | 0.621 | Medium | 14,030 |
https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/discuss/1394469/DFS-in-Python-3-using-generators-(with-comments) | class Solution:
def distanceK(self, root: TreeNode, target: TreeNode, k: int) -> List[int]:
if (None, None) == (root.left, root.right):
return [] if k > 0 else [root.val]
if k == 0:
return [target.val]
def find_target(n: TreeNode):
if n is target:
yield [n]
else:
yield from ([n] + path for c in (n.left, n.right) if c for path in find_target(c))
# applying the logic from 257. Binary Tree Paths, get the path to target
path_to_target = next(find_target(root))
for n in path_to_target:
setattr(n, 'in_critical_path', True)
target_depth = len(path_to_target)-1
def dfs_by_depth(n: TreeNode, depth: int):
if not n:
return
if depth == 0:
yield n.val
else:
# avoid repeatedly visiting the nodes in path_to_target
for c in (n.left, n.right):
if getattr(c, 'in_critical_path', False):
continue
for cc in dfs_by_depth(c, depth-1):
yield cc
def search():
# search down along target's child nodes
yield from dfs_by_depth(target.left, k-1)
yield from dfs_by_depth(target.right, k-1)
# search along path_to_target in reversed order, looking for nodes
# in other subtrees
for i in range(1, (k if k < target_depth else target_depth) + 1):
yield from dfs_by_depth(path_to_target[-i-1], k - i)
return list(search()) | all-nodes-distance-k-in-binary-tree | DFS in Python 3, using generators (with comments) | mousun224 | 0 | 34 | all nodes distance k in binary tree | 863 | 0.621 | Medium | 14,031 |
https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/discuss/941014/Python3-BFS-O(N) | class Solution:
def distanceK(self, root: TreeNode, target: TreeNode, K: int) -> List[int]:
graph = {} # graph as adjacency list
stack = [root]
while stack:
node = stack.pop()
for child in (node.left, node.right):
if child:
stack.append(child)
graph.setdefault(node.val, []).append(child.val)
graph.setdefault(child.val, []).append(node.val)
# bfs from target
queue = [target.val]
seen = set()
while queue:
if K == 0: break
newq = []
for n in queue:
seen.add(n)
newq.extend(nn for nn in graph.get(n, []) if nn not in seen)
K -= 1
queue = newq
return queue | all-nodes-distance-k-in-binary-tree | [Python3] BFS O(N) | ye15 | 0 | 91 | all nodes distance k in binary tree | 863 | 0.621 | Medium | 14,032 |
https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/discuss/905157/python-3-two-recursive-solutions | class Solution:
def distanceK(self, root: TreeNode, target: TreeNode, K: int) -> List[int]:
# dfs1: generate parent hashmap { node : prnt }
# this lets us traverse up as well as down
# then dfs2 starting from target
# add seen nodes to set to avoid looping, otherwise take K steps away
# O(N) time, O(N + H) space including recursive calls to tree height
# helper function to get parents
def get_prnts(node, parent):
if not node: return
d[node] = parent
get_prnts(node.left, node)
get_prnts(node.right, node)
d = {}
get_prnts(root, None)
# helper function to step from target
def rcrs(node, dist):
if (not node) or (node in seen): return
seen.add(node)
if dist == K:
res.append(node.val)
else:
rcrs(node.left, dist+1)
rcrs(node.right, dist+1)
rcrs(d[node], dist+1)
res = []
seen = set()
rcrs(target, 0)
return res
def distanceK1(self, root: TreeNode, target: TreeNode, K: int) -> List[int]:
# recursive dfs only: find target, update distance, re-traverse branches
# dist initially inf until target found
# O(N) ish time, O(H) recursive call space
def rcrs(node, dist):
if node is target:
dist = 0
# check distance of kids to target
lt, rt = float("inf"), float("inf")
if node.left: lt = rcrs(node.left, dist+1)
if node.right: rt = rcrs(node.right, dist+1)
# update node distance from children if not yet updated
if dist == float("inf"): dist = min(lt, rt)
# add node.val to result list if K steps from target
if dist == K: self.res.append(node.val)
# if target found, one branch hasn't seen it, redo said branch
if dist < float("inf"):
if node.left and lt == float("inf"): rcrs(node.left, dist+1)
if node.right and rt == float("inf"): rcrs(node.right, dist+1)
return dist+1
# setup & recursive call
self.res = []
rcrs(root, float("inf"))
return self.res | all-nodes-distance-k-in-binary-tree | python 3 - two recursive solutions | dachwadachwa | 0 | 66 | all nodes distance k in binary tree | 863 | 0.621 | Medium | 14,033 |
https://leetcode.com/problems/shortest-path-to-get-all-keys/discuss/1516812/Python3-bfs | class Solution:
def shortestPathAllKeys(self, grid: List[str]) -> int:
m, n = len(grid), len(grid[0])
ii = jj = total = 0
for i in range(m):
for j in range(n):
if grid[i][j] == "@": ii, jj = i, j
elif grid[i][j].islower(): total += 1
ans = 0
seen = {(ii, jj, 0)}
queue = [(ii, jj, 0)]
while queue:
newq = []
for i, j, keys in queue:
if keys == (1 << total) - 1: return ans
for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j):
if 0 <= ii < m and 0 <= jj < n and grid[ii][jj] != "#":
kk = keys
if grid[ii][jj].islower(): kk |= 1 << ord(grid[ii][jj]) - 97
if (ii, jj, kk) in seen or grid[ii][jj].isupper() and not kk & (1 << ord(grid[ii][jj])-65): continue
newq.append((ii, jj, kk))
seen.add((ii, jj, kk))
ans += 1
queue = newq
return -1 | shortest-path-to-get-all-keys | [Python3] bfs | ye15 | 4 | 222 | shortest path to get all keys | 864 | 0.455 | Hard | 14,034 |
https://leetcode.com/problems/shortest-path-to-get-all-keys/discuss/2818735/Python-BFS-bit-masking | class Solution:
def shortestPathAllKeys(self, grid: List[str]) -> int:
m, n = len(grid), len(grid[0])
directions = [-1, 0, 1, 0, -1]
symbols = {".", "#", "@"}
start = None
num_keys = 0
for i in range(m):
for j in range(n):
temp = grid[i][j]
if temp == "@":
start = (i, j)
num_keys += (temp not in symbols)
num_keys //= 2
FULL_KEYS = (1 << num_keys) - 1
q = [start + (0, 0)]
visited = {(start[0], start[1], 0)}
while q:
i, j, original_keys, d = q.pop(0)
for k in range(4):
keys = original_keys
x, y = i + directions[k], j + directions[k + 1]
if 0 <= x < m and 0 <= y < n and grid[x][y] != "#":
if grid[x][y] == "." or grid[x][y] == "@":
if (x, y, keys) not in visited:
visited.add((x, y, keys))
q.append((x, y, keys, d + 1))
elif 0 <= ord(grid[x][y]) - ord("A") < 26:
lock = ord(grid[x][y]) - ord("A")
if keys & (1 << lock) != 0 and (x, y, keys) not in visited:
visited.add((x, y, keys))
q.append((x, y, keys, d + 1))
else:
temp = ord(grid[x][y]) - ord("a")
if keys & (1 << temp) == 0:
keys |= (1 << temp)
if keys == FULL_KEYS:
return d + 1
if (x, y, keys) not in visited:
visited.add((x, y, keys))
q.append((x, y, keys, d + 1))
return -1 | shortest-path-to-get-all-keys | Python, BFS, bit masking | yiming999 | 0 | 7 | shortest path to get all keys | 864 | 0.455 | Hard | 14,035 |
https://leetcode.com/problems/shortest-path-to-get-all-keys/discuss/2779715/Python-BFS%3A-75-time-8-space | class Solution:
def shortestPathAllKeys(self, grid: List[str]) -> int:
dir = [[1,0], [-1,0], [0,1], [0,-1]]
m = len(grid)
n = len(grid[0])
q = []
k = 0
for i in range(m):
for j in range(n):
if grid[i][j] == '@': q.append([i, j, ''])
elif grid[i][j].islower(): k += 1
visited = set()
moves = 0
while q:
new_q = []
for row, col, keys in q:
if len(keys) == k: return moves
if ((row, col, keys) in visited): continue
visited.add((row, col, keys))
for r, c in dir:
nr, nc = row + r, col + c
if nr < 0 or nr == m or nc < 0 or nc == n: continue
val = grid[nr][nc]
if val == '#': continue
if val == '.' or val == '@' or val in keys: new_q.append([nr, nc, keys])
elif val.islower(): new_q.append([nr, nc, keys + val])
elif val.lower() in keys: new_q.append([nr, nc, keys])
moves += 1
q = new_q
return -1 | shortest-path-to-get-all-keys | Python BFS: 75% time, 8% space | hqz3 | 0 | 11 | shortest path to get all keys | 864 | 0.455 | Hard | 14,036 |
https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/discuss/940618/Python3-dfs-O(N) | class Solution:
def subtreeWithAllDeepest(self, root: TreeNode) -> TreeNode:
@lru_cache(None)
def fn(node):
"""Return height of tree rooted at node."""
if not node: return 0
return 1 + max(fn(node.left), fn(node.right))
node = root
while node:
left, right = fn(node.left), fn(node.right)
if left == right: return node
elif left > right: node = node.left
else: node = node.right | smallest-subtree-with-all-the-deepest-nodes | [Python3] dfs O(N) | ye15 | 5 | 140 | smallest subtree with all the deepest nodes | 865 | 0.686 | Medium | 14,037 |
https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/discuss/940618/Python3-dfs-O(N) | class Solution:
def subtreeWithAllDeepest(self, root: TreeNode) -> TreeNode:
fn = lru_cache(None)(lambda x: 1 + max(fn(x.left), fn(x.right)) if x else 0)
node = root
while node:
if fn(node.left) == fn(node.right): return node
elif fn(node.left) < fn(node.right): node = node.right
else: node = node.left
return node | smallest-subtree-with-all-the-deepest-nodes | [Python3] dfs O(N) | ye15 | 5 | 140 | smallest subtree with all the deepest nodes | 865 | 0.686 | Medium | 14,038 |
https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/discuss/1995707/Python-two-pass-beats-99 | class Solution:
def subtreeWithAllDeepest(self, root: TreeNode) -> TreeNode:
parent, depth = {root: None}, {root: 0}
def dfs(node):
if node.right:
parent[node.right] = node
depth[node.right] = depth[node] + 1
dfs(node.right)
if node.left:
parent[node.left] = node
depth[node.left] = depth[node] + 1
dfs(node.left)
dfs(root)
max_depth = max(depth.values())
deepest_nodes = set(node for node in parent.keys() if depth[node] == max_depth)
while len(deepest_nodes) > 1:
deepest_nodes = set(parent[node] for node in deepest_nodes)
return deepest_nodes.pop() | smallest-subtree-with-all-the-deepest-nodes | Python two pass beats 99% | ashkan-leo | 1 | 72 | smallest subtree with all the deepest nodes | 865 | 0.686 | Medium | 14,039 |
https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/discuss/1557645/Python-Faster-than-95-solution-recursion-with-explanation | class Solution:
def subtreeWithAllDeepest(self, root: TreeNode) -> TreeNode:
max_depth, max_depth_subtree = self.helper(root, 0)
return max_depth_subtree
def helper(self, root, depth):
if not root:
return depth, root
left_max_depth, left_max_depth_subtree = self.helper(root.left, depth + 1)
right_max_depth, right_max_depth_subtree = self.helper(root.right, depth + 1)
## if max depth of left subtree equals to max depth of right subtree, root is the LCA
if left_max_depth == right_max_depth:
return left_max_depth, root
## if left subtree is deeper, return left subtree
if left_max_depth > right_max_depth:
return left_max_depth, left_max_depth_subtree
## if right subtree is deeper, return right subtree
return right_max_depth, right_max_depth_subtree | smallest-subtree-with-all-the-deepest-nodes | Python - Faster than 95% solution - recursion - with explanation | invincibleyg | 1 | 54 | smallest subtree with all the deepest nodes | 865 | 0.686 | Medium | 14,040 |
https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/discuss/1335770/Smallest-Subtree-With-All-Deepest-Nodes-or-Short-Python-3-DFS-Solution-or-10-LOC | class Solution:
def subtreeWithAllDeepest(self, root: TreeNode) -> TreeNode:
def find_subtree(n, level = 0):
if not n:
return 0, None
l, r = find_subtree(n.left, level + 1), find_subtree(n.right, level + 1)
if l[0] == r[0]:
return max(level, l[0]), n
return max((l, r), key = lambda x: x[0])
return find_subtree(root)[1] | smallest-subtree-with-all-the-deepest-nodes | Smallest Subtree With All Deepest Nodes | Short Python 3 DFS Solution | 10 LOC | yiseboge | 1 | 116 | smallest subtree with all the deepest nodes | 865 | 0.686 | Medium | 14,041 |
https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/discuss/2408736/Optimal-DFS-python3-solution-with-complexity-analysis | class Solution:
# O(n) time,
# O(1) space,
# Approach: DFS, recursion
def subtreeWithAllDeepest(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
depth = [0]
ancestor = [root]
def findDepth(root, length):
if root == None:
return
depth[0] = max(depth[0], length)
findDepth(root.left, length+1)
findDepth(root.right, length+1)
def isDeepLeaf(node, l):
return not node.left and not node.right and l == depth[0]
def dfs(root, length):
if isDeepLeaf(root, length):
ancestor[0] = root
return True
left = False
right = False
if root.left:
left = dfs(root.left, length+1)
if root.right:
right = dfs(root.right, length+1)
if left and right:
ancestor[0] = root
return True
if left or right:
return True
return False
findDepth(root, 0)
dfs(root, 0)
return ancestor[0] | smallest-subtree-with-all-the-deepest-nodes | Optimal DFS python3 solution with complexity analysis | destifo | 0 | 4 | smallest subtree with all the deepest nodes | 865 | 0.686 | Medium | 14,042 |
https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/discuss/2289971/Python3-Simple-solution-with-two-pass | class Solution:
def subtreeWithAllDeepest(self, root: TreeNode) -> TreeNode:
# Find all the deepest leaves
q = deque([root])
while q:
res = []
for i in range(len(q)):
node = q.popleft()
if node:
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
res.append(node.val)
# find LCA of deepest leaves
def lca(root):
if not root:
return None
if root.val in res:
return root
left = lca(root.left)
right = lca(root.right)
if left and right:
return root
if not left:
return right
else:
return left
return lca(root) | smallest-subtree-with-all-the-deepest-nodes | [Python3] Simple solution with two pass | Gp05 | 0 | 6 | smallest subtree with all the deepest nodes | 865 | 0.686 | Medium | 14,043 |
https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/discuss/1827834/Python-simple-Level-order-traversal-solution-SIMPLEST-TO-UNDERSTAND | class Solution:
def parents(self , node , parent):
if not node: return
if node.left:
parent[node.left] = node
self.parents(node.left,parent)
if node.right:
parent[node.right] = node
self.parents(node.right,parent)
def subtreeWithAllDeepest(self, root: TreeNode) -> TreeNode:
parent = {root : None}
deepest = [root]
self.parents(root , parent)
while deepest:
tmp = []
for x in deepest:
if x.left:tmp.append(x.left)
if x.right:tmp.append(x.right)
if tmp == []:break
deepest = tmp | smallest-subtree-with-all-the-deepest-nodes | Python simple Level order traversal solution SIMPLEST TO UNDERSTAND | reaper_27 | 0 | 67 | smallest subtree with all the deepest nodes | 865 | 0.686 | Medium | 14,044 |
https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/discuss/1774783/python3-solution-using-LCA-of-first-and-last-nodes-in-last-level | class Solution:
def subtreeWithAllDeepest(self, root: TreeNode) -> TreeNode:
from collections import deque
q=deque()
q.append(root)
while q:
first=None
last=None
n=len(q)
for i in range(n):
node=q.popleft()
if i==0:
first=node
last=node
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
mydict={}
def Parents(root,parent):
if not root:
return
mydict[root]=parent
Parents(root.left,root)
Parents(root.right,root)
Parents(root,None)
s=set()
while first!=None:
s.add(first)
first=mydict[first]
while last!=None:
if last in s:
return last
last=mydict[last] | smallest-subtree-with-all-the-deepest-nodes | python3 solution using LCA of first and last nodes in last level | Karna61814 | 0 | 43 | smallest subtree with all the deepest nodes | 865 | 0.686 | Medium | 14,045 |
https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/discuss/1687386/Python-Solution | class Solution:
def subtreeWithAllDeepest(self, root: TreeNode) -> TreeNode:
def calculate_height(root):
if root is None:
return 0
if root.left is None and root.right is None:
return 1
return max(calculate_height(root.left), calculate_height(root.right))+1
def find_node(root):
if root is None:
return []
left_height=calculate_height(root.left)
right_height=calculate_height(root.right)
if (left_height < right_height):
return find_node(root.right)
elif (left_height > right_height):
return find_node(root.left)
else:
return root
return find_node(root) | smallest-subtree-with-all-the-deepest-nodes | Python Solution | Siddharth_singh | 0 | 42 | smallest subtree with all the deepest nodes | 865 | 0.686 | Medium | 14,046 |
https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/discuss/1447055/O(n)-T-or-O(n)-S-or-DSU-%2B-BFS-%2B-DFS-or-Python-3 | class Solution:
def subtreeWithAllDeepest(self, root: TreeNode) -> TreeNode:
import collections
class DSU:
"""Union-Find, disjoint-set"""
def __init__(self, is_equal_compare: bool = True) -> None:
"""Create object. O(1)
:param is_equal_compare: compare elements by '=='. False if compare by 'is'.
"""
self.to_parent = dict()
self.is_equal_compare = is_equal_compare
self.size = 0
self.elements_number = 0
def number_elements(self) -> int:
"""Return number elements in all sets. O(1)
:return:
"""
return self.elements_number
def __len__(self) -> int:
"""Return number of sets. O(1)
:return:
"""
return self.size
def make(self, x: Any) -> None:
"""Create new set. ~O(1)
:param x: element.
:return:
"""
self.to_parent[x] = x
self.size += 1
self.elements_number += 1
def find(self, x: Any) -> Optional[Any]:
"""Return mark set by element. None if element not in any set. ~O(1)
:param x: element.
:return:
"""
if x not in self.to_parent:
return None
if (self.is_equal_compare and self.to_parent[x] == x) or (not self.is_equal_compare and self.to_parent[x] is x):
return x
self.to_parent[x] = self.find(self.to_parent[x])
return self.to_parent[x]
def union(self, x: Any, y: Any) -> None:
"""Union two sets by elements. ~O(1)
:param x: element is first set.
:param y: element is second set.
:return:
"""
x_mark = self.find(x)
y_mark = self.find(y)
if (self.is_equal_compare and x_mark != y_mark) or (self.is_equal_compare and x_mark is not y_mark):
self.size -= 1
if random.randint(0, 1):
self.to_parent[x_mark] = y_mark
else:
self.to_parent[y_mark] = x_mark
dsu = DSU(False)
to_parent = {root: None}
deepest_leafs = [root]
q = collections.deque()
q.appendleft((root, 0))
last_lvl = -1
while len(q) > 0:
v, lvl = q.pop()
if lvl != last_lvl:
last_lvl = lvl
deepest_leafs = []
deepest_leafs.append(v)
for ch in (v.left, v.right):
if ch is not None:
to_parent[ch] = v
q.appendleft((ch, lvl + 1))
def dfs(node, mark, dsu):
if node is None:
return
dsu.make(node)
dsu.union(node, mark)
dfs(node.left, mark, dsu)
dfs(node.right, mark, dsu)
node = deepest_leafs[0]
dsu.make(node)
lvl = 0
mark_to_ancestor = {node: (node, lvl)}
while node is not root:
parent = to_parent[node]
dsu.make(parent)
if parent.left is not node:
dfs(parent.left, parent, dsu)
else:
dfs(parent.right, parent, dsu)
mark_to_ancestor[dsu.find(parent)] = (parent, lvl + 1)
node = parent
lvl += 1
result = None
max_lvl = -1
for leaf in deepest_leafs:
v, lvl = mark_to_ancestor[dsu.find(leaf)]
if lvl > max_lvl:
max_lvl = lvl
result = v
return result | smallest-subtree-with-all-the-deepest-nodes | O(n) T | O(n) S | DSU + BFS + DFS | Python 3 | CiFFiRO | 0 | 68 | smallest subtree with all the deepest nodes | 865 | 0.686 | Medium | 14,047 |
https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/discuss/1425018/Python3-dfs-recursion | class Solution:
def __init__(self):
self.ans = None
self.max_depth = 0
def traversal(self, node, cur_lvl):
if node == None:
return 0
l_child_lvl = self.traversal(node.left, cur_lvl + 1)
r_child_lvl = self.traversal(node.right, cur_lvl + 1)
if cur_lvl > self.max_depth:
self.max_depth = cur_lvl
if l_child_lvl == r_child_lvl == self.max_depth or cur_lvl == self.max_depth:
self.ans = node
return max(cur_lvl, l_child_lvl, r_child_lvl)
def subtreeWithAllDeepest(self, root: TreeNode) -> TreeNode:
self.ans = root
self.traversal(root, 0)
return self.ans | smallest-subtree-with-all-the-deepest-nodes | [Python3] dfs recursion | maosipov11 | 0 | 64 | smallest subtree with all the deepest nodes | 865 | 0.686 | Medium | 14,048 |
https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/discuss/1414536/Simple-recursion-in-Python-(with-explaination) | class Solution:
def subtreeWithAllDeepest(self, root: TreeNode) -> TreeNode:
def max_depth(n: TreeNode) -> int:
return max(max_depth(n.left), max_depth(n.right)) + 1 if n else 0
stack = [root]
while stack:
n = stack.pop()
l_depth, r_depth = max_depth(n.left), max_depth(n.right)
if l_depth == r_depth:
return n
if l_depth > r_depth:
stack += n.left,
else:
stack += n.right,
return 0 | smallest-subtree-with-all-the-deepest-nodes | Simple recursion in Python (with explaination) | mousun224 | 0 | 84 | smallest subtree with all the deepest nodes | 865 | 0.686 | Medium | 14,049 |
https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/discuss/1414536/Simple-recursion-in-Python-(with-explaination) | class Solution:
def subtreeWithAllDeepest(self, root: TreeNode) -> TreeNode:
l_depth, r_depth = self.max_depth(root.left), self.max_depth(root.right)
if l_depth == r_depth:
return root
return self.subtreeWithAllDeepest(root.left) if l_depth > r_depth else self.subtreeWithAllDeepest(root.right)
def max_depth(self, root: TreeNode) -> int:
return max(self.max_depth(root.left), self.max_depth(root.right)) + 1 if root else 0 | smallest-subtree-with-all-the-deepest-nodes | Simple recursion in Python (with explaination) | mousun224 | 0 | 84 | smallest subtree with all the deepest nodes | 865 | 0.686 | Medium | 14,050 |
https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/discuss/1221922/A-Python-Solution | class Solution:
def subtreeWithAllDeepest(self, root: TreeNode) -> TreeNode:
# Step 1: Find all nodes at the deepest "level" in the tree
queue, graph = collections.deque([(root, 0)]), collections.defaultdict(list)
while queue:
node, depth = queue.popleft()
if not node: continue
graph[depth] += [node]
queue.extend([
(node.left, depth+1),
(node.right, depth+1),
])
levels = set(graph[max(graph.keys())])
# Step 2: Find the "deepest" node that contains all nodes in the levels list
def node_contains_all_levels(node):
if not node: return 0
return (node in levels) + node_contains_all_levels(node.left) + node_contains_all_levels(node.right)
queue, result = collections.deque([root]), None
while queue:
node = queue.popleft()
if not node: continue
if node_contains_all_levels(node) == len(levels):
result = node
queue.extend([node.left, node.right])
# Step 3: Return the result
return result | smallest-subtree-with-all-the-deepest-nodes | A Python Solution | dev-josh | 0 | 97 | smallest subtree with all the deepest nodes | 865 | 0.686 | Medium | 14,051 |
https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/discuss/840563/python3-recursive-dfs | class Solution:
def subtreeWithAllDeepest(self, root: TreeNode) -> TreeNode:
# recursive dfs approach
# helper function: pass "level" when descending, return (node, max_depth)
# if left depth == right_depth, return yourself
# else return the side with greater depth
# O(N) time, O(H) stack calls
def rcrs(node, level):
if not node: return (None, level-1)
lt_node, lt_depth = rcrs(node.left, level+1)
rt_node, rt_depth = rcrs(node.right, level+1)
if not lt_node and not rt_node:
return (node, level)
if lt_depth == rt_depth:
return (node, lt_depth)
else:
if lt_depth > rt_depth:
return (lt_node, lt_depth)
else:
return (rt_node, rt_depth)
# setup & recursive call
return rcrs(root, 0)[0] | smallest-subtree-with-all-the-deepest-nodes | python3 - recursive dfs | dachwadachwa | 0 | 44 | smallest subtree with all the deepest nodes | 865 | 0.686 | Medium | 14,052 |
https://leetcode.com/problems/prime-palindrome/discuss/707393/Python3-check-next-palindrome-Prime-Palindrome | class Solution:
def primePalindrome(self, N: int) -> int:
def isPrime(N):
return N > 1 and all(N % d for d in range(2, int(N**0.5)+1))
# N must be a palindrome with odd number of digits.
# The return value will have odd number of digits too.
def nextPalindrome(N):
if N in [999, 99999, 9999999]:
return (N + 1) * 10 + 1
n = str(N // 10 ** (len(str(N))//2) + 1)
return int(n + n[-2::-1])
if N <= 11:
while not isPrime(N):
N += 1
return N
if (digits := len(str(N))) % 2 == 0:
N = 10 ** digits + 1
else:
n = str(N // 10 ** (len(str(N))//2))
if (p := int(n + n[-2::-1])) >= N:
N = p
else:
N = nextPalindrome(p)
while not isPrime(N):
N = nextPalindrome(N)
return N | prime-palindrome | Python3 check next palindrome - Prime Palindrome | r0bertz | 1 | 484 | prime palindrome | 866 | 0.258 | Medium | 14,053 |
https://leetcode.com/problems/prime-palindrome/discuss/1488677/Python-3-or-Brute-force-%2B-Math-Pruning-or-Explanation | class Solution:
def primePalindrome(self, n: int) -> int:
def is_prime(n):
if n == 1: return False
for i in range(2, int(n**0.5)+1):
if n % i == 0: return False
return True
n_str = str(n)
l = len(n_str)
for k in range(max(0, l//2-1), 5):
for i in range(10**k, 10**(k+1)): # odd length
i_str = str(i)
if k > 0 and i_str[0] in ['2','4','5','6','8']: continue # pruning
cur = i_str + i_str[-2::-1]
cur_int = int(cur)
if cur_int >= n and is_prime(cur_int):
return cur_int
for i in range(10**k, 10**(k+1)): # even length
i_str = str(i)
if i_str[0] in ['2','4','5','6','8']: continue # pruning
cur = i_str + i_str[::-1]
cur_int = int(cur)
if cur_int >= n and is_prime(cur_int):
return cur_int
return -1 | prime-palindrome | Python 3 | Brute-force + Math Pruning | Explanation | idontknoooo | 0 | 273 | prime palindrome | 866 | 0.258 | Medium | 14,054 |
https://leetcode.com/problems/prime-palindrome/discuss/1458153/Python3-brute-force | class Solution:
def primePalindrome(self, n: int) -> int:
if 8 <= n <= 11: return 11 # edge case
def fn(n):
"""Return next palindromic number greater than x."""
digits = [int(x) for x in str(n)]
for i in reversed(range(len(digits)//2+1)):
if digits[i] < 9: break
else: return 10*n + 11
digits[i] = digits[~i] = digits[i] + 1
for ii in range(i):
digits[~ii] = digits[ii]
for ii in range(i+1, len(digits)//2+1):
digits[ii] = digits[~ii] = 0
return int("".join(map(str, digits)))
def isprime(x):
"""Return True if x is prime."""
if x <= 1: return False
if x % 2 == 0: return x == 2
for k in range(3, int(sqrt(x))+1, 2):
if x % k == 0: return False
return True
nn = n
k = 0
while nn:
nn //= 10
k += 1
if not k&1: n = 10**k + 1
elif str(n) != str(n)[::-1]: n = fn(n)
while True:
if isprime(n): return n
n = fn(n) | prime-palindrome | [Python3] brute-force | ye15 | 0 | 158 | prime palindrome | 866 | 0.258 | Medium | 14,055 |
https://leetcode.com/problems/prime-palindrome/discuss/1161034/Python3-easy-solution-with-explanation-and-comments-100-faster | class Solution:
def primePalindrome(self, N: int) -> int:
'''
1. If N<=11, then the result is the first prime number greater than or equal N
2. If 11<N<=101, then the result is 101
3. Otherwise, there are no prime palindromes of even length
4. Let N is a x' digit number. If x' is even, then set N=10^x'. Now N is x=x'+1 digit number where x is odd. If x' is odd, then don't change N and here x=x'.
5. Starting from N, generate palindromes and check if it is prime
6. If not, then set N = value of first floor(x//2) digits + 1, and go back to step 4 and generate new palindromes from new N.
'''
def isPrime(n):
i=3 #don't need to check any even number, so start checking from 3
while i*i<=n: #if n is not prime, then it will be divisible by a number at most sqrt(n)
if n%i==0:
return False #has divisor, so not prime
i+=2 #only check if there are odd divisors, as n is odd
return True #n is prime
if N==1 or N==2: #nearest prime number of N in {1,2} is 2 which is palindrome
return 2
elif N==3: #3 is a prime palindrome
return 3
elif N==4 or N==5: #nearest prime number of N in {4,5} is 5 which is palindrome
return 5
elif N==6 or N==7: #nearest prime number of N in {6,7} is 7 which is palindrome
return 7
elif N>7 and N<=11: #nearest prime number of N greater than 7 is 11 which is palindrome
return 11
elif N>11 and N<=101: #for all two digit numbers greater than 11, and for 100,101
return 101 #nearest prime palindrome is 101
start=(N+1)*(N%2==0)+N*(N%2==1) #prime number must be odd, so start checking from the odd number nearest to N
len_string =len(str(start))
str_N = str(start)
if str_N==str_N[::-1] and isPrime(start): #if N or (N+1) is prime, then don't need to check further
return start
else:
while(True):
if len_string%2==0:
start=10**(len_string) #convert even length starting number to odd length
str_N=str(start) #store the string representation of starting number
if int(str_N[0])%2==0: #if the first digit is even, then the palindrome will also be even
start+=10**(len_string-1) #start from the nearest number whose first digit is odd
str_N=str(start)
if int(str_N[0])==5: #if the first digit is 5, then the palindrome is divisible by 5
start=7*(10**(len_string-1)) #the nearest prime palindrome starts with 7
str_N=str(start)
str_N = str_N[0:len_string//2]+str_N[len_string//2]+str_N[0:len_string//2][::-1] #create palindrome closest to starting number
if int(str_N)>=N and isPrime(int(str_N)):
return int(str_N) #got a palindrome greater than or equal N, return the palindrome
else:
start=int(str_N[0:len_string//2+1])+1 #increase the value of starting floor(len_string//2) digits by one
start*=10**(len_string//2) #append necessary 0's to start and this will be the new starting position
str_N=str(start) #convert start to string
len_string=len(str_N) #store the length | prime-palindrome | Python3 easy solution with explanation and comments, 100% faster | bPapan | 0 | 183 | prime palindrome | 866 | 0.258 | Medium | 14,056 |
https://leetcode.com/problems/prime-palindrome/discuss/995044/python3-Find-palindromes-first-and-then-check-if-it's-prime | class Solution:
primes = [2]
def primePalindrome(self, N: int) -> int:
# Find palindrome number first, then check it is a prime number.
# Elimiate special case 2 and 11.
if N < 3: return 2
elif 7 < N <= 11: return 11
# Record the number of digits.
num, digitLen = N, 0
while num > 0:
num = num // 10
digitLen += 1
# Even length palindromes are divisible by 11,
# it will be non-prime number except for 11 itself.
if digitLen % 2 == 0:
return self.primePalindrome(10**(digitLen))
else:
halfDigitLen = digitLen//2
# All number which length is one, is palindrome number.
if halfDigitLen == 0:
for num in range(N, 10):
if self.isPrime(num):
return num
# If length is bigger than one.
# Split the palindrome number into three part, left, middle, right
# We need to find palindrome number in ascending way.
# So first decide left side number then middle number.(right number don't matter if it's palindrome number)
else:
# first digit of left side number has to be 1, otherwise it would not be the same number of digits.
# If 7 digits number => left side number is 100 ~ 999
leftSideNum = 10**(halfDigitLen-1)
while leftSideNum < 10**halfDigitLen:
# Caculate right side number
rightSideNum = 0
for digit in range(halfDigitLen):
rightSideNum += (leftSideNum%(10**(digit+1))//(10**digit))*(10**(halfDigitLen-digit-1))
# middle number is 0 ~ 9
for middleNum in range(10):
num = rightSideNum + leftSideNum*(10**(halfDigitLen+1)) + middleNum*(10**halfDigitLen)
if num >= N:
if self.isPrime(num):
return num
leftSideNum += 1
# The while statement just to elimiate last digit is multiple of 2 or 5
# which definitely not the prime number.
firstNum = leftSideNum//(10**(halfDigitLen-1))
while firstNum % 2 == 0 or firstNum % 5 == 0:
leftSideNum += 10**(halfDigitLen-1)
firstNum = leftSideNum//(10**(halfDigitLen-1))
# If can not find prime with current length
# then add 2 to length. 999 -> 10000 (3->5)
return self.primePalindrome(10**(digitLen+1))
def isPrime(self, x: int) -> bool:
notEnoughPrime = True
for prime in self.primes:
if prime*prime > x:
notEnoughPrime = False
break
if x % prime == 0:
return False
if notEnoughPrime:
num = self.primes[-1] + 1
while num*num <= x:
if self.isPrime(num):
self.primes.append(num)
num += 1
for prime in self.primes:
if x % prime == 0:
return False
return True | prime-palindrome | [python3] Find palindromes first and then check if it's prime | d486250 | 0 | 234 | prime palindrome | 866 | 0.258 | Medium | 14,057 |
https://leetcode.com/problems/prime-palindrome/discuss/434061/Best-Python-3-Solution-(100-less-memory-100-less-time) | class Solution:
def primePalindrome(self, k: int) -> int:
if k < 12:
for i in range(1, 12):
if self.is_prime(i) and i >= k:
return i
string_k = str(k)
string_length = len(string_k)
if string_length % 2 == 0:
starting_root = 10**(string_length-string_length // 2)
else:
starting_root = int(string_k[:string_length-string_length // 2])
for root in range(starting_root, 10**6):
str_root = str(root)
palindrome_gen = int(str_root + str_root[-2::-1])
if palindrome_gen >= k and self.is_prime(palindrome_gen):
return palindrome_gen
def is_prime(self, n):
return n > 1 and all(n % d for d in range(2, int(n**.5) + 1)) | prime-palindrome | Best Python 3 Solution (100% less memory, 100% less time) | EllaShar | 0 | 782 | prime palindrome | 866 | 0.258 | Medium | 14,058 |
https://leetcode.com/problems/prime-palindrome/discuss/414797/I-only-know-how-the-is_prime-function-works-and-even-that's-a-maybe | class Solution:
def primePalindrome(self, k: int) -> int:
def is_prime(num):
if num % 2 is 0: return False
return all(num%i for i in range(3, int(num**0.5)+1, 2))
if k < 12:
return next(x for x in [2,3,5,7,11] if x >= k)
else:
string_k = str(k)
string_length = len(string_k)
if string_length % 2:
starting_root = int(string_k[:string_length-string_length//2])
for root in range(starting_root, 10**6):
root = str(root)
palindrome_gen = int(root + root[-2::-1])
if is_prime(palindrome_gen) and palindrome_gen >= k:
return palindrome_gen
else:
starting_root = str(10**(string_length-string_length//2))
starting_reverse = starting_root[-2::-1]
for root in range(int(starting_root), 10**6):
palindrome_gen = int(str(root) + starting_reverse)
if is_prime(palindrome_gen) and palindrome_gen >= k:
return palindrome_gen | prime-palindrome | I only know how the is_prime function works, and even that's a maybe | SkookumChoocher | 0 | 250 | prime palindrome | 866 | 0.258 | Medium | 14,059 |
https://leetcode.com/problems/transpose-matrix/discuss/2100098/Python-Easy-2-Approaches-one-liner | class Solution:
def transpose(self, matrix: List[List[int]]) -> List[List[int]]:
m,n=len(matrix),len(matrix[0])
ans = [[None] * m for _ in range(n)]
for i in range(m):
for j in range(n):
ans[j][i]=matrix[i][j]
return ans | transpose-matrix | Python Easy - 2 Approaches - one liner | constantine786 | 18 | 2,600 | transpose matrix | 867 | 0.635 | Easy | 14,060 |
https://leetcode.com/problems/transpose-matrix/discuss/2100098/Python-Easy-2-Approaches-one-liner | class Solution:
def transpose(self, matrix: List[List[int]]) -> List[List[int]]:
return list(map(list,zip(*matrix))) # we need to explicitly cast as zip returns tuples | transpose-matrix | Python Easy - 2 Approaches - one liner | constantine786 | 18 | 2,600 | transpose matrix | 867 | 0.635 | Easy | 14,061 |
https://leetcode.com/problems/transpose-matrix/discuss/2100098/Python-Easy-2-Approaches-one-liner | class Solution:
def transpose(self, matrix: List[List[int]]) -> List[List[int]]:
return [[matrix[y][x] for y in range(len(matrix))] for x in range(len(matrix[0]))] | transpose-matrix | Python Easy - 2 Approaches - one liner | constantine786 | 18 | 2,600 | transpose matrix | 867 | 0.635 | Easy | 14,062 |
https://leetcode.com/problems/transpose-matrix/discuss/2528813/Python-Solution-or-One-Liner-or-100-Faster-or-Zip-Em-All | class Solution:
def transpose(self, matrix: List[List[int]]) -> List[List[int]]:
return zip(*matrix) | transpose-matrix | Python Solution | One Liner | 100% Faster | Zip Em All | Gautam_ProMax | 2 | 111 | transpose matrix | 867 | 0.635 | Easy | 14,063 |
https://leetcode.com/problems/transpose-matrix/discuss/2434640/Transpose-Matrix | class Solution:
def transpose(self, matrix: List[List[int]]) -> List[List[int]]:
m= len(matrix)
n = len(matrix[0])
Transpose=[[0]*m for i in range(n)]
for i in range(m):
for j in range(n):
Transpose[j][i]=matrix[i][j]
return(Transpose) | transpose-matrix | Transpose Matrix | dhananjayaduttmishra | 1 | 29 | transpose matrix | 867 | 0.635 | Easy | 14,064 |
https://leetcode.com/problems/transpose-matrix/discuss/2169700/Python3-3-solutions-best-Runtime%3A-79ms-88.18-oror-memory%3A-14.9mb-17.05 | class Solution:
def transpose(self, matrix: List[List[int]]) -> List[List[int]]:
if not matrix or not matrix[0]:
return matrix
return self.solOne(matrix)
# return self.solTwo(matrix)
# return self.solOne(matrix)
# O(rc) || O(n)
# Runtime: 91ms 73.05% memory: 14.7mb 57.03%
def solOne(self, matrix):
result = []
for row in range(len(matrix[0])):
newList = []
for col in range(len(matrix)):
newList.append(matrix[col][row])
result.append(newList)
return result
# Runtime: 109ms 52.05% memory: 14.7mb 92.09%
def solTwo(self, matrix):
return list(map(list, zip(*matrix)))
# O(rc) || O(n)
# Runtime: 79ms 88.18% || memory: 14.9mb 17.05%
def solThree(self, matrix):
return [[row[i] for row in matrix] for i in range(len(matrix[0]))] | transpose-matrix | Python3 3 solutions best Runtime: 79ms 88.18% || memory: 14.9mb 17.05% | arshergon | 1 | 114 | transpose matrix | 867 | 0.635 | Easy | 14,065 |
https://leetcode.com/problems/transpose-matrix/discuss/2101988/Runtime%3A-106-ms-faster-than-41.92-of-Python3 | class Solution:
def transpose(self, matrix: List[List[int]]) -> List[List[int]]:
return [*zip(*matrix)] | transpose-matrix | Runtime: 106 ms, faster than 41.92% of Python3 | writemeom | 1 | 65 | transpose matrix | 867 | 0.635 | Easy | 14,066 |
https://leetcode.com/problems/transpose-matrix/discuss/2101193/python3-or-python-or-easy-understanding-or-neat-and-clean-code | class Solution:
def transpose(self, matrix: List[List[int]]) -> List[List[int]]:
l=[]
k=[]
i=0
j=0
while(j!=len(matrix[0])):
k.append(matrix[i][j])
if i==len(matrix)-1:
j+=1
i=0
l.append(k)
k=[]
else:
i+=1
return l | transpose-matrix | python3 | python | easy understanding | neat and clean code | T1n1_B0x1 | 1 | 97 | transpose matrix | 867 | 0.635 | Easy | 14,067 |
https://leetcode.com/problems/transpose-matrix/discuss/2101129/python-or-One-liner | class Solution:
def transpose(self, matrix: List[List[int]]) -> List[List[int]]:
return list(zip(*matrix)) | transpose-matrix | python | One liner | e1leet | 1 | 32 | transpose matrix | 867 | 0.635 | Easy | 14,068 |
https://leetcode.com/problems/transpose-matrix/discuss/2100830/Easy-to-understand-python-code-O(m-x-n)-time-complexity-with-intuition-and-Complexity-analysis. | class Solution:
def transpose(self, matrix: List[List[int]]) -> List[List[int]]:
ans=[[0 for _ in range(len(matrix))] for _ in range(len(matrix[0]))]
for i in range(len(matrix)):
for j in range(len(matrix[0])):
ans[j][i]=matrix[i][j]
return ans | transpose-matrix | Easy to understand python code O(m x n) time complexity with intuition and Complexity analysis. | tkdhimanshusingh | 1 | 52 | transpose matrix | 867 | 0.635 | Easy | 14,069 |
https://leetcode.com/problems/transpose-matrix/discuss/2100718/PYTHON-oror-EASY | class Solution:
def transpose(self, matrix: List[List[int]]) -> List[List[int]]:
m = len(matrix)
n = len(matrix[0])
temp = [[0] * m for _ in range(n)]
for i in range(m):
for j in range(n):
temp[j][i] = matrix[i][j]
return temp | transpose-matrix | PYTHON || EASY | testbugsk | 1 | 32 | transpose matrix | 867 | 0.635 | Easy | 14,070 |
https://leetcode.com/problems/transpose-matrix/discuss/2100540/PYTHON-oror-EAZY-oror-EXPLAINEDDDD | class Solution:
def transpose(self, matrix: List[List[int]]) -> List[List[int]]:
res=[]
for i in range(len(matrix[0])):
res.append([])
for j in range(len(matrix)):
res[-1].append(matrix[j][i])
return res | transpose-matrix | 🐍 PYTHON 🐍 || EAZY || EXPLAINEDDDD | karan_8082 | 1 | 108 | transpose matrix | 867 | 0.635 | Easy | 14,071 |
https://leetcode.com/problems/transpose-matrix/discuss/1343880/Python3-dollarolution-(Faster-than-96) | class Solution:
def transpose(self, matrix: List[List[int]]) -> List[List[int]]:
x = list(zip(*matrix))
return x | transpose-matrix | Python3 $olution (Faster than 96%) | AakRay | 1 | 289 | transpose matrix | 867 | 0.635 | Easy | 14,072 |
https://leetcode.com/problems/transpose-matrix/discuss/381763/Solution-in-Python-3-(one-line) | class Solution:
def transpose(self, A: List[List[int]]) -> List[List[int]]:
return list(zip(*A))
- Junaid Mansuri
(LeetCode ID)@hotmail.com | transpose-matrix | Solution in Python 3 (one line) | junaidmansuri | 1 | 405 | transpose matrix | 867 | 0.635 | Easy | 14,073 |
https://leetcode.com/problems/transpose-matrix/discuss/2775314/Python-one-liner-without-numpy | class Solution:
def transpose(self, matrix: List[List[int]]) -> List[List[int]]:
return zip(*matrix) | transpose-matrix | Python one-liner - without numpy | denfedex | 0 | 4 | transpose matrix | 867 | 0.635 | Easy | 14,074 |
https://leetcode.com/problems/transpose-matrix/discuss/2772054/Python3-95-faster-with-explanation | class Solution:
def transpose(self, matrix: List[List[int]]) -> List[List[int]]:
rlist = []
while len(rlist) < len(matrix[0]):
rlist.append([])
for row in matrix:
i = 0
for item in row:
rlist[i].append(item)
i += 1
return rlist | transpose-matrix | Python3, 95% faster with explanation | cvelazquez322 | 0 | 8 | transpose matrix | 867 | 0.635 | Easy | 14,075 |
https://leetcode.com/problems/transpose-matrix/discuss/2756146/Python3-Solution-oror-Using-Lists | class Solution:
def transpose(self, matrix: List[List[int]]) -> List[List[int]]:
new = []
for i in range(len(matrix[0])):
tmp = []
for j in range(len(matrix)):
tmp.append(matrix[j][i])
new.append(tmp)
return new | transpose-matrix | Python3 Solution || Using Lists | shashank_shashi | 0 | 3 | transpose matrix | 867 | 0.635 | Easy | 14,076 |
https://leetcode.com/problems/transpose-matrix/discuss/2750823/Python-Solution | class Solution:
def transpose(self, matrix: List[List[int]]) -> List[List[int]]:
m = len(matrix)
n = len(matrix[0])
t_matrix = [[None for _ in range(m)] for _ in range(n)]
for i in range(m):
for j in range(n):
t_matrix[j][i] = matrix[i][j]
return t_matrix | transpose-matrix | Python Solution | mansoorafzal | 0 | 3 | transpose matrix | 867 | 0.635 | Easy | 14,077 |
https://leetcode.com/problems/transpose-matrix/discuss/2732959/Easy-Approach | class Solution:
def transpose(self, matrix: List[List[int]]) -> List[List[int]]:
rows = len(matrix)
cols = len(matrix[0])
res = []
for c in range(cols):
temp = []
for r in range(rows):
temp.append(matrix[r][c])
res.append(temp)
return res | transpose-matrix | Easy Approach | wakadoodle | 0 | 2 | transpose matrix | 867 | 0.635 | Easy | 14,078 |
https://leetcode.com/problems/transpose-matrix/discuss/2719460/python-sol | class Solution:
def transpose(self, matrix: List[List[int]]) -> List[List[int]]:
r=[[1]*len(matrix) for i in range(len(matrix[0]))]
for i in range(len(matrix)):
for j in range(len(matrix[0])):
r[j][i]=matrix[i][j]
return r | transpose-matrix | python sol | Vtu14918 | 0 | 3 | transpose matrix | 867 | 0.635 | Easy | 14,079 |
https://leetcode.com/problems/transpose-matrix/discuss/2718898/Python3 | class Solution:
def transpose(self, matrix: List[List[int]]) -> List[List[int]]:
rows = len(matrix)
cols = len(matrix[0])
res = [[matrix[col][row] for col in range(rows)] for row in range(cols)]
return res | transpose-matrix | Python3 | yzhao05 | 0 | 3 | transpose matrix | 867 | 0.635 | Easy | 14,080 |
https://leetcode.com/problems/transpose-matrix/discuss/2224051/Python-Solution-using-map | class Solution:
def transpose(self, mat: List[List[int]]) -> List[List[int]]:
# We assume that each row has the same amount of column
lenCol = len(mat[0])
# If there's 4 column then [0, 1, 2, 3]
listIndexCol = range(0, lenCol)
# This lambda function return the column i of a matrix
column = lambda matrix, i: map(lambda row: row[i], matrix)
# By doing an iteration on listIndexCol, we simply transpose the matrice
return list(map(lambda indexCol: column(mat, indexCol), listIndexCol)) | transpose-matrix | Python - Solution using map | gibisi | 0 | 52 | transpose matrix | 867 | 0.635 | Easy | 14,081 |
https://leetcode.com/problems/transpose-matrix/discuss/2121962/Python3-List-Comprehension-1-Liner | class Solution:
def transpose(self, matrix: List[List[int]]) -> List[List[int]]:
return [[matrix[j][i] for j in range(len(matrix))] for i in range(len(matrix[0]))] | transpose-matrix | [Python3] List Comprehension 1 Liner | betaRobin | 0 | 26 | transpose matrix | 867 | 0.635 | Easy | 14,082 |
https://leetcode.com/problems/transpose-matrix/discuss/2104611/Python-solution-or-just-5-lines-of-code-or-Easy-to-understand | class Solution:
def transpose(self, matrix: List[List[int]]) -> List[List[int]]:
y=[list() for i in range(len(matrix[0]))]
for j in range(0,len(matrix[0])):
for i in range(len(matrix)):
y[j].append(matrix[i][j])
return y | transpose-matrix | Python solution | just 5 lines of code | Easy to understand | arjunkhatiwadaarjun | 0 | 27 | transpose matrix | 867 | 0.635 | Easy | 14,083 |
https://leetcode.com/problems/transpose-matrix/discuss/2104004/Python3-Nested-List-Comprehension-Solution | class Solution:
def transpose(self, matrix: List[List[int]]) -> List[List[int]]:
return [[matrix[i][j] for i in range(len(matrix))] for j in range(len(matrix[0]))] | transpose-matrix | Python3 Nested List Comprehension Solution | grandpaboy | 0 | 10 | transpose matrix | 867 | 0.635 | Easy | 14,084 |
https://leetcode.com/problems/transpose-matrix/discuss/2103694/simple-solution-or-99.75-faster-or-91-spaceor-well-explained | class Solution:
def transpose(self, matrix: List[List[int]]) -> List[List[int]]:
rows = len(matrix)
cols = len(matrix[0])
res = []
i = 1
maxItr = cols
while maxItr > 0:
res.append([m[-i] for m in matrix])
maxItr -= 1
i += 1
return res[::-1] | transpose-matrix | simple solution | 99.75% faster | 91% space| well explained | sanketsans | 0 | 16 | transpose matrix | 867 | 0.635 | Easy | 14,085 |
https://leetcode.com/problems/transpose-matrix/discuss/2103685/python3-solution | class Solution:
def transpose(self, matrix: List[List[int]]) -> List[List[int]]:
newlist = []
for i in range(len(matrix[0])):
data = []
for j in matrix:
data.append(j[i])
newlist.append(data)
return newlist | transpose-matrix | python3 solution | gfhdfd123 | 0 | 15 | transpose matrix | 867 | 0.635 | Easy | 14,086 |
https://leetcode.com/problems/transpose-matrix/discuss/2103301/O(n)-Python-Solutionsimple | class Solution:
def transpose(self, matrix: List[List[int]]) -> List[List[int]]:
n = len(matrix)
m = len(matrix[0])
ans = [[] for i in range(len(matrix[0]))]
for i in range(n):
row = matrix[i]
for j in range(m):
ans[j].append(matrix[i][j])
return ans | transpose-matrix | O(n) Python Solution[simple] | Tobi_Akin | 0 | 20 | transpose matrix | 867 | 0.635 | Easy | 14,087 |
https://leetcode.com/problems/transpose-matrix/discuss/2103129/Runtime%3A-75-ms-faster-than-88.58-of-Python3.-Memory-Usage%3A-14.7-MB-less-than-55.33 | class Solution:
def transpose(self, matrix: List[List[int]]) -> List[List[int]]:
rows = len(matrix[0])
cols = len(matrix)
# Creating a transpose matrix will all entries a zero.
arr=[]
for i in range(rows):
col = []
for j in range(cols):
col.append(0)
arr.append(col)
# Now, changing the values in the transpose matrix using 'matrix'(given)
for i in range(len(matrix)):
for j in range(len(matrix[0])):
arr[j][i] = matrix[i][j]
return arr | transpose-matrix | Runtime: 75 ms, faster than 88.58% of Python3. Memory Usage: 14.7 MB, less than 55.33% | swift_guy | 0 | 11 | transpose matrix | 867 | 0.635 | Easy | 14,088 |
https://leetcode.com/problems/transpose-matrix/discuss/2102966/Python-or-Easy-and-Understanding-Solution | class Solution:
def transpose(self, matrix: List[List[int]]) -> List[List[int]]:
n=len(matrix)
m=len(matrix[0])
transpose=[[0 for j in range(n)] for i in range(m)]
for i in range(m):
for j in range(n):
transpose[i][j]=matrix[j][i]
return transpose | transpose-matrix | Python | Easy & Understanding Solution | backpropagator | 0 | 22 | transpose matrix | 867 | 0.635 | Easy | 14,089 |
https://leetcode.com/problems/transpose-matrix/discuss/2101729/Python3-Easy-to-understand-solution | class Solution:
def transpose(self, matrix: List[List[int]]) -> List[List[int]]:
rows=len(matrix) ## Get the number of rows
columns=len(matrix[0]) ## Get the number of columns
## if the source matrix is MxN then transposed matrix will be NxM
transposedMatrix=[ [None for _ in range(rows)] for _ in range(columns)]
columnT=0 ## Column pointer in the transposed matrix
for row in matrix: ## for each row in the original matrix
currRowT=0 ## Row pointer in the transposed matrix
for i, element in enumerate(row):
transposedMatrix[currRowT][columnT]=row[i] ##row of original matrix becomes the column of the transposed matrix
currRowT+=1 ## increment the row
columnT+=1 ## increment the column pointer
return transposedMatrix | transpose-matrix | Python3 Easy to understand solution | mavericktopGun | 0 | 9 | transpose matrix | 867 | 0.635 | Easy | 14,090 |
https://leetcode.com/problems/transpose-matrix/discuss/2101390/Python3-Solution-with-using-additional-matrix | class Solution:
def transpose(self, matrix: List[List[int]]) -> List[List[int]]:
res = []
for j in range(len(matrix[0])):
res.append([])
for i in range(len(matrix)):
res[j].append(matrix[i][j])
return res | transpose-matrix | [Python3] Solution with using additional matrix | maosipov11 | 0 | 17 | transpose matrix | 867 | 0.635 | Easy | 14,091 |
https://leetcode.com/problems/transpose-matrix/discuss/2101184/java-python-easy-to-understand | class Solution:
def transpose(self, matrix: List[List[int]]) -> List[List[int]]:
transposed = []
for j in range(len(matrix[0])):
transposed.append([0]*len(matrix))
for i in range(len(matrix)):
transposed[-1][i] = matrix[i][j]
return transposed | transpose-matrix | java, python - easy to understand | ZX007java | 0 | 12 | transpose matrix | 867 | 0.635 | Easy | 14,092 |
https://leetcode.com/problems/transpose-matrix/discuss/2101116/Transpose-Matrixx | class Solution:
def transpose(self, matrix: List[List[int]]) -> List[List[int]]:
return numpy.transpose(matrix) | transpose-matrix | Transpose Matrixx | Sai_Prasoona_Moolpuru | 0 | 11 | transpose matrix | 867 | 0.635 | Easy | 14,093 |
https://leetcode.com/problems/transpose-matrix/discuss/2101041/Python-One-Liner-oror-80ms-Beats-80 | class Solution:
def transpose(self, matrix: List[List[int]]) -> List[List[int]]:
return [[matrix[j][i] for j in range(len(matrix))] for i in range(len(matrix[0]))] | transpose-matrix | Python One Liner || 80ms - Beats 80% | Pootato | 0 | 12 | transpose matrix | 867 | 0.635 | Easy | 14,094 |
https://leetcode.com/problems/transpose-matrix/discuss/2100764/python-solution-using-easy-approach | class Solution(object):
def transpose(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[List[int]]
"""
m , n= len(matrix) , len(matrix[0])
res = [[0 for i in range(m)] for i in range(n)]
for i in range(m):
for j in range(n):
res[j][i] = matrix[i][j]
return res | transpose-matrix | python solution using easy approach | jhaprashant1108 | 0 | 16 | transpose matrix | 867 | 0.635 | Easy | 14,095 |
https://leetcode.com/problems/transpose-matrix/discuss/2100604/Python-84.25-Faster-oror-Simple-Python-Solution-By-Swapping-Row-and-Column | class Solution:
def transpose(self, matrix: List[List[int]]) -> List[List[int]]:
result_mat = [[0 for _ in range(len(matrix))] for _ in range(len(matrix[0]))]
for row in range(len(matrix)):
for col in range(len(matrix[row])):
result_mat[col][row] = matrix[row][col]
return result_mat | transpose-matrix | [ Python ] ✅✅ 84.25% Faster || Simple Python Solution By Swapping Row and Column 🥳✌👍 | ASHOK_KUMAR_MEGHVANSHI | 0 | 23 | transpose matrix | 867 | 0.635 | Easy | 14,096 |
https://leetcode.com/problems/transpose-matrix/discuss/2100353/Life-is-short-Use-Python-or-No-Extra-Space-or-One-Liner | class Solution:
def transpose(self, matrix: List[List[int]]) -> List[List[int]]:
return list(zip(*matrix)) | transpose-matrix | Life is short - Use Python | No Extra Space | One Liner | morgans_lc | 0 | 26 | transpose matrix | 867 | 0.635 | Easy | 14,097 |
https://leetcode.com/problems/transpose-matrix/discuss/2100334/Python-Easy-Solution | class Solution:
def transpose(self, matrix: List[List[int]]) -> List[List[int]]:
t = [] # t --> transposed
# outer loop (over rows)
for i in range(len(matrix[0])):
# Inner Loop --> append each column as a row
t.append([matrix[j][i] for j in range(len(matrix))])
return t | transpose-matrix | Python Easy Solution | pe-mn | 0 | 13 | transpose matrix | 867 | 0.635 | Easy | 14,098 |
https://leetcode.com/problems/transpose-matrix/discuss/2100300/Solution-Python-or-TC-O(n2) | class Solution:
def transpose(self, matrix: List[List[int]]) -> List[List[int]]:
result = [[0 for i in range(len(matrix))] for j in range(len(matrix[0]))]
for i in range(len(matrix)):
for j in range(len(matrix[0])):
result[j][i] = matrix[i][j]
return result | transpose-matrix | Solution Python | TC O(n^2) | reeteshz | 0 | 10 | transpose matrix | 867 | 0.635 | Easy | 14,099 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.