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/flatten-binary-tree-to-linked-list/discuss/2338726/Python3-recursive-approach
class Solution: def __init__(self): self.prev = None def flatten(self, root): if not root: return None self.flatten(root.right) self.flatten(root.left) root.right = self.prev root.left = None self.prev = root
flatten-binary-tree-to-linked-list
πŸ“Œ Python3 recursive approach
Dark_wolf_jss
6
360
flatten binary tree to linked list
114
0.612
Medium
900
https://leetcode.com/problems/flatten-binary-tree-to-linked-list/discuss/1608790/Pythonor-Simple-and-Easy-2-approachesor-Faster-than-98.13
class Solution: def flatten(self, root: Optional[TreeNode]) -> None: """ Do not return anything, modify root in-place instead. """ #writing the function to flatten the binary tree def helper(root): """ param type root: TreeNode rtype root """ if not root: return left_end = helper(root.left) right_end = helper(root.right) if left_end: left_end.right = root.right root.right = root.left root.left = None end_pointer = right_end or left_end or root return end_pointer helper(root)
flatten-binary-tree-to-linked-list
Python| Simple and Easy 2 approaches| Faster than 98.13%
lunarcrab
3
181
flatten binary tree to linked list
114
0.612
Medium
901
https://leetcode.com/problems/flatten-binary-tree-to-linked-list/discuss/1608790/Pythonor-Simple-and-Easy-2-approachesor-Faster-than-98.13
class Solution: def flatten(self, root: Optional[TreeNode]) -> None: """ Do not return anything, modify root in-place instead. """ res=[] # Functtion to return the preorder Traversal def helper(root): if not root: return res.append(root.val) helper(root.left) helper(root.right) helper(root) #iterating through the res list to create a flattened list for i in range(1,len(res)): temp = TreeNode(res[i]) root.right = temp root.left = None root= root.right
flatten-binary-tree-to-linked-list
Python| Simple and Easy 2 approaches| Faster than 98.13%
lunarcrab
3
181
flatten binary tree to linked list
114
0.612
Medium
902
https://leetcode.com/problems/flatten-binary-tree-to-linked-list/discuss/750312/Python3-Solution-with-a-Detailed-Explanation-Flatten-binary-tree-to-linkedlist
class Solution: def flatten(self, root): if not root: #1 return if root.left: #2 self.flatten(root.left) #3 temp = root.right #4 root.right = root.left #5 root.left = None #6 curr = root.right #7 while curr.right: #8 curr = curr.right #9 curr.right = temp #10 if root.right: #11 self.flatten(root.right)
flatten-binary-tree-to-linked-list
Python3 Solution with a Detailed Explanation - Flatten binary tree to linkedlist
peyman_np
2
205
flatten binary tree to linked list
114
0.612
Medium
903
https://leetcode.com/problems/flatten-binary-tree-to-linked-list/discuss/2345900/Py-or-2-iterative-methods-or-O(1)-space
class Solution: def flatten(self, root: Optional[TreeNode]) -> None: """ Do not return anything, modify root in-place instead. """ if not root: return prev = None stack = [root] while stack: node = stack.pop() if node.right: stack.append(node.right) if node.left: stack.append(node.left) if prev: prev.left = None prev.right = node prev = node # iterative dfs # O(n) # O(log n) if balanced O(n) if singly linked def flatten(self, root: Optional[TreeNode]) -> None: if not root: return node = root while node: if node.left: # move left child to right rightMost = node.left while rightMost.right: # find first child without right rightMost = rightMost.right rightMost.right = node.right # still keeps the same pre order node.right = node.left node.left = None node = node.right # O(n) time # O(1) space
flatten-binary-tree-to-linked-list
Py | 2 iterative methods | O(1) space
XUEYANZ
1
63
flatten binary tree to linked list
114
0.612
Medium
904
https://leetcode.com/problems/flatten-binary-tree-to-linked-list/discuss/2040103/O(n)timeBEATS-99.97-MEMORYSPEED-0ms-MAY-2022
class Solution: def flatten(self, root: TreeNode) -> None: head, curr = None, root while head != root: if curr.right == head: curr.right = None if curr.left == head: curr.left = None if curr.right: curr = curr.right elif curr.left: curr = curr.left else: curr.right, head, curr = head, curr, root
flatten-binary-tree-to-linked-list
O(n)time/BEATS 99.97% MEMORY/SPEED 0ms MAY 2022
cucerdariancatalin
1
98
flatten binary tree to linked list
114
0.612
Medium
905
https://leetcode.com/problems/flatten-binary-tree-to-linked-list/discuss/1603835/Python-3-line-recursive
class Solution: def flatten(self, root: Optional[TreeNode], right=None) -> None: if not root: return right root.left, root.right = None, self.flatten(root.left, self.flatten(root.right, right)) return root
flatten-binary-tree-to-linked-list
[Python] 3-line recursive
hooneken
1
117
flatten binary tree to linked list
114
0.612
Medium
906
https://leetcode.com/problems/flatten-binary-tree-to-linked-list/discuss/1603835/Python-3-line-recursive
class Solution: def flatten(self, root: Optional[TreeNode]) -> None: cur = root while cur: left = cur.left if left: while left.right: left = left.right left.right = cur.right cur.left, cur.right = None, cur.left cur = cur.right return root
flatten-binary-tree-to-linked-list
[Python] 3-line recursive
hooneken
1
117
flatten binary tree to linked list
114
0.612
Medium
907
https://leetcode.com/problems/flatten-binary-tree-to-linked-list/discuss/1474276/Python-iterative-solution-using-preorder
class Solution: def flatten(self, root: TreeNode) -> None: """ Do not return anything, modify root in-place instead. """ # curr = TreeNode(0) if not root: return None stack = [root] while len(stack)>0: temp = stack.pop() # here, first we will iteratively add both the child of the current node in our stack if temp.right: stack.append(temp.right) if temp.left: stack.append(temp.left) #to mark the beginning of our flattened linkedlist if temp==root: curr = root #in each case, left child will be none curr.left = None else: curr.right = temp #in each case, left child will be none curr.left = None curr = curr.right
flatten-binary-tree-to-linked-list
Python iterative solution, using preorder
Ridzzz
1
170
flatten binary tree to linked list
114
0.612
Medium
908
https://leetcode.com/problems/flatten-binary-tree-to-linked-list/discuss/1398415/Python-Clean-and-Easy-or-92.29-speed
class Solution: def flatten(self, root: TreeNode) -> None: if not root: return queue = deque([root.right, root.left]) while queue: node = queue.pop() if not node: continue root.left, root.right = None, node root = root.right queue.append(node.right), queue.append(node.left)
flatten-binary-tree-to-linked-list
[Python] Clean and Easy | 92.29% speed
soma28
1
155
flatten binary tree to linked list
114
0.612
Medium
909
https://leetcode.com/problems/flatten-binary-tree-to-linked-list/discuss/696054/Python-DFS-Solution-Easy-to-Understand
class Solution: # Time: O(n) # Space: O(H) def flatten(self, node: TreeNode) -> None: """ Do not return anything, modify root in-place instead. """ if not node: return self.flatten(node.left) self.flatten(node.right) if not node.right and node.left: node.right, node.left = node.left, None if node.left and node.right: left_side = node.left while left_side.right: left_side = left_side.right left_side.right, node.right, node.left = node.right, node.left, None
flatten-binary-tree-to-linked-list
Python DFS Solution Easy to Understand
whissely
1
156
flatten binary tree to linked list
114
0.612
Medium
910
https://leetcode.com/problems/flatten-binary-tree-to-linked-list/discuss/692703/Python3-5-line-recursive
class Solution: def flatten(self, root: TreeNode) -> None: def fn(node, tail=None): """Return head of flattened binary tree""" if not node: return tail node.left, node.right = None, fn(node.left, fn(node.right, tail)) return node fn(root)
flatten-binary-tree-to-linked-list
[Python3] 5-line recursive
ye15
1
109
flatten binary tree to linked list
114
0.612
Medium
911
https://leetcode.com/problems/flatten-binary-tree-to-linked-list/discuss/2730476/Striver-approach
class Solution: def flatten(self, root: Optional[TreeNode]) -> None: prev = None def solve(node): nonlocal prev if not node: return None solve(node.right) solve(node.left) node.right = prev node.left = None prev = node solve(root)
flatten-binary-tree-to-linked-list
Striver approach
hacktheirlives
0
4
flatten binary tree to linked list
114
0.612
Medium
912
https://leetcode.com/problems/flatten-binary-tree-to-linked-list/discuss/2688353/python-or-recursion
class Solution: def flatten(self, root: Optional[TreeNode]) -> None: def helper(root): if not root: return None # get leaf left = helper(root.left) right = helper(root.right) # left leaf move to right subtree root.left = None root.right = left # because we add left subtree to right substree, we need to get the right node of # the previous right substree node = root while node.right: node = node.right node.right = right return root helper(root)
flatten-binary-tree-to-linked-list
python | recursion
MichelleZou
0
9
flatten binary tree to linked list
114
0.612
Medium
913
https://leetcode.com/problems/flatten-binary-tree-to-linked-list/discuss/2459663/Python-Recursive-Approach
class Solution: def flatten(self, root: Optional[TreeNode]) -> None: def dfs(root): while root: if root.left: dfs(root.left) node1 = root.left while node1.right: node1 = node1.right node2 = root.right root.right = root.left node1.right = node2 root.left = None root = root.right # for terminating dfs(root)
flatten-binary-tree-to-linked-list
Python Recursive Approach
Abhi_009
0
35
flatten binary tree to linked list
114
0.612
Medium
914
https://leetcode.com/problems/flatten-binary-tree-to-linked-list/discuss/2346551/Easy-peasy-Solution-in-Python-3-which-cannot-be-difficult
class Solution: def flatten(self, root: Optional[TreeNode]) -> None: if not root: return root elif not root.left and not root.right: return root stack, nums = [root], [] while stack: node = stack.pop() if node: nums.append(node) stack.append(node.right) stack.append(node.left) cursor = root for i in nums[1:]: cursor.left = None cursor.right = i cursor = cursor.right
flatten-binary-tree-to-linked-list
Easy-peasy Solution in Python 3, which cannot be difficult
HappyLunchJazz
0
38
flatten binary tree to linked list
114
0.612
Medium
915
https://leetcode.com/problems/flatten-binary-tree-to-linked-list/discuss/2342956/Python-Bruteforce-With-Preorder-Traversal-Helper
class Solution: def flatten(self, root: Optional[TreeNode]) -> None: preorder = [] self.helper(root, preorder) for node in preorder[1:]: root.left = None root.right = node root = root.right def helper(self, root, preorder): if root: preorder.append(root) self.helper(root.left, preorder) self.helper(root.right, preorder)
flatten-binary-tree-to-linked-list
Python Bruteforce With Preorder Traversal Helper
HunkWhoCodes
0
7
flatten binary tree to linked list
114
0.612
Medium
916
https://leetcode.com/problems/flatten-binary-tree-to-linked-list/discuss/2342478/Python-solution-or-Flatten-Binary-Tree-to-Linked-List
class Solution: def flatten(self, root: Optional[TreeNode]) -> None: if not root: return None left = self.flatten(root.left) right = self.flatten(root.right) if root.left: left.right = root.right root.right = root.left root.left = None lastVal = right or left or root return lastVal
flatten-binary-tree-to-linked-list
Python solution | Flatten Binary Tree to Linked List
nishanrahman1994
0
15
flatten binary tree to linked list
114
0.612
Medium
917
https://leetcode.com/problems/flatten-binary-tree-to-linked-list/discuss/2342382/Easy-Python-With-Explanation-DFS-wRecursion
class Solution: def flatten(self, root: Optional[TreeNode]) -> None: """ Do not return anything, modify root in-place instead. """ # Depth-first recursion def dfs(node): # Recursion base case # do nothing if none if not node: return # Check for leaf elif not node.left and not node.right: # Return leafs return node # Flatten left and right subtrees node_left = dfs(node.left) node_right = dfs(node.right) # Switch left subtree to the right if node_left: # Get to end of right subtree # Maintain head head = node_left while node_left.right: node_left = node_left.right # Add right subtree to end of left subtree node_left.right = node.right # Set right to head of left subtree node.right = head # Remove left subtree node.left = None # Return flattened subtree return node # Flatten Tree dfs(root)
flatten-binary-tree-to-linked-list
Easy Python With Explanation DFS w/Recursion
drblessing
0
17
flatten binary tree to linked list
114
0.612
Medium
918
https://leetcode.com/problems/flatten-binary-tree-to-linked-list/discuss/2342018/Python-Simple-Python-Solution-Using-Depth-First-Search
class Solution: def flatten(self, root: Optional[TreeNode]) -> None: """ Do not return anything, modify root in-place instead. """ self.previous_node = None def DepthFirstSearch(root): if root is None: return None DepthFirstSearch(root.right) DepthFirstSearch(root.left) root.right = self.previous_node root.left = None self.previous_node = root return root DepthFirstSearch(root) return root
flatten-binary-tree-to-linked-list
[ Python ] βœ…βœ… Simple Python Solution Using Depth First Search πŸ”₯✌ πŸ₯³πŸ‘
ASHOK_KUMAR_MEGHVANSHI
0
27
flatten binary tree to linked list
114
0.612
Medium
919
https://leetcode.com/problems/flatten-binary-tree-to-linked-list/discuss/2341111/Very-simple-and-short-python-code
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def flatten(self, root: Optional[TreeNode]) -> None: """ Do not return anything, modify root in-place instead. """ def flatten(n): tail = n tmp = n.right if n.left: tail = flatten(n.left) n.right = n.left n.left = None if tmp: newtail = flatten(tmp) tail.right = tmp return newtail return tail if root: flatten(root)
flatten-binary-tree-to-linked-list
Very simple and short python code
pradyumna04
0
5
flatten binary tree to linked list
114
0.612
Medium
920
https://leetcode.com/problems/flatten-binary-tree-to-linked-list/discuss/2341053/Beginner's-Solution-Python
class linkedlist: def __init__(self): self.head = None self.tail = None def flatten(self, root: Optional[TreeNode]) -> None: """ Do not return anything, modify root in-place instead. """ if root == None: return root result = self.helper(root) return result.head def helper(self, root): ll = self.linkedlist() # base case if root.left == None and root.right == None: ll.head = ll.tail = root elif root.left != None and root.right== None: temp = self.helper(root.left) ll.head = root root.right = temp.head ll.tail = temp.tail elif root.left == None and root.right != None: temp = self.helper(root.right) ll.head = root root.right = temp.head ll.tail = temp.tail else: templeft = self.helper(root.left) tempright = self.helper(root.right) ll.head = root root.right = templeft.head templeft.tail.right = tempright.head ll.tail = tempright.tail root.left = None return ll
flatten-binary-tree-to-linked-list
Beginner's Solution - Python
niteshjyo
0
18
flatten binary tree to linked list
114
0.612
Medium
921
https://leetcode.com/problems/flatten-binary-tree-to-linked-list/discuss/2340023/Python-39ms-oror-Simple-Recursive-2-Tail-Pointers-Space-O(1)-oror-Documented
class Solution: def flatten(self, root: Optional[TreeNode]) -> None: # flatten given root of binary tree and return the tail of linked list def recursive(node) -> Optional[TreeNode]: if node: # these will be leaf nodes of the given subtrees/linked list tailLeft = recursive(node.left) tailRight = recursive(node.right) if tailLeft: # Set node's left subtree to its right, and then make it null tailLeft.right = node.right node.right = node.left node.left = None # return leaf node of the linked list return tailRight or tailLeft or node recursive(root)
flatten-binary-tree-to-linked-list
[Python] 39ms || Simple Recursive 2-Tail Pointers - Space O(1) || Documented
Buntynara
0
4
flatten binary tree to linked list
114
0.612
Medium
922
https://leetcode.com/problems/flatten-binary-tree-to-linked-list/discuss/2339175/Python-simple-commented-recursive-solution
class Solution: def flatten(self, root: Optional[TreeNode]) -> None: """ Do not return anything, modify root in-place instead. """ if not root: return None # left is the last node of the left subtree. # and similarly right is the last node of the right subtree left = self.flatten(root.left) right = self.flatten(root.right) if left: # First, we join the last node of left subtree to first node in right subtree # Then we move the left subtree to the right of the node, and delete the left subtree pointer left.right = root.right root.right = root.left root.left = None # if theres a right subtree, we return its last node, failing which the last node of the left subtree, # and if none are present (i.e. its a leaf node), we return the node itself. return right or left or root
flatten-binary-tree-to-linked-list
Python simple commented recursive solution
kaustav43
0
12
flatten binary tree to linked list
114
0.612
Medium
923
https://leetcode.com/problems/distinct-subsequences/discuss/1472969/Python-Bottom-up-DP-Explained
class Solution: def numDistinct(self, s: str, t: str) -> int: m = len(s) n = len(t) dp = [[0] * (n+1) for _ in range(m+1)] for i in range(m+1): dp[i][0] = 1 """redundant, as we have initialised dp table with full of zeros""" # for i in range(1, n+1): # dp[0][i] = 0 for i in range(1, m+1): for j in range(1, n+1): dp[i][j] += dp[i-1][j] #if current character is skipped if s[i-1] == t[j-1]: dp[i][j] += dp[i-1][j-1] #if current character is used return dp[-1][-1]
distinct-subsequences
Python - Bottom up DP - Explained
ajith6198
6
475
distinct subsequences
115
0.439
Hard
924
https://leetcode.com/problems/distinct-subsequences/discuss/2040129/O(n)timeBEATS-99.97-MEMORYSPEED-0ms-MAY-2022
class Solution: def numDistinct(self, s: str, t: str) -> int: ## RC ## ## APPROACH : DP ## ## LOGIC ## # 1. Point to be noted, empty seq is also subsequence of any sequence i.e "", "" should return 1. so we fill the first row accordingly # 2. if chars match, we get the maximum of [diagonal + upper, upper + 1] (Try below example) # 3. if no match, we pull the upper value ## EXAMPLE : "axacccax" "aca" ## ## STACK TRACE ## # [ "" a c a # "" [1, 0, 0, 0], # a [1, 1, 0, 0], # x [1, 1, 0, 0], # a [1, 2, 0, 0], # c [1, 2, 2, 0], # c [1, 2, 4, 0], # c [1, 2, 6, 0], # a [1, 3, 6, 6], # ] ## TIME COMPLEXITY : O(MxN) ## ## SPACE COMPLEXITY : O(MxN) ## dp = [[0] * (len(t)+1) for _ in range(len(s)+1)] for k in range(len(dp)): dp[k][0] = 1 for i in range(1, len(dp)): for j in range(1, len(dp[0])): if(s[i-1] == t[j-1] and dp[i-1][j-1]): dp[i][j] = max(dp[i-1][j-1] + dp[i-1][j], dp[i-1][j]+1) else: dp[i][j] = dp[i-1][j] # print(dp) return dp[-1][-1]
distinct-subsequences
O(n)time/BEATS 99.97% MEMORY/SPEED 0ms MAY 2022
cucerdariancatalin
4
231
distinct subsequences
115
0.439
Hard
925
https://leetcode.com/problems/distinct-subsequences/discuss/2775154/Linear-order-Python-Easy-Solution
class Solution: def numDistinct(self, s: str, t: str) -> int: def disSub(s,t,ind_s,ind_t,dp): if ind_t<0: return 1 if ind_s<0: return 0 if s[ind_s]==t[ind_t]: if (dp[ind_t])[ind_s]!=-1: return (dp[ind_t])[ind_s] else: (dp[ind_t])[ind_s]=(disSub(s,t,ind_s-1,ind_t-1,dp) + disSub(s,t,ind_s-1,ind_t,dp)) return (dp[ind_t])[ind_s] (dp[ind_t])[ind_s]=disSub(s,t,ind_s-1,ind_t,dp) return (dp[ind_t])[ind_s] ls=len(s) lt=len(t) dp=[[-1]* ls for i in range(lt)] return disSub(s,t,ls-1,lt-1,dp)
distinct-subsequences
Linear order Python Easy Solution
Khan_Baba
2
176
distinct subsequences
115
0.439
Hard
926
https://leetcode.com/problems/distinct-subsequences/discuss/2775154/Linear-order-Python-Easy-Solution
class Solution: def numDistinct(self, s: str, t: str) -> int: ls=len(s) lt=len(t) dp=[[0]*(ls+1) for i in range(lt+1)] for i in range(ls): (dp[0])[i]=1 for ind_t in range(1,lt+1): for ind_s in range (1,ls+1): if s[ind_s-1]==t[ind_t-1]: (dp[ind_t])[ind_s]= (dp[ind_t -1])[ind_s -1] +(dp[ind_t])[ind_s -1] else: (dp[ind_t])[ind_s]= (dp[ind_t])[ind_s -1] return (dp[ind_t])[ind_s]
distinct-subsequences
Linear order Python Easy Solution
Khan_Baba
2
176
distinct subsequences
115
0.439
Hard
927
https://leetcode.com/problems/distinct-subsequences/discuss/2775154/Linear-order-Python-Easy-Solution
class Solution: def numDistinct(self, s: str, t: str) -> int: ls=len(s) lt=len(t) prev=[1]*(ls+1) for ind_t in range(1,lt+1): temp=[0]*(ls+1) for ind_s in range (1,ls+1): if s[ind_s-1]==t[ind_t-1]: temp[ind_s]= prev[ind_s -1]+temp[ind_s -1] else: temp[ind_s]= temp[ind_s -1] prev=temp return prev[ind_s]
distinct-subsequences
Linear order Python Easy Solution
Khan_Baba
2
176
distinct subsequences
115
0.439
Hard
928
https://leetcode.com/problems/distinct-subsequences/discuss/2437315/Python-DP-O(m*n)-Time
class Solution: def numDistinct(self, s: str, t: str) -> int: dp = [[0] * (len(s)+1) for _ in range(len(t)+1)] # 0th row => len(t) == 0 and len(s) can be anything. So empty string t can be Subsequence of s for j in range(len(s)+1): dp[0][j] = 1 for i in range(1, len(t)+1): for j in range(1, len(s)+1): dp[i][j] += dp[i][j-1] # skip the current character s[j-1] if t[i-1] == s[j-1]: dp[i][j] += dp[i-1][j-1] # current character s[j-1] is used return dp[-1][-1]
distinct-subsequences
Python - DP - O(m*n) Time
samirpaul1
1
44
distinct subsequences
115
0.439
Hard
929
https://leetcode.com/problems/distinct-subsequences/discuss/580112/DP-Solution-(Beats-99-in-Time-58-in-Space)
class Solution: def numDistinct(self, s: str, t: str) -> int: c_indices = collections.defaultdict(list) max_counts = [1] + [0] * len(t) for i, c in enumerate(t): c_indices[c].append(i + 1) for c in s: for i in reversed(c_indices[c]): max_counts[i] += max_counts[i - 1] return max_counts[-1]
distinct-subsequences
DP Solution (Beats 99% in Time, 58% in Space)
skarakulak
1
208
distinct subsequences
115
0.439
Hard
930
https://leetcode.com/problems/distinct-subsequences/discuss/2805876/Python-bottom-up-approach
class Solution: def numDistinct(self, s: str, t: str) -> int: n = len(s) m = len(t) if n<m: return 0 dp = [1]+[0]*m for i in range(n): for j in reversed(range(m)): if s[i]==t[j]: dp[j+1]+=dp[j] return dp[m]
distinct-subsequences
Python bottom up approach
Akshit-Gupta
0
2
distinct subsequences
115
0.439
Hard
931
https://leetcode.com/problems/distinct-subsequences/discuss/2784680/Python(Tabulation)
class Solution: def numDistinct(self, s: str, t: str) -> int: dp=[[0]*(len(t)+1) for i in range(len(s)+1)] for i in range(len(s)+1): dp[i][0]=1 for i in range(1,len(s)+1): for j in range(1,len(t)+1): if s[i-1]==t[j-1]: dp[i][j] = dp[i-1][j]+dp[i-1][j-1] else: dp[i][j] = dp[i-1][j] return dp[len(s)][len(t)] ''' dp=[[-1]*len(t) for i in range(len(s))] def solve(ind1,ind2): if ind2<0: return 1 if ind1<0: return 0 if dp[ind1][ind2]!=-1: return dp[ind1][ind2] if s[ind1]==t[ind2]: dp[ind1][ind2] = solve(ind1-1,ind2-1)+solve(ind1-1,ind2) return dp[ind1][ind2] else: dp[ind1][ind2] = solve(ind1-1,ind2) return dp[ind1][ind2] return solve(len(s)-1,len(t)-1) '''
distinct-subsequences
Python(Tabulation)
parasgarg31
0
4
distinct subsequences
115
0.439
Hard
932
https://leetcode.com/problems/distinct-subsequences/discuss/2784674/Simple-Python-Solution(Striver)
class Solution: def numDistinct(self, s: str, t: str) -> int: dp=[[-1]*len(t) for i in range(len(s))] def solve(ind1,ind2): if ind2<0: return 1 if ind1<0: return 0 if dp[ind1][ind2]!=-1: return dp[ind1][ind2] if s[ind1]==t[ind2]: dp[ind1][ind2] = solve(ind1-1,ind2-1)+solve(ind1-1,ind2) return dp[ind1][ind2] else: dp[ind1][ind2] = solve(ind1-1,ind2) return dp[ind1][ind2] return solve(len(s)-1,len(t)-1)
distinct-subsequences
Simple Python Solution(Striver)
parasgarg31
0
3
distinct subsequences
115
0.439
Hard
933
https://leetcode.com/problems/distinct-subsequences/discuss/2760304/Python-Three-approach-recursion-top-down-bottom-up
class Solution: def solve(self , s , t, i , j): if j == 0: return 1 if i == 0: return 0 if s[i-1] == t[j-1]: take = self.solve(s , t, i-1 , j-1) move = self.solve(s , t , i-1 , j) return (take + move) else: return self.solve(s , t, i-1 , j) def numDistinct(self, s: str, t: str) -> int: return self.solve(s , t , len(s) , len(t)) """ Top - down """ class Solution: def solve(self , s , t, i , j , memo): if j == 0: return 1 if i == 0: return 0 if memo[i][j] != -1: return memo[i][j] if s[i-1] == t[j-1]: take = self.solve(s , t, i-1 , j-1 , memo) move = self.solve(s , t , i-1 , j , memo) memo[i][j] = (take + move) return memo[i][j] else: memo[i][j] = self.solve(s , t, i-1 , j , memo) return memo[i][j] def numDistinct(self, s: str, t: str) -> int: memo = [[-1 for j in range(len(t)+1)] for i in range(len(s)+1)] return self.solve(s , t , len(s) , len(t) , memo) """ Bottom - up """ class Solution: def numDistinct(self, s: str, t: str) -> int: dp = [[0 for j in range(len(t)+1)] for i in range(len(s)+1)] for i in range(len(t)+1): dp[0][i] = 0 for i in range(len(s)+1): dp[i][0] = 1 for i in range(1 , len(s)+1): for j in range(1 , len(t)+1): if s[i-1] == t[j-1]: take = dp[i-1][j-1] move = dp[i-1][j] dp[i][j] = (take + move) else: dp[i][j] = dp[i-1][j] return dp[len(s)][len(t)]
distinct-subsequences
Python Three approach recursion , top-down , bottom-up
rajitkumarchauhan99
0
4
distinct subsequences
115
0.439
Hard
934
https://leetcode.com/problems/distinct-subsequences/discuss/2694849/PYTHONoror-EASY-SOLUoror-with-EXPLAINATION-using-DP-Bottomup-approach
class Solution: def numDistinct(self, s: str, t: str) -> int: m=len(s) n=len(t) dp=[] for i in range (m+1): #making dp of m+1 and n+1 dp.append([0]*(n+1)) dp[0][0]=1 #making 1st element of 2d dp as 1 for i in range (m+1): #making 1st column of every row as 1 dp[i][0]=1 for i in range (1,n+1): #making all column as 0 of 1st row leaving first element as it already set to 1 dp[0][i]=0 for i in range (1,m+1): for j in range (1,n+1): if s[i-1]==t[j-1]: #checking if s and t if both equal then add (the previous diagonal element of dp) and (one row before of the same column) i.e [i-1][j] dp[i][j]=dp[i-1][j]+dp[i-1][j-1] else: dp[i][j]=dp[i-1][j] # if not equal then copy the previous i-1 element of the same row in dp return dp[m][n]
distinct-subsequences
PYTHON|| EASY SOLU|| with EXPLAINATION using DP Bottomup approach
tush18
0
8
distinct subsequences
115
0.439
Hard
935
https://leetcode.com/problems/distinct-subsequences/discuss/2431193/Clean-Fast-Python3-or-Bottom-Up-DP-or-O(s-%2B-t)
class Solution: def numDistinct(self, s: str, t: str) -> int: ls, lt = len(s), len(t) if ls < lt: return 0 # dp subseqs = [[0] * (ls + 1) for _ in range(lt + 1)] subseqs[0] = [1] * (ls + 1) letters_seen = set() for ti in range(lt): letters_seen.add(t[ti]) for si in range(ti, ls): left = subseqs[ti + 1][si] up_left = subseqs[ti][si] up = subseqs[ti][si + 1] # always add value from 1 letter back in s, it will never decrease from there subseqs[ti + 1][si + 1] = left # if they match, add min of 1 letter back in t, 1 letter back in both strings # (this min check ensures that we will not count duplicates) if t[ti] == s[si]: subseqs[ti + 1][si + 1] += min(up_left, up) return subseqs[lt][ls]
distinct-subsequences
Clean, Fast Python3 | Bottom Up DP | O(s + t)
ryangrayson
0
9
distinct subsequences
115
0.439
Hard
936
https://leetcode.com/problems/distinct-subsequences/discuss/2429305/Memoization-and-Recursion
class Solution: def numDistinct(self, s: str, t: str) -> int: n, m = len(s), len(t) lookup = {} def f(i, j, lookup): if j<0: return 1 if i<0: return 0 if (i, j) in lookup: return lookup[(i,j)] #matching case if s[i] == t[j]: lookup[(i,j)] = f(i-1, j-1, lookup) + f(i-1, j, lookup) return lookup[(i,j)] lookup[(i,j)] = f(i-1, j, lookup) return lookup[(i,j)] return f(n-1, m-1, lookup)
distinct-subsequences
Memoization & Recursion
logeshsrinivasans
0
16
distinct subsequences
115
0.439
Hard
937
https://leetcode.com/problems/distinct-subsequences/discuss/2429305/Memoization-and-Recursion
class Solution: def numDistinct(self, s: str, t: str) -> int: m, n = len(s), len(t) dp = [[0] * (n+1) for i in range(m+1)] for i in range(m+1): dp[i][0] = 1 for i in range(1, m+1): for j in range(1, n+1): if s[i-1] == t[j-1]: dp[i][j] = dp[i-1][j-1] + dp[i-1][j] else: dp[i][j] = dp[i-1][j] return dp[m][n]
distinct-subsequences
Memoization & Recursion
logeshsrinivasans
0
16
distinct subsequences
115
0.439
Hard
938
https://leetcode.com/problems/distinct-subsequences/discuss/2420912/Python-DP-Solution
class Solution: def numDistinct(self, s: str, t: str) -> int: d = {} def r(index_s, index_t): if index_t < 0: return 1 if index_s < 0: return 0 if s[index_s] == t[index_t]: if (index_s-1, index_t-1) not in d: moveTIndex = r(index_s-1, index_t-1) else: moveTIndex = d[(index_s-1, index_t-1)] if (index_s-1, index_t) not in d: notMoveTIndex = r(index_s-1, index_t) else: notMoveTIndex = d[(index_s-1, index_t)] d[(index_s, index_t)] = notMoveTIndex + moveTIndex return d[(index_s, index_t)] else: if (index_s-1, index_t) not in d: x = r(index_s-1, index_t) else: x = d[(index_s-1, index_t)] d[(index_s, index_t)] = x return d[(index_s, index_t)] return r(len(s)-1, len(t)-1)
distinct-subsequences
Python DP Solution
DietCoke777
0
17
distinct subsequences
115
0.439
Hard
939
https://leetcode.com/problems/distinct-subsequences/discuss/2341291/Python-Solution-or-Recursion-or-DP
class Solution: def numDistinct(self, s: str, t: str) -> int: #Memoiation n=len(s) m=len(t) dp=[[-1]*(m+1) for i in range(n+1)] def helper(i, j): if j<0: return 1 if i<0: return 0 if dp[i][j]!=-1: return dp[i][j] if s[i]==t[j]: dp[i][j]=helper(i-1, j-1) + helper(i-1, j) else: dp[i][j]=helper(i-1, j) return dp[i][j] return helper(n-1, m-1) # Tabulation n=len(s) m=len(t) dp=[[0]*(m+1) for i in range(n+1)] for i in range(n+1): dp[i][0]=1 for i in range(1, n+1): for j in range(1, m+1): if s[i-1]==t[j-1]: dp[i][j]=dp[i-1][j-1]+dp[i-1][j] else: dp[i][j]=dp[i-1][j] return dp[n][m]
distinct-subsequences
Python Solution | Recursion | DP
Siddharth_singh
0
40
distinct subsequences
115
0.439
Hard
940
https://leetcode.com/problems/distinct-subsequences/discuss/2335067/Python-easy-to-read-and-understand-or-dynamic-programming
class Solution: def solve(self, x, y, m, n): if n == 0: return 1 elif m == 0: return 0 if x[m-1] == y[n-1]: return self.solve(x, y, m-1, n-1) + self.solve(x, y, m-1, n) else: return self.solve(x, y, m-1, n) def numDistinct(self, s: str, t: str) -> int: return self.solve(s, t, len(s), len(t))
distinct-subsequences
Python easy to read and understand | dynamic-programming
sanial2001
0
21
distinct subsequences
115
0.439
Hard
941
https://leetcode.com/problems/distinct-subsequences/discuss/2335067/Python-easy-to-read-and-understand-or-dynamic-programming
class Solution: def solve(self, x, y, m, n): if n == 0: return 1 elif m == 0: return 0 if (m, n) in self.d: return self.d[(m, n)] if x[m-1] == y[n-1]: self.d[(m, n)] = self.solve(x, y, m-1, n-1) + self.solve(x, y, m-1, n) return self.d[(m, n)] else: self.d[(m, n)] = self.solve(x, y, m-1, n) return self.d[(m, n)] def numDistinct(self, s: str, t: str) -> int: self.d = {} return self.solve(s, t, len(s), len(t))
distinct-subsequences
Python easy to read and understand | dynamic-programming
sanial2001
0
21
distinct subsequences
115
0.439
Hard
942
https://leetcode.com/problems/distinct-subsequences/discuss/2301931/Python3-oror-My-first-DP-thought-solution-ever-83.86-of-Python3-submissions
class Solution: def numDistinct(self, s: str, t: str) -> int: r, c = len(t), len(s) dp = [[0]*c for _ in range(r)] for i in range(c): dp[0][i] = 1 + dp[0][i-1] if t[0] == s[i] else dp[0][i-1] for i in range(1, r): for j in range(1, c): dp[i][j] = dp[i-1][j-1] + dp[i][j-1] if t[i] == s[j] else dp[i][j-1] return dp[-1][-1]
distinct-subsequences
Python3 || My first DP thought solution ever 83.86% of Python3 submissions
sagarhasan273
0
43
distinct subsequences
115
0.439
Hard
943
https://leetcode.com/problems/distinct-subsequences/discuss/2244692/easy-to-understand-Memoized-and-Bottom-up-solution
class Solution: def numDistinct(self, s: str, t: str) -> int: # Bottom-up solution # T(c)=O(n*m) # S(c)=O(n*m) n=len(s) m=len(t) dp=[[0 for _ in range(m+1)] for _ in range(n+1)] for i in range(n+1): for j in range(m+1): if i==0: dp[i][j]=0 if j==0: dp[i][j]=1 for i in range(1,n+1): for j in range(1,m+1): if s[i-1]==t[j-1]: dp[i][j]=dp[i-1][j-1]+dp[i-1][j] else: dp[i][j]=dp[i-1][j] return dp[n][m] # Memoization solution # T(c)=O(n*m) # S(c)=O(n*m)+O(n) n=len(s) m=len(t) def solve(i,j): dp=[[-1 for _ in range(m)] for _ in range(n)] if dp[i][j]!=-1: return dp[i][j] if j<0 : return 1 if i<0 : return 0 if s[i]==t[j]: dp[i][j]=solve(i-1,j-1)+solve(i-1,j) return dp[i][j] else: dp[i][j]=solve(i-1,j) return dp[i][j] return solve(n-1,m-1)
distinct-subsequences
easy to understand Memoized and Bottom-up solution
Aniket_liar07
0
29
distinct subsequences
115
0.439
Hard
944
https://leetcode.com/problems/distinct-subsequences/discuss/2228316/DP-oror-Top-Down-oror-Memoization
class Solution: def distinctSubsequences(self, i, j, s, t, dpCache): if j == len(t): return 1 if i == len(s): return 0 if (i, j) in dpCache: return dpCache[(i, j)] if s[i] == t[j]: dpCache[(i, j)] = self.distinctSubsequences(i + 1, j + 1, s, t, dpCache) + self.distinctSubsequences(i + 1, j, s, t, dpCache) else: dpCache[(i, j)] = self.distinctSubsequences(i + 1, j, s, t, dpCache) return dpCache[(i, j)] def numDistinct(self, s: str, t: str) -> int: dpCache = {} return self.distinctSubsequences(0, 0, s, t, dpCache)
distinct-subsequences
DP || Top Down || Memoization
Vaibhav7860
0
36
distinct subsequences
115
0.439
Hard
945
https://leetcode.com/problems/distinct-subsequences/discuss/2190935/Python3-clean-code-(recursion-%2B-memoization)
class Solution: def numDistinct(self, s: str, t: str) -> int: def get_subsequences(s, t, index_1, index_2, memo): if index_1 == len(s): if index_2 == len(t): return 1 return 0 if index_2 == len(t): return 1 if (index_1, index_2) in memo: return memo[(index_1, index_2)] ans = 0 if s[index_1] == t[index_2]: # Choose to include this index ans += get_subsequences(s, t, index_1 + 1, index_2 + 1, memo) # Choose to not include this index ans += get_subsequences(s, t, index_1 + 1, index_2, memo) memo[(index_1, index_2)] = ans return ans return get_subsequences(s, t, 0, 0, {})
distinct-subsequences
Python3 clean code (recursion + memoization)
myvanillaexistence
0
35
distinct subsequences
115
0.439
Hard
946
https://leetcode.com/problems/distinct-subsequences/discuss/1686168/step-by-step-explanation-of-dp-solution-from-O(mn)-space-to-O(n)-space-O(mn)time
class Solution: def numDistinct(self, s: str, t: str) -> int: m,n=len(s),len(t) dp=[[0 for _ in range(n+1)] for _ in range(m+1)] for i in range(m+1): dp[i][n] = 1 dp[-1][-1]=1 for i in range(m-1,-1,-1): for j in range(n-1,-1,-1): dp[i][j] = dp[i+1][j] # not using s[i] if s[i]==t[j]: dp[i][j] += dp[i+1][j+1] # use s[i] to match t[j] and delegate s[i+1:] to match t[j+1:] return dp[0][0]
distinct-subsequences
step-by-step explanation of dp solution from O(mn) space to O(n) space, O(mn)time
jacot
0
70
distinct subsequences
115
0.439
Hard
947
https://leetcode.com/problems/distinct-subsequences/discuss/1686168/step-by-step-explanation-of-dp-solution-from-O(mn)-space-to-O(n)-space-O(mn)time
class Solution: def numDistinct(self, s: str, t: str) -> int: m,n=len(s),len(t) dp=[[0 for _ in range(n+1)] for _ in range(2)] for i in range(2): dp[i][n] = 1 for i in range(m-1,-1,-1): for j in range(n-1,-1,-1): dp[0][j] = dp[1][j] # not using s[i] if s[i]==t[j]: dp[0][j] += dp[1][j+1] # use s[i] to match t[j] and delegate s[i+1:] to match t[j+1:] dp[0],dp[1] = dp[1],dp[0] # the last outer loop switch the answer to the 2nd row in dp return dp[1][0]
distinct-subsequences
step-by-step explanation of dp solution from O(mn) space to O(n) space, O(mn)time
jacot
0
70
distinct subsequences
115
0.439
Hard
948
https://leetcode.com/problems/distinct-subsequences/discuss/1653663/Python3-Easy-DFS-%2B-Memoization
class Solution: def numDistinct(self, s: str, t: str) -> int: n, m = len(s), len(t) @cache def dfs(i, j): if (j >= m): return 1 if (i >= n): return 0 if (s[i] == t[j]): return dfs(i + 1, j + 1) + dfs(i + 1, j) return dfs(i + 1, j) return dfs(0, 0)
distinct-subsequences
Python3 - Easy DFS + Memoization βœ…
Bruception
0
175
distinct subsequences
115
0.439
Hard
949
https://leetcode.com/problems/distinct-subsequences/discuss/1472826/Distinct-Subsequences-oror-DP
class Solution: def numDistinct(self, s: str, t: str) -> int: memo = {} def dfs(i, j): if (i,j) in memo: return memo[(i,j)] if j == len(t): return 1 if i == len(s) or len(t)-j > len(s)-i: return 0 count = 0 if s[i] == t[j]: count += dfs(i+1, j+1) count += dfs(i+1, j) memo[(i,j)] = count return count return dfs(0,0)
distinct-subsequences
Distinct Subsequences || DP
mdAzhar
0
59
distinct subsequences
115
0.439
Hard
950
https://leetcode.com/problems/distinct-subsequences/discuss/1309048/2-Pointer-Recursion-2D-1D-iteration-Edit-distance-delete-operation-)
class Solution: def numDistinctTopDown(self, s: str, t: str) -> int: # this is like edit distance... with only delete ;) @functools.cache def ways(si, ti): # index in both strings if ti == len(t): return 1 elif si == len(s): return 0 # MATCH / include match = 0 if s[si] == t[ti]: match = ways(si+1,ti+1) # SKIP skip = ways(si+1, ti) return match + skip return ways(0,0) # now trying bottom up def numDistinct2D(self, s: str, t: str) -> int: N,M = len(s), len(t) # construct N x M matrix for storing DP results ways = [[0 for __ in range(M+1)] for _ in range(N+1)] # base case: ti == M for si in range(N+1): ways[si][M] = 1 # now iterate backwards since ways[si] -> depends on ways[si+1] for si in range(N-1, -1, -1): for ti in range(M-1, -1, -1): # ti depends on ti+1 so again backwards # MATCH / include match = 0 if s[si] == t[ti]: match = ways[si+1][ti+1] # SKIP skip = ways[si+1][ti] ways[si][ti] = match + skip return ways[0][0] # now trying bottom up, only store today `i` and tommorrow `i+1` def numDistinct(self, s: str, t: str) -> int: # O(M) N,M = len(s), len(t) # construct N x M matrix for storing DP results ways_today = [0 for _ in range(M+1)] # base case: ti == M ways_today[M] = 1 ways_tomm = ways_today[:] # now iterate backwards since today -> depends on tommorrow for si in range(N-1, -1, -1): # each value of ti depends on ti+1 so again backwards for ti in range(M-1, -1, -1): # MATCH / include match = 0 if s[si] == t[ti]: match = ways_tomm[ti+1] # SKIP skip = ways_tomm[ti] ways_today[ti] = match + skip # now we do i--, then tomm = i, tomm ways_tomm = ways_today[:] return ways_today[0]
distinct-subsequences
2 Pointer, Recursion, 2D, 1D iteration Edit distance delete operation ;)
yozaam
0
76
distinct subsequences
115
0.439
Hard
951
https://leetcode.com/problems/distinct-subsequences/discuss/692969/Python3-dynamic-programming
class Solution: def numDistinct(self, s: str, t: str) -> int: @lru_cache(None) def fn(i, j): """Return number of subsequences of s[i:] which equals t[j:]""" if j == len(t): return 1 if i == len(s): return 0 return fn(i+1, j) + (s[i] == t[j]) * fn(i+1, j+1) return fn(0, 0)
distinct-subsequences
[Python3] dynamic programming
ye15
0
52
distinct subsequences
115
0.439
Hard
952
https://leetcode.com/problems/distinct-subsequences/discuss/692969/Python3-dynamic-programming
class Solution: def numDistinct(self, s: str, t: str) -> int: loc = {} for i, x in enumerate(t): loc.setdefault(x, []).append(i) ans = [0]*len(t) + [1] for c in reversed(s): for i in pos.get(c, []): ans[i] += ans[i+1] return ans[0]
distinct-subsequences
[Python3] dynamic programming
ye15
0
52
distinct subsequences
115
0.439
Hard
953
https://leetcode.com/problems/distinct-subsequences/discuss/445405/python-solution-recursive-with-memory-beats-99
class Solution: def numDistinct(self, s: str, t: str) -> int: nextp = [ {} for _ in range(len(s))] current={} for i in range(len(s)-1,-1,-1): current[s[i]] = i nextp[i]=current.copy() self.mem={} return self.helper(s,0,t,0,nextp) def helper(self,s,i,t,j,nextp): if (i,j) in self.mem: return self.mem[(i,j)] if j==len(t): self.mem[(i,j)]=1 return 1 if i==len(s): self.mem[(i,j)] = 0 return 0 if t[j] in nextp[i]: self.mem[(i,j)] = self.helper(s,nextp[i][t[j]]+1,t,j,nextp) + self.helper(s,nextp[i][t[j]]+1,t,j+1,nextp) else: self.mem[(i,j)] = 0 return self.mem[(i,j)]
distinct-subsequences
python solution recursive with memory, beats 99%
meowthecat
0
88
distinct subsequences
115
0.439
Hard
954
https://leetcode.com/problems/distinct-subsequences/discuss/1226056/Python-O(n2)-solution-using-DP
class Solution: def numDistinct(self, s: str, t: str) -> int: m, n = len(s), len(t) dp = [[0 for i in range(m + 1)] for i in range(n + 1)] for i in range(0, m + 1): dp[i][0] = 1 for i in range(1,m + 1): for j in range(1,n + 1): dp[i][j] += dp[i - 1][j] + (dp[i - 1][j - 1] if s[i - 1] == t[j - 1] else 0) return dp[m][n]
distinct-subsequences
Python O(n^2) solution using DP
m0biu5
-1
95
distinct subsequences
115
0.439
Hard
955
https://leetcode.com/problems/populating-next-right-pointers-in-each-node/discuss/719347/Python-Solution-O(1)-and-O(n)-memory.
class Solution: def connect(self, root: 'Node') -> 'Node': # edge case check if not root: return None # initialize the queue with root node (for level order traversal) queue = collections.deque([root]) # start the traversal while queue: size = len(queue) # get number of nodes on the current level for i in range(size): node = queue.popleft() # pop the node # An important check so that we do not wire the node to the node on the next level. if i < size-1: node.next = queue[0] # because the right node of the popped node would be the next in the queue. if node.left: queue.append(node.left) if node.right: queue.append(node.right) return root
populating-next-right-pointers-in-each-node
Python Solution O(1) and O(n) memory.
darshan_22
10
534
populating next right pointers in each node
116
0.596
Medium
956
https://leetcode.com/problems/populating-next-right-pointers-in-each-node/discuss/719347/Python-Solution-O(1)-and-O(n)-memory.
class Solution: def connect(self, root: 'Node') -> 'Node': # edge case check if not root: return None node = root # create a pointer to the root node # iterate only until we have a new level (because the connections for Nth level are done when we are at N-1th level) while node.left: head = node while head: head.left.next = head.right if head.next: head.right.next = head.next.left head = head.next node = node.left return root
populating-next-right-pointers-in-each-node
Python Solution O(1) and O(n) memory.
darshan_22
10
534
populating next right pointers in each node
116
0.596
Medium
957
https://leetcode.com/problems/populating-next-right-pointers-in-each-node/discuss/2040150/O(n)timeBEATS-99.97-MEMORYSPEED-0ms-MAY-2022
class Solution: def connect(self, root: 'Node') -> 'Node': # edge case check if not root: return None node = root # create a pointer to the root node # iterate only until we have a new level (because the connections for Nth level are done when we are at N-1th level) while node.left: head = node while head: head.left.next = head.right if head.next: head.right.next = head.next.left head = head.next node = node.left return root
populating-next-right-pointers-in-each-node
O(n)time/BEATS 99.97% MEMORY/SPEED 0ms MAY 2022
cucerdariancatalin
8
421
populating next right pointers in each node
116
0.596
Medium
958
https://leetcode.com/problems/populating-next-right-pointers-in-each-node/discuss/1114796/python-recursion-constant-space-beats-98-short-solution
class Solution: def connect(self, root: 'Node') -> 'Node': if not root or not root.left: return root root.left.next = root.right if root.next: root.right.next = root.next.left self.connect(root.left) self.connect(root.right) return root
populating-next-right-pointers-in-each-node
python recursion constant space beats 98% short solution
marriema
5
261
populating next right pointers in each node
116
0.596
Medium
959
https://leetcode.com/problems/populating-next-right-pointers-in-each-node/discuss/1786038/Python-3-(70ms)-or-BFS-O(N)-Solution
class Solution: def connect(self, root: 'Optional[Node]') -> 'Optional[Node]': head = root while root: cur, root = root, root.left while cur: if cur.left: cur.left.next = cur.right if cur.next: cur.right.next = cur.next.left else: break cur = cur.next return head
populating-next-right-pointers-in-each-node
Python 3 (70ms) | BFS O(N) Solution
MrShobhit
3
198
populating next right pointers in each node
116
0.596
Medium
960
https://leetcode.com/problems/populating-next-right-pointers-in-each-node/discuss/726359/Python-Easy-understanding-solution-with-explaination
class Solution: def connect(self, root: 'Node') -> 'Node': # dfs if not root: return # if root has non-empty right pointer, it means root must have left pointer and we need to link left -> right through next pointer if root.right: root.left.next = root.right # if root has non-empty next pointer (means not point to NULL), it means we are linking left subtree and right subtree together # so their left and right subtree also need to be linked together just like in the example 1: # when we link 2->3, we also need to link their subtrees through 5 -> 6 (5: 2.right, ->: next, 6: 2.next.left ) if root.next: root.right.next = root.next.left self.connect(root.left) self.connect(root.right) return root
populating-next-right-pointers-in-each-node
Python -- Easy understanding solution with explaination
nbismoi
3
177
populating next right pointers in each node
116
0.596
Medium
961
https://leetcode.com/problems/populating-next-right-pointers-in-each-node/discuss/694695/Python3-O(1)-space-solution
class Solution: def connect(self, root: 'Node') -> 'Node': head = root while head and head.left: node = head while node: node.left.next = node.right if node.next: node.right.next = node.next.left node = node.next head = head.left return root
populating-next-right-pointers-in-each-node
[Python3] O(1) space solution
ye15
3
96
populating next right pointers in each node
116
0.596
Medium
962
https://leetcode.com/problems/populating-next-right-pointers-in-each-node/discuss/694695/Python3-O(1)-space-solution
class Solution: def connect(self, root: 'Node') -> 'Node': def fn(node): """Connect node's children""" if node and node.left: node.left.next = node.right if node.next: node.right.next = node.next.left fn(node.left) or fn(node.right) fn(root) return root
populating-next-right-pointers-in-each-node
[Python3] O(1) space solution
ye15
3
96
populating next right pointers in each node
116
0.596
Medium
963
https://leetcode.com/problems/populating-next-right-pointers-in-each-node/discuss/694695/Python3-O(1)-space-solution
class Solution: def connect(self, root: 'Node') -> 'Node': def fn(node, i=0): """Return tree whose next pointer is populated.""" if not node: return node.next = seen.get(i) seen[i] = node fn(node.right, i+1) and fn(node.left, i+1) return node seen = {} return fn(root)
populating-next-right-pointers-in-each-node
[Python3] O(1) space solution
ye15
3
96
populating next right pointers in each node
116
0.596
Medium
964
https://leetcode.com/problems/populating-next-right-pointers-in-each-node/discuss/694695/Python3-O(1)-space-solution
class Solution: def connect(self, root: 'Node') -> 'Node': stack = [(0, root)] seen = {} while stack: i, node = stack.pop() if node: node.next = seen.get(i) seen[i] = node stack.append((i+1, node.left)) stack.append((i+1, node.right)) return root
populating-next-right-pointers-in-each-node
[Python3] O(1) space solution
ye15
3
96
populating next right pointers in each node
116
0.596
Medium
965
https://leetcode.com/problems/populating-next-right-pointers-in-each-node/discuss/694695/Python3-O(1)-space-solution
class Solution: def connect(self, root: 'Node') -> 'Node': if not root: return # edge case seen = {} stack = [(0, root)] while stack: i, node = stack.pop() if i in seen: seen[i].next = node seen[i] = node if node.right: stack.append((i+1, node.right)) if node.left: stack.append((i+1, node.left)) return root
populating-next-right-pointers-in-each-node
[Python3] O(1) space solution
ye15
3
96
populating next right pointers in each node
116
0.596
Medium
966
https://leetcode.com/problems/populating-next-right-pointers-in-each-node/discuss/694695/Python3-O(1)-space-solution
class Solution: def connect(self, root: 'Node') -> 'Node': if not root: return # edge case queue = [root] while queue: newq = [] next = None for node in queue: node.next = next next = node if node.right: newq.append(node.right) if node.left: newq.append(node.left) queue = newq return root
populating-next-right-pointers-in-each-node
[Python3] O(1) space solution
ye15
3
96
populating next right pointers in each node
116
0.596
Medium
967
https://leetcode.com/problems/populating-next-right-pointers-in-each-node/discuss/1102368/PythonPython3-Populating-Next-Right-Pointers-in-Each-Node
class Solution: def connect(self, root: 'Node') -> 'Node': if not root: return None nodes_at_each_level = [] level = [root] while level: nodes_at_each_level.append([node for node in level]) level = [child for node in level for child in (node.left,node.right) if child] # return root for level_nodes in nodes_at_each_level: for idx in range(len(level_nodes)-1): level_nodes[idx].next = level_nodes[idx+1] return root
populating-next-right-pointers-in-each-node
[Python/Python3] Populating Next Right Pointers in Each Node
newborncoder
2
195
populating next right pointers in each node
116
0.596
Medium
968
https://leetcode.com/problems/populating-next-right-pointers-in-each-node/discuss/1102368/PythonPython3-Populating-Next-Right-Pointers-in-Each-Node
class Solution: def connect(self, root: 'Optional[Node]') -> 'Optional[Node]': def rp(parent, child): if parent and child: if child == parent.left: child.next = parent.right elif child == parent.right and parent.next: child.next = parent.next.left if child: rp(child, child.left) rp(child, child.right) rp(None, root) return root
populating-next-right-pointers-in-each-node
[Python/Python3] Populating Next Right Pointers in Each Node
newborncoder
2
195
populating next right pointers in each node
116
0.596
Medium
969
https://leetcode.com/problems/populating-next-right-pointers-in-each-node/discuss/2391618/Python3-or-SC-O(1)-or-98-Faster-74-less-space-or-Easy-understanding
class Solution: def connect(self, root: 'Optional[Node]') -> 'Optional[Node]': #if tree is empty if not root: return #if tree has only one value if not root.left or not root.right: return root flag = False #to assign the very first node.next = None def dfs(root): nonlocal flag if not root.left or not root.right: #if node has no left and right child return if not flag: root.next = None flag = True root.left.next = root.right if not root.next: # if you have traversed all the node of a particular node root.right.next = None else: root.right.next = root.next.left dfs(root.left) dfs(root.right) dfs(root) return root
populating-next-right-pointers-in-each-node
[Python3] | SC O(1) | 98% Faster 74% less space | Easy-understanding
_vikaskumar_
1
56
populating next right pointers in each node
116
0.596
Medium
970
https://leetcode.com/problems/populating-next-right-pointers-in-each-node/discuss/2337682/Python-Simple-Iterative-solution-Space-O(1)-oror-Documented
class Solution: def connect(self, root: 'Optional[Node]') -> 'Optional[Node]': parent = root nextChild = root.left if root else None # traverse the tree parent and next child that will be # required once right side nodes are covered and we come back to this state while parent and nextChild: parent.left.next = parent.right # if parent has right side node rightSideNode = parent.next if rightSideNode: parent.right.next = rightSideNode.left # next parent will be next right side node parent = rightSideNode # if there is no next right side node, go downward (next left child) if parent == None: parent = nextChild nextChild = parent.left return root
populating-next-right-pointers-in-each-node
[Python] Simple Iterative solution - Space O(1) || Documented
Buntynara
1
22
populating next right pointers in each node
116
0.596
Medium
971
https://leetcode.com/problems/populating-next-right-pointers-in-each-node/discuss/1655076/Python3-Intuitive-Recursive-Approach
class Solution: def connect(self, root: 'Optional[Node]') -> 'Optional[Node]': if not root: return if root.next: if root.right and root.next.left: root.right.next = root.next.left if root.left and root.right: root.left.next = root.right self.connect(root.left) self.connect(root.right) return root
populating-next-right-pointers-in-each-node
[Python3] Intuitive Recursive Approach
Rainyforest
1
22
populating next right pointers in each node
116
0.596
Medium
972
https://leetcode.com/problems/populating-next-right-pointers-in-each-node/discuss/1653808/Python3-ITERATIVE-BFS-Explained
class Solution: def connect(self, root: 'Optional[Node]') -> 'Optional[Node]': if not root: return level = deque([root]) while level: nextLevel = deque() next = None while level: node = level.pop() if node.left: nextLevel.appendleft(node.right) nextLevel.appendleft(node.left) node.next, next = next, node level = nextLevel return root
populating-next-right-pointers-in-each-node
βœ”οΈ [Python3] ITERATIVE BFS, Explained
artod
1
114
populating next right pointers in each node
116
0.596
Medium
973
https://leetcode.com/problems/populating-next-right-pointers-in-each-node/discuss/1653748/Python3-2-Solutions-or-BFS-O(n)-and-Modified-BFS-O(1)
class Solution: def connect(self, root: 'Optional[Node]') -> 'Optional[Node]': if not root: return None level = [root] while level: level.append(None) nextLevel = [] for i in range(len(level) - 1): level[i].next = level[i + 1] if level[i].left: nextLevel.append(level[i].left) if level[i].right: nextLevel.append(level[i].right) level = nextLevel return root
populating-next-right-pointers-in-each-node
[Python3] 2 Solutions | BFS O(n) & Modified BFS O(1)
PatrickOweijane
1
106
populating next right pointers in each node
116
0.596
Medium
974
https://leetcode.com/problems/populating-next-right-pointers-in-each-node/discuss/1653748/Python3-2-Solutions-or-BFS-O(n)-and-Modified-BFS-O(1)
class Solution: def connect(self, root: 'Optional[Node]') -> 'Optional[Node]': if not root: return None level = root while level: nextLevel = level.left last = None while level: if last: last.next = level.left if level.left: level.left.next = level.right last = level.right level = level.next level = nextLevel return root
populating-next-right-pointers-in-each-node
[Python3] 2 Solutions | BFS O(n) & Modified BFS O(1)
PatrickOweijane
1
106
populating next right pointers in each node
116
0.596
Medium
975
https://leetcode.com/problems/populating-next-right-pointers-in-each-node/discuss/1595860/3-iterative-solutions-in-Python-from-O(n)-space-to-O(1)
class Solution: def connect(self, root: 'Node') -> 'Node': if not root: return root from collections import deque q = deque([(root, 0)]) while q: n, level = q.popleft() q += ((c, level + 1) for c in (n.left, n.right) if c) try: if level == q[0][1]: n.next = q[0][0] except IndexError: pass return root
populating-next-right-pointers-in-each-node
3 iterative solutions in Python, from O(n) space to O(1)
mousun224
1
145
populating next right pointers in each node
116
0.596
Medium
976
https://leetcode.com/problems/populating-next-right-pointers-in-each-node/discuss/1595860/3-iterative-solutions-in-Python-from-O(n)-space-to-O(1)
class Solution: def connect(self, root: 'Node') -> 'Node': if not root: return root level = [root] while level: for i in range(len(level) - 1): level[i].next = level[i + 1] level = [c for n in level for c in (n.left, n.right) if c] return root
populating-next-right-pointers-in-each-node
3 iterative solutions in Python, from O(n) space to O(1)
mousun224
1
145
populating next right pointers in each node
116
0.596
Medium
977
https://leetcode.com/problems/populating-next-right-pointers-in-each-node/discuss/1595860/3-iterative-solutions-in-Python-from-O(n)-space-to-O(1)
class Solution: def connect(self, root: 'Node') -> 'Node': head = root while head and head.left: left_most = head.left while head: head.left.next = head.right if head.next: head.right.next = head.next.left head = head.next head = left_most return root
populating-next-right-pointers-in-each-node
3 iterative solutions in Python, from O(n) space to O(1)
mousun224
1
145
populating next right pointers in each node
116
0.596
Medium
978
https://leetcode.com/problems/populating-next-right-pointers-in-each-node/discuss/1572626/Python-or-Recursive-approach-with-no-extra-space-or-Explained
class Solution: def connect(self, root: 'Node') -> 'Node': # corner case where the tree is empty if root: # if it's not a leaf node if root.left and root.right: # connect the left child to the right child root.left.next = root.right # if the current node has the next set if root.next: # the current right's next will be the left child of it root.right.next = root.next.left # repeat the process recursevely self.connect(root.left) self.connect(root.right) return root
populating-next-right-pointers-in-each-node
Python | Recursive approach with no extra space | Explained
hemersontacon
1
73
populating next right pointers in each node
116
0.596
Medium
979
https://leetcode.com/problems/populating-next-right-pointers-in-each-node/discuss/1478239/Python-O(1)-space-with-recursion-beats-90-speed
class Solution: def connect(self, root: 'Node') -> 'Node': if root is None: return root self.traverse(root, None, None) return root def traverse(self, node, parent, goLeft): if node is None: return left, right = node.left, node.right self.traverse(left, node, True) if parent is None: # for root node.next = None elif goLeft: node.next = parent.right else: if parent.next is None: node.next = None else: node.next = parent.next.left self.traverse(right, node, False)
populating-next-right-pointers-in-each-node
Python O(1) space with recursion beats 90 speed
SleeplessChallenger
1
170
populating next right pointers in each node
116
0.596
Medium
980
https://leetcode.com/problems/populating-next-right-pointers-in-each-node/discuss/1432505/Row-by-row-80-speed
class Solution: def connect(self, root: 'Node') -> 'Node': if not root: return root row = [root] while row: new_row = [] for i, node in enumerate(row): if i < len(row) - 1: node.next = row[i + 1] if node.left: new_row.append(node.left) if node.right: new_row.append(node.right) row = new_row return root
populating-next-right-pointers-in-each-node
Row by row, 80% speed
EvgenySH
1
82
populating next right pointers in each node
116
0.596
Medium
981
https://leetcode.com/problems/populating-next-right-pointers-in-each-node/discuss/2842198/Python-DFS
class Solution: def dfs(self, root, levels, level): if level not in levels: levels[level] = [] if root and root.left: levels[level].extend([root.left, root.right]) self.dfs(root.left, levels, level + 1) self.dfs(root.right, levels, level + 1) def connect(self, root: 'Optional[Node]') -> 'Optional[Node]': levels = {} self.dfs(root, levels, 0) for level in levels.keys(): nodes = levels[level] for i in range(len(nodes) - 1): nodes[i].next = nodes[i + 1] return root
populating-next-right-pointers-in-each-node
Python DFS
alimohammad1995
0
1
populating next right pointers in each node
116
0.596
Medium
982
https://leetcode.com/problems/populating-next-right-pointers-in-each-node/discuss/2677789/Python3-or-Hash-Map-%2B-BFS
class Solution: def __init__(self): self.hash_table = None def connect(self, root: 'Optional[Node]') -> 'Optional[Node]': if root is None: return self.hash_table = defaultdict(list) self.level_order(root, 0) for key in self.hash_table: if key == 0: continue last_node = self.hash_table[key][0] for current_node in self.hash_table[key][1:]: last_node.next = current_node last_node = current_node return root def level_order(self, node, level): if node is None: return self.hash_table[level].append(node) self.level_order(node.left, level+1) self.level_order(node.right, level+1)
populating-next-right-pointers-in-each-node
Python3 | Hash Map + BFS
honeybadgerofdoom
0
6
populating next right pointers in each node
116
0.596
Medium
983
https://leetcode.com/problems/populating-next-right-pointers-in-each-node/discuss/2657457/Python3-DFS-recursion!-Nodes-matched-on-the-same-level
class Solution: def connect(self, root: 'Optional[Node]') -> 'Optional[Node]': tree = [] def dfs(node, level=0): if node is None: return if len(tree) == level: tree.append([]) dfs(node.right, level + 1) dfs(node.left, level + 1) if len(tree[level]) > 0: node.next = tree[level].pop() else: node.next = None tree[level].append(node) dfs(root) return root ```
populating-next-right-pointers-in-each-node
Python3 DFS, recursion! Nodes matched on the same `level`
zakmatt
0
31
populating next right pointers in each node
116
0.596
Medium
984
https://leetcode.com/problems/populating-next-right-pointers-in-each-node/discuss/2610043/Python3-faster-than-99.77-submissions
class Solution: def connect(self, root: 'Optional[Node]') -> 'Optional[Node]': curr , nxt = root, root.left if root else None while curr and nxt: curr.left.next = curr.right if curr.next: curr.right.next = curr.next.left curr = curr.next if not curr: curr = nxt nxt = curr.left return root
populating-next-right-pointers-in-each-node
Python3 faster than 99.77% submissions
sumedha19129
0
25
populating next right pointers in each node
116
0.596
Medium
985
https://leetcode.com/problems/populating-next-right-pointers-in-each-node/discuss/2469191/simple-python-solution-using-level-order-and-bfs-with-comments
class Solution: def connect(self, root: 'Optional[Node]') -> 'Optional[Node]': if(not root): return None q = deque() q.append(root) while(q): sz = len(q) pre = None for i in range(sz): curr = q.popleft() if(pre != None): pre.next = curr pre = curr if(curr.left): q.append(curr.left) if(curr.right): q.append(curr.right) return root
populating-next-right-pointers-in-each-node
simple python solution using level order and bfs with comments
rajitkumarchauhan99
0
17
populating next right pointers in each node
116
0.596
Medium
986
https://leetcode.com/problems/populating-next-right-pointers-in-each-node/discuss/2283706/116.-My-Java-and-Python-Solution-with-comments
class Solution: def connect(self, root: 'Optional[Node]') -> 'Optional[Node]': if not root: return None dummy = root # while we still have next level to check while root.left: # save the pointer of next level next_level = root.left # we use pointer root to check node one by one in the same layer (horizontal check) # that is: while root is not at the end of that level, root=root.next while root: root.left.next = root.right # connect left node to right node if root.next is not None: root.right.next = root.next.left # connect right node to next left node #else: don't need this, because by default it is 0. # root.right.next = None root = root.next #when we go out from this inner while loop, it means root goes to the end of the level, so we move to next level root = next_level return dummy
populating-next-right-pointers-in-each-node
116. My Java and Python Solution with comments
JunyiLin
0
26
populating next right pointers in each node
116
0.596
Medium
987
https://leetcode.com/problems/populating-next-right-pointers-in-each-node/discuss/2220136/Python-recursive...Very-simple-and-commented
class Solution: def connect(self, root: 'Optional[Node]') -> 'Optional[Node]': def dfs(node, nxt): if not node: return node.next = nxt dfs(node.left, node.right) # left and right children connect with next if node.next: dfs(node.right, node.next.left) # if there is already next then we connect right and left child else: dfs(node.right, None) # or else just do not connect and traverse this node dfs(root, None) return root
populating-next-right-pointers-in-each-node
Python recursive...Very simple and commented
saqibmubarak
0
46
populating next right pointers in each node
116
0.596
Medium
988
https://leetcode.com/problems/populating-next-right-pointers-in-each-node/discuss/2149548/Python3-Solution
class Solution: def connect(self, root: 'Optional[Node]') -> 'Optional[Node]': if not root: return None self.traverse(root.left, root.right); return root def traverse(self, node1, node2): if not node1 or not node2: return node1.next = node2 #εŒηˆΆθŠ‚η‚Ή self.traverse(node1.left, node1.right); self.traverse(node2.left, node2.right); #εΌ‚ηˆΆθŠ‚η‚Ή self.traverse(node1.right, node2.left);
populating-next-right-pointers-in-each-node
Python3 Solution
qywang
0
38
populating next right pointers in each node
116
0.596
Medium
989
https://leetcode.com/problems/populating-next-right-pointers-in-each-node/discuss/2061341/Python-level-order-traversal
class Solution: def connect(self, root: 'Optional[Node]') -> 'Optional[Node]': q = deque([root]) if root else None while q: length = len(q) prev = None for _ in range(length): node = q.popleft() node.next = prev prev = node if node.right: q.append(node.right) q.append(node.left) return root
populating-next-right-pointers-in-each-node
Python, level order traversal
blue_sky5
0
18
populating next right pointers in each node
116
0.596
Medium
990
https://leetcode.com/problems/populating-next-right-pointers-in-each-node/discuss/1976150/Python-DFS-oror-O(N)-time-and-O(1)-Memory-Complexity
class Solution: def connect(self, root: 'Optional[Node]') -> 'Optional[Node]': cur, nextNode = root, root.left if root else None while cur and nextNode: cur.left.next = cur.right if cur.next: cur.right.next = cur.next.left cur = cur.next if not cur: cur = nextNode nextNode = cur.left return root
populating-next-right-pointers-in-each-node
Python - DFS || O(N) time and O(1) Memory Complexity
dayaniravi123
0
70
populating next right pointers in each node
116
0.596
Medium
991
https://leetcode.com/problems/populating-next-right-pointers-in-each-node/discuss/1864709/Python3-Simple-recursive-solution
class Solution: def connect(self, root: 'Optional[Node]') -> 'Optional[Node]': if (root == None): return None self.connectTwoNodes(root.left, root.right) return root def connectTwoNodes(self, node1, node2): if (node1 == None or node2 == None): return # Connect child nodes for each single parent self.connectTwoNodes(node1.left, node1.right) self.connectTwoNodes(node2.left, node2.right) # Connect two parent nodes node1.next = node2 # Connect child nodes across two parents self.connectTwoNodes(node1.right, node2.left)
populating-next-right-pointers-in-each-node
[Python3] Simple recursive solution
leqinancy
0
22
populating next right pointers in each node
116
0.596
Medium
992
https://leetcode.com/problems/populating-next-right-pointers-in-each-node/discuss/1804220/simple-python-bfs
class Solution: def connect(self, root: 'Optional[Node]') -> 'Optional[Node]': cur = [root] nxt = [] while root and len(cur) > 0: cur.append(None) for i in range(0, len(cur)-1): cur[i].next = cur[i+1] if cur[i].left: nxt.append(cur[i].left) if cur[i].right: nxt.append(cur[i].right) cur = nxt nxt = [] return root
populating-next-right-pointers-in-each-node
simple python bfs
gasohel336
0
45
populating next right pointers in each node
116
0.596
Medium
993
https://leetcode.com/problems/populating-next-right-pointers-in-each-node/discuss/1785696/Easy-to-Understand-or-Step-by-Step-Explanation
class Solution: def connect(self, root: 'Optional[Node]') -> 'Optional[Node]': q1 = [] q1.append(root) level = 0 if not root: return root while q1: rightMostNodeIndex = 2**level - 1 q1[rightMostNodeIndex].next = None for i in range(rightMostNodeIndex + 1): q1[i].next = q1[i + 1] if i+1 <= rightMostNodeIndex else None if q1[i].left: q1.append(q1[i].left) if q1[i].right: q1.append(q1[i].right) q1[:] = q1[rightMostNodeIndex + 1:] level += 1 return root
populating-next-right-pointers-in-each-node
Easy to Understand | Step by Step Explanation
swap2210
0
26
populating next right pointers in each node
116
0.596
Medium
994
https://leetcode.com/problems/populating-next-right-pointers-in-each-node/discuss/1763650/Python-Simple-Python-Solution-Using-BFS-With-the-help-of-Queue
class Solution: def connect(self, root: 'Optional[Node]') -> 'Optional[Node]': if root is None: return None queue = [root] total_node = 1 while queue: count_node = 1 for i in range(len(queue)): node = queue.pop(0) if count_node == total_node: node.next = None else: node.next = queue[0] if node.left != None: queue.append(node.left) if node.right != None: queue.append(node.right) count_node = count_node + 1 total_node = total_node * 2 return root
populating-next-right-pointers-in-each-node
[ Python ] βœ”βœ” Simple Python Solution Using BFS With the help of Queue ✌πŸ”₯πŸ”₯
ASHOK_KUMAR_MEGHVANSHI
0
122
populating next right pointers in each node
116
0.596
Medium
995
https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/discuss/2033286/Python-Easy%3A-BFS-and-O(1)-Space-with-Explanation
class Solution: def connect(self, root: 'Node') -> 'Node': if not root: return None q = deque() q.append(root) dummy=Node(-999) # to initialize with a not null prev while q: length=len(q) # find level length prev=dummy for _ in range(length): # iterate through all nodes in the same level popped=q.popleft() if popped.left: q.append(popped.left) prev.next=popped.left prev=prev.next if popped.right: q.append(popped.right) prev.next=popped.right prev=prev.next return root
populating-next-right-pointers-in-each-node-ii
Python Easy: BFS and O(1) Space with Explanation
constantine786
39
3,000
populating next right pointers in each node ii
117
0.498
Medium
996
https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/discuss/2033286/Python-Easy%3A-BFS-and-O(1)-Space-with-Explanation
class Solution: def connect(self, root: 'Node') -> 'Node': if not root: return None curr=root dummy=Node(-999) head=root while head: curr=head # initialize current level's head prev=dummy # init prev for next level linked list traversal # iterate through the linked-list of the current level and connect all the siblings in the next level while curr: if curr.left: prev.next=curr.left prev=prev.next if curr.right: prev.next=curr.right prev=prev.next curr=curr.next head=dummy.next # update head to the linked list of next level dummy.next=None # reset dummy node return root
populating-next-right-pointers-in-each-node-ii
Python Easy: BFS and O(1) Space with Explanation
constantine786
39
3,000
populating next right pointers in each node ii
117
0.498
Medium
997
https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/discuss/521193/Python-O(1)-aux-space-DFS-sol.-with-Diagram
class Solution: def connect(self, root: 'Node') -> 'Node': def helper( node: 'Node'): if not node: return None scanner = node.next # Scanner finds left-most neighbor, on same level, in right hand side while scanner: if scanner.left: scanner = scanner.left break if scanner.right: scanner = scanner.right break scanner = scanner.next # connect right child if right child exists if node.right: node.right.next = scanner # connect left child if left child exists if node.left: node.left.next = node.right if node.right else scanner # DFS down to next level helper( node.right ) helper( node.left ) return node # ------------------------------- return helper( root )
populating-next-right-pointers-in-each-node-ii
Python O(1) aux space DFS sol. [with Diagram]
brianchiang_tw
31
1,500
populating next right pointers in each node ii
117
0.498
Medium
998
https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/discuss/1448257/Python3-in-place-BFS-solution-faster-than-97
class Solution: def connect(self, root: 'Node') -> 'Node': parents = [root] kids = [] prev = None while len(parents) > 0: p = parents.pop(0) if prev: prev.next = p prev = p if p: if p.left: kids.append(p.left) if p.right: kids.append(p.right) if len(parents) == 0: parents = kids kids = [] prev = None return root
populating-next-right-pointers-in-each-node-ii
Python3 - in-place, BFS solution, faster than 97%
elainefaith0314
4
255
populating next right pointers in each node ii
117
0.498
Medium
999