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/lowest-common-ancestor-of-a-binary-tree/discuss/1681767/Python-Simple-recursive-DFS-explained | class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
# if in the current recursion level
# you find either p or q, return that node
# if you instead find a None, return None
# since we're handling both the cases below
if root is None or root == p or root == q:
return root
# find either p or q in the left subtree
# we're expecting this to return one of
# [None, p, q] and for both the left and right
# subtree
l = self.lowestCommonAncestor(root.left, p, q)
r = self.lowestCommonAncestor(root.right, p , q)
# since values in the tree are unique
# and this root's left and right subtree
# has either p and q each, this is the root
# we're looking for. We're not worried about
# what values are returned, it's more like
# we have presence of either p or q in both
# subtrees, so this has to be our result
if l and r:
return root
# if either of the node doesn't contain
# p or q, just return either None or the
# one node which has either p or q
return l if l else r | lowest-common-ancestor-of-a-binary-tree | [Python] Simple recursive DFS explained | buccatini | 2 | 195 | lowest common ancestor of a binary tree | 236 | 0.581 | Medium | 4,400 |
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/discuss/1067464/Python3-post-order-dfs | class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
def fn(node):
"""Return LCA of p and q in subtree rooted at node (if found)."""
if not node or node in (p, q): return node
left, right = fn(node.left), fn(node.right)
return node if left and right else left or right
return fn(root) | lowest-common-ancestor-of-a-binary-tree | [Python3] post-order dfs | ye15 | 2 | 174 | lowest common ancestor of a binary tree | 236 | 0.581 | Medium | 4,401 |
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/discuss/2538018/Python-Recusive-Approach | class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if not root:
return None
if root == p or root == q:
return root
l = self.lowestCommonAncestor(root.left, p, q)
r = self.lowestCommonAncestor(root.right, p, q)
if l and r :
return root
else:
return l or r | lowest-common-ancestor-of-a-binary-tree | Python Recusive Approach ✅ | Khacker | 1 | 88 | lowest common ancestor of a binary tree | 236 | 0.581 | Medium | 4,402 |
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/discuss/2345245/Python-3-oror-81-ms-faster-than-82.91-of-Python3-online-submissions. | class Solution:
def __init__(self):
self.ans = None
def lowestCommonAncestor(self, root, p, q):
def dfs(node):
if not node:
return False
left = dfs(node.left)
right = dfs(node.right)
mid = node == p or node == q
if mid + left + right >= 2:
self.ans = node
return mid or left or right
dfs(root)
return self.ans | lowest-common-ancestor-of-a-binary-tree | Python 3 || 81 ms, faster than 82.91% of Python3 online submissions. | sagarhasan273 | 1 | 73 | lowest common ancestor of a binary tree | 236 | 0.581 | Medium | 4,403 |
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/discuss/2335124/Python-orRecursive-or-easy-to-read-or-Explained | class Solution(object):
def lowestCommonAncestor(self, root, p, q):
if root==None:
return None
if root== p:
return p
if root == q:
return q
l=self.lowestCommonAncestor(root.left,p,q)
r=self.lowestCommonAncestor(root.right,p,q)
if l!=None and r!=None:
return root
return l or r | lowest-common-ancestor-of-a-binary-tree | Python |Recursive | easy to read | Explained | mync | 1 | 40 | lowest common ancestor of a binary tree | 236 | 0.581 | Medium | 4,404 |
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/discuss/2334213/python3-or-easy-or-explained-code-or-tree-traversal | class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
return self.lca(root, p.val, q.val)
def lca(self, root, n1, n2):
if root:
if root.val == n1 or root.val == n2: # check for lca as ancestor key(of other key) is also lca
return root
left = self.lca(root.left, n1, n2)
right = self.lca(root.right, n1, n2)
if left and right: # if left and right both are not None that means one key is present in left subtree and another in right subtree.
return root
# checking for left or right subtrees have lca
return left if left is not None else right | lowest-common-ancestor-of-a-binary-tree | python3 | easy | explained code | tree traversal | H-R-S | 1 | 66 | lowest common ancestor of a binary tree | 236 | 0.581 | Medium | 4,405 |
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/discuss/1847631/preorder-python-recursive-solution.-easy-to-understand | class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if root == None or root.val == p.val or root.val == q.val:
return root
l = self.lowestCommonAncestor(root.left, p, q)
r = self.lowestCommonAncestor(root.right, p, q)
if l and r:
return root
else:
return l or r | lowest-common-ancestor-of-a-binary-tree | preorder python recursive solution. easy to understand | karanbhandari | 1 | 81 | lowest common ancestor of a binary tree | 236 | 0.581 | Medium | 4,406 |
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/discuss/1156364/Straight-Forward-DFS-in-Python-with-explanation-beats-81.72 | class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype TreeNode
"""
"""
DFS
check if current node is q or p, if so, return current node
or
check left and right children, if so, cur node is the lowest parent, else return the one with value, cause it's the parent of p,q with the other as child
Time: O(N)
Space: O(N)
"""
# save the value for checking
result = [p.val, q.val]
# depth first search
def dfs(node):
# if not node, return None
if not node:
return None
# check if current value in result, if so, return this node
if node.val in result:
return node
# if note current node, check both children
left = dfs(node.left)
right = dfs(node.right)
# if both children, then cur_node is the lowest parent of both,
# else return the one node with value
if left and right:
return node
else:
return left or right
return dfs(root) | lowest-common-ancestor-of-a-binary-tree | Straight Forward DFS in Python with explanation, beats 81.72% | AlbertWang | 1 | 263 | lowest common ancestor of a binary tree | 236 | 0.581 | Medium | 4,407 |
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/discuss/2642181/Python3-or-Recursive-Way | class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if root == None: return None
if root == p or root == q:
return root
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
if left != None and right != None:
return root
elif left != None and right == None:
return left
elif left == None and right != None:
return right
else:
return None | lowest-common-ancestor-of-a-binary-tree | Python3 | Recursive Way | sojwal_ | 0 | 38 | lowest common ancestor of a binary tree | 236 | 0.581 | Medium | 4,408 |
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/discuss/2425881/Python-two-O(n)-solutions-recursive-and-DFS | class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
# Recursive
if root == None or root == p or root == q: # root == None -> hit a leaf node
return root
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
if left and right:
return root
return right if not left else left # both p and q are in the same sub tree | lowest-common-ancestor-of-a-binary-tree | Python two O(n) solutions - recursive and DFS | averule | 0 | 92 | lowest common ancestor of a binary tree | 236 | 0.581 | Medium | 4,409 |
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/discuss/2425881/Python-two-O(n)-solutions-recursive-and-DFS | class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
def dfs(cur):
if not cur: # leaf node
return None
if cur == p or cur == q:
return cur
left = dfs(cur.left)
right = dfs(cur.right)
if left and right:
return cur
return left if left else right # both p and q are in the same sub tree
return dfs(root) | lowest-common-ancestor-of-a-binary-tree | Python two O(n) solutions - recursive and DFS | averule | 0 | 92 | lowest common ancestor of a binary tree | 236 | 0.581 | Medium | 4,410 |
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/discuss/2343520/Iterative-without-point-implementation-more-than-90-for-both-speed-and-space-Python3 | class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if not root or p == root or q == root: return root # special cases, fast route
s = [(root, 2)] # statck: 2-> start; 1-> left side done; 0-> both side done
rt = None # return value
while s:
parent, st = s.pop()
if parent == p or parent == q: # check if any target found
if rt and rt != parent: return rt # if 2nd node found
else: rt = parent # if 1st node found
if 2 == st: # if just started
if parent.left: # if there is left node
s.append((parent, 1))
s.append((parent.left, 2))
elif parent.right: # otherwise directly go to right node
s.append((parent, 0))
s.append((parent.right, 2))
elif parent == rt: rt = s[-1][0] # if both side done, check if it is (parent of)target node, if so pass to upper parent node
elif 1 == st: # if left side is done
if parent.right: # if there is right node
s.append((parent, 0))
s.append((parent.right, 2))
elif parent == rt: rt = s[-1][0] # otherwise, both side done, check if it is (parent of)target node, if so pass to upper parent node
elif parent == rt: rt = s[-1][0] # if both side are done, just check if it is (parent of)target node, if so pass to upper parent node
return rt | lowest-common-ancestor-of-a-binary-tree | Iterative without point implementation, more than 90% for both speed and space Python3 | wwwhhh1988 | 0 | 13 | lowest common ancestor of a binary tree | 236 | 0.581 | Medium | 4,411 |
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/discuss/2338061/Python-Solution-or-Lowest-Common-Ancestor-of-a-Binary-Tree | class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if root is None:
return None
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
if (left and right) or (root in [p, q]):
return root
else:
return left or right | lowest-common-ancestor-of-a-binary-tree | Python Solution | Lowest Common Ancestor of a Binary Tree | nishanrahman1994 | 0 | 29 | lowest common ancestor of a binary tree | 236 | 0.581 | Medium | 4,412 |
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/discuss/2337823/Python-easy-recursive | class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
self.ans = None
def dfs(root):
if not root: return 0
sm = dfs(root.left) + (root in [p,q]) + dfs(root.right)
if sm > 1: self.ans = root
return min(sm, 1)
dfs(root)
return self.ans | lowest-common-ancestor-of-a-binary-tree | ✅ Python easy recursive | dhananjay79 | 0 | 20 | lowest common ancestor of a binary tree | 236 | 0.581 | Medium | 4,413 |
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/discuss/2337190/Python-DFS-Signaling-upward | class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
self.set = None
def dfs(node):
if not node or self.set: return 0
own = 0
if node == p or node == q:
own = 1
left = dfs(node.left)
right = dfs(node.right)
if left + right + own >= 2 and not self.set:
self.set = node
return left + right + own
dfs(root)
return self.set | lowest-common-ancestor-of-a-binary-tree | Python DFS, Signaling upward | Strafespey | 0 | 18 | lowest common ancestor of a binary tree | 236 | 0.581 | Medium | 4,414 |
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/discuss/2337151/Python-or-Easy-and-Undestanding-or-dfs-solution | class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if(root==None or root==p or root==q):
return root
left=self.lowestCommonAncestor(root.left,p,q)
right=self.lowestCommonAncestor(root.right,p,q)
if(left==None):
return right
elif(right==None):
return left
else:
return root | lowest-common-ancestor-of-a-binary-tree | Python | Easy & Undestanding | dfs solution | backpropagator | 0 | 26 | lowest common ancestor of a binary tree | 236 | 0.581 | Medium | 4,415 |
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/discuss/2336415/Python-a-concise-solution | class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if root in [None, p, q]:
return root
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
return root if left and right else left or right | lowest-common-ancestor-of-a-binary-tree | Python a concise solution | blue_sky5 | 0 | 3 | lowest common ancestor of a binary tree | 236 | 0.581 | Medium | 4,416 |
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/discuss/2336254/Python-Simple-Faster-Solution-74-ms-oror-Documented | class Solution:
# T = O(N)
# S = O(N) for stack created recursively with size up to N
def lowestCommonAncestor(self, root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode:
# base case
if not root: return None
# if p or q matched, return root
if root == p or root == q: return root
# recursively search of p and q
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
# if there is split (one is in left and one is in right), return root
if left and right:
return root
else:
# return non-null node, returned from children
# if both are null, then just return null
return left or right | lowest-common-ancestor-of-a-binary-tree | [Python] Simple Faster Solution - 74 ms || Documented | Buntynara | 0 | 3 | lowest common ancestor of a binary tree | 236 | 0.581 | Medium | 4,417 |
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/discuss/2336225/Python-Simple-Python-Solution-Using-Recursion | class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
def LCABT(node,p,q):
if node==None:
return node
if node.val == p.val or node.val == q.val:
return node
leftnode = LCABT(node.left,p,q)
rightnode = LCABT(node.right,p,q)
if leftnode!=None and rightnode!=None:
return node
else:
if leftnode!=None:
return leftnode
else:
return rightnode
return LCABT(root,p,q) | lowest-common-ancestor-of-a-binary-tree | [ Python] ✅✅ Simple Python Solution Using Recursion 🥳✌👍 | ASHOK_KUMAR_MEGHVANSHI | 0 | 23 | lowest common ancestor of a binary tree | 236 | 0.581 | Medium | 4,418 |
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/discuss/2336104/python3-simple-understandable | class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
self.ans = None
def dfs(node):
if not node:
return 0
count = 0
if node.val == p.val or node.val == q.val:
count += 1
count += dfs(node.left)
count += dfs(node.right)
if count == 2:
self.ans = node
return 0
return count
dfs(root)
return self.ans | lowest-common-ancestor-of-a-binary-tree | python3, simple, understandable | pjy953 | 0 | 3 | lowest common ancestor of a binary tree | 236 | 0.581 | Medium | 4,419 |
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/discuss/2335324/python3-DFS-with-explanation | class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
return self.dfs(root, p, q)
def dfs(self, root, p, q):
if root == None: return None #quick test for root = [None] case
if p.val == root.val or q.val == root.val : return root #once we find p or q, return it
r, l = self.dfs(root.right, p, q), self.dfs(root.left, p, q) #establishing finding path
if l and r: return root #if both l and r are not None, we return root here because the root is common anscestor in this case
return l or r #else case we return l or r if one of them isn't None | lowest-common-ancestor-of-a-binary-tree | [python3] DFS with explanation | AustinHuang823 | 0 | 4 | lowest common ancestor of a binary tree | 236 | 0.581 | Medium | 4,420 |
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/discuss/2335210/python-c%2B%2B-java-inorder-(iterative)-simple-and-fast | class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
st = []
cur_depth = 1
flag = False
while root != None or len(st) != 0 :
if root != None:
if root == p or root == q :
if flag : return ans
else : flag, d, ans = True, cur_depth, root
st.append( (root, cur_depth) )
cur_depth += 1
root = root.left
else :
root, cur_depth = st.pop()
if flag and cur_depth < d : d, ans = cur_depth, root
root = root.right | lowest-common-ancestor-of-a-binary-tree | python, c++, java - inorder (iterative) simple & fast | ZX007java | 0 | 14 | lowest common ancestor of a binary tree | 236 | 0.581 | Medium | 4,421 |
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/discuss/2334940/Python-Solution | class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if root == None:
return root
if root.val == p.val or root.val == q.val:
return root
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
if left and right:
return root
return left if right == None else right | lowest-common-ancestor-of-a-binary-tree | Python Solution | creativerahuly | 0 | 1 | lowest common ancestor of a binary tree | 236 | 0.581 | Medium | 4,422 |
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/discuss/2334234/Python3-or-Easy-to-Understand-or-Iterative-Solution | class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
que = deque([root])
parent = {root: None}
while que:
node = que.popleft()
if node.left:
que.append(node.left)
parent[node.left] = node
if node.right:
que.append(node.right)
parent[node.right] = node
if p in parent and q in parent:
break
ancestors = set()
while p:
ancestors.add(p)
p = parent[p]
while q:
if q in ancestors:
return q
q = parent[q] | lowest-common-ancestor-of-a-binary-tree | ✅Python3 | Easy to Understand | Iterative Solution | thesauravs | 0 | 15 | lowest common ancestor of a binary tree | 236 | 0.581 | Medium | 4,423 |
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/discuss/2272476/Clean-Code-in-C%2B%2B-and-Python | class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if root==p or root==q:
return root
if root.left:
left = self.lowestCommonAncestor(root.left,p,q)
if not root.left:
left = None
if root.right:
right = self.lowestCommonAncestor(root.right,p,q)
if not root.right:
right = None
if left and right:
return root
else:
return left or right | lowest-common-ancestor-of-a-binary-tree | Clean Code in C++ and Python | Ridzzz | 0 | 78 | lowest common ancestor of a binary tree | 236 | 0.581 | Medium | 4,424 |
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/discuss/2178743/Recursive-Approach | class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if root.val == p.val or root.val == q.val:
return root
if root.left == None and root.right == None:
return None
left = None
right = None
if root.left:
left = self.lowestCommonAncestor(root.left, p, q)
if root.right:
right = self.lowestCommonAncestor(root.right, p , q)
if left and right:
return root
if left == None:
return right
else:
return left | lowest-common-ancestor-of-a-binary-tree | Recursive Approach | Vaibhav7860 | 0 | 48 | lowest common ancestor of a binary tree | 236 | 0.581 | Medium | 4,425 |
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/discuss/1566770/Python3-Recursive-solution | class Solution:
def __init__(self):
self.seen = collections.defaultdict(TreeNode)
def get_list(self, cur, prev, target):
if not cur:
return None
self.seen[cur.val] = cur
new_cur = TreeNode(cur.val)
new_cur.left = prev
if new_cur.val == target.val:
return new_cur
_next = cur.left
head_from_left = self.get_list(_next, new_cur, target)
if head_from_left:
return head_from_left
_next = cur.right
head_from_right = self.get_list(_next, new_cur, target)
if head_from_right:
return head_from_right
new_cur.left = None
return None
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
head1 = self.get_list(root, None, p)
head2 = self.get_list(root, None, q)
it1, it2 = head1, head2
while it1.val != it2.val:
if not it1.left:
it1 = head2
else:
it1 = it1.left
if not it2.left:
it2 = head1
else:
it2 = it2.left
return self.seen[it1.val] | lowest-common-ancestor-of-a-binary-tree | [Python3] Recursive solution | maosipov11 | 0 | 90 | lowest common ancestor of a binary tree | 236 | 0.581 | Medium | 4,426 |
https://leetcode.com/problems/delete-node-in-a-linked-list/discuss/1454184/95.96-faster-and-Simpler-solution-with-Explanation. | class Solution:
def deleteNode(self, node):
nextNode = node.next
node.val = nextNode.val
node.next = nextNode.next | delete-node-in-a-linked-list | 95.96% faster and Simpler solution with Explanation. | AmrinderKaur1 | 6 | 870 | delete node in a linked list | 237 | 0.753 | Medium | 4,427 |
https://leetcode.com/problems/delete-node-in-a-linked-list/discuss/297138/Python-faster-than-97-24-ms | class Solution(object):
def deleteNode(self, node):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead.
"""
cur = node
while node.next!=None:
node.val = node.next.val
cur = node
node = node.next
cur.next = None | delete-node-in-a-linked-list | Python - faster than 97%, 24 ms | il_buono | 5 | 1,800 | delete node in a linked list | 237 | 0.753 | Medium | 4,428 |
https://leetcode.com/problems/delete-node-in-a-linked-list/discuss/2699687/Python3-ONE-LINER-O_o-holly-shch-explained | class Solution:
def deleteNode(self, node):
node.val, node.next.next, node.next = node.next.val, None, node.next.next | delete-node-in-a-linked-list | ✔️ [Python3] ONE LINER, O_o holly shch, explained | artod | 4 | 114 | delete node in a linked list | 237 | 0.753 | Medium | 4,429 |
https://leetcode.com/problems/delete-node-in-a-linked-list/discuss/2696852/python-easy-solution-in-5-lines | class Solution:
def deleteNode(self, node):
node.val=node.next.val
if node.next.next:
node.next=node.next.next
else:
node.next=None | delete-node-in-a-linked-list | python easy solution in 5 lines | shubham_1307 | 3 | 602 | delete node in a linked list | 237 | 0.753 | Medium | 4,430 |
https://leetcode.com/problems/delete-node-in-a-linked-list/discuss/2457174/easy-python-code-or-O(1) | class Solution:
def deleteNode(self, node):
node.val = node.next.val
node.next = node.next.next | delete-node-in-a-linked-list | easy python code | O(1) | dakash682 | 3 | 208 | delete node in a linked list | 237 | 0.753 | Medium | 4,431 |
https://leetcode.com/problems/delete-node-in-a-linked-list/discuss/2696556/Python3-C%2B%2B-Easy-approach! | class Solution:
def deleteNode(self, node):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead.
"""
node.val = node.next.val
node.next = node.next.next | delete-node-in-a-linked-list | [Python3, C++] Easy approach! | JoeH | 1 | 28 | delete node in a linked list | 237 | 0.753 | Medium | 4,432 |
https://leetcode.com/problems/delete-node-in-a-linked-list/discuss/2696556/Python3-C%2B%2B-Easy-approach! | class Solution:
def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
prev = dummy = ListNode(-1)
prev.next = cur = head
while cur:
if cur.val == val:
prev.next = cur.next
else: # """ CRITICAL BRANCH! """
prev = prev.next
cur = cur.next
return dummy.next | delete-node-in-a-linked-list | [Python3, C++] Easy approach! | JoeH | 1 | 28 | delete node in a linked list | 237 | 0.753 | Medium | 4,433 |
https://leetcode.com/problems/delete-node-in-a-linked-list/discuss/1892649/Python-One-liner-or-O(1) | class Solution:
def deleteNode(self, node):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead.
"""
node.val, node.next = node.next.val, node.next.next | delete-node-in-a-linked-list | Python One liner | O(1) | parthpatel9414 | 1 | 133 | delete node in a linked list | 237 | 0.753 | Medium | 4,434 |
https://leetcode.com/problems/delete-node-in-a-linked-list/discuss/1858237/1-Line-Python-Solution-oror-40-Faster-oror-Memory-less-than-95 | class Solution:
def deleteNode(self, node):
node.val,node.next=node.next.val,node.next.next | delete-node-in-a-linked-list | 1-Line Python Solution || 40% Faster || Memory less than 95% | Taha-C | 1 | 79 | delete node in a linked list | 237 | 0.753 | Medium | 4,435 |
https://leetcode.com/problems/delete-node-in-a-linked-list/discuss/877029/Python3-simple-solution-beats-95 | class Solution:
def deleteNode(self, node):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead.
"""
node.val = node.next.val
node.next = node.next.next | delete-node-in-a-linked-list | Python3 simple solution, beats 95% | n0execution | 1 | 478 | delete node in a linked list | 237 | 0.753 | Medium | 4,436 |
https://leetcode.com/problems/delete-node-in-a-linked-list/discuss/468005/Python-3-(one-line)-(beats-~99) | class Solution:
def deleteNode(self, N):
N.next, N.val = N.next.next, N.next.val
- Junaid Mansuri
- Chicago, IL | delete-node-in-a-linked-list | Python 3 (one line) (beats ~99%) | junaidmansuri | 1 | 802 | delete node in a linked list | 237 | 0.753 | Medium | 4,437 |
https://leetcode.com/problems/delete-node-in-a-linked-list/discuss/2781334/Python-oror-Easy | class Solution:
def deleteNode(self, node):
while node and node.next:
node.val = node.next.val
prev = node
node = node.next
prev.next = None | delete-node-in-a-linked-list | Python || Easy | morpheusdurden | 0 | 5 | delete node in a linked list | 237 | 0.753 | Medium | 4,438 |
https://leetcode.com/problems/delete-node-in-a-linked-list/discuss/2700215/Python | class Solution:
def deleteNode(self, node):
last = None
while node.next != None:
last = node
node.val = node.next.val
node = node.next
last.next = None | delete-node-in-a-linked-list | Python | JSTM2022 | 0 | 5 | delete node in a linked list | 237 | 0.753 | Medium | 4,439 |
https://leetcode.com/problems/delete-node-in-a-linked-list/discuss/2699926/Python3!-As-short-as-it-gets. | class Solution:
def deleteNode(self, node):
node.val = node.next.val
if node.next.next is None:
node.next = None
else:
self.deleteNode(node.next) | delete-node-in-a-linked-list | 😎Python3! As short as it gets. | aminjun | 0 | 5 | delete node in a linked list | 237 | 0.753 | Medium | 4,440 |
https://leetcode.com/problems/delete-node-in-a-linked-list/discuss/2699648/2-lines-Code | class Solution:
def deleteNode(self, node):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead.
"""
node.val=node.next.val
node.next=node.next.next | delete-node-in-a-linked-list | 2 lines Code | venkatasaipalla | 0 | 4 | delete node in a linked list | 237 | 0.753 | Medium | 4,441 |
https://leetcode.com/problems/delete-node-in-a-linked-list/discuss/2699136/Python3-base-solution-for-real | class Solution:
def deleteNode(self, node):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead.
"""
node.val = node.next.val
node.next = node.next.next | delete-node-in-a-linked-list | Python3, base solution for real 🏭 | evvfebruary | 0 | 5 | delete node in a linked list | 237 | 0.753 | Medium | 4,442 |
https://leetcode.com/problems/delete-node-in-a-linked-list/discuss/2698882/2-lines-python-solution | class Solution:
def deleteNode(self, node):
node.val = node.next.val
node.next = node.next.next | delete-node-in-a-linked-list | 2 lines python solution | valera_grishko | 0 | 9 | delete node in a linked list | 237 | 0.753 | Medium | 4,443 |
https://leetcode.com/problems/delete-node-in-a-linked-list/discuss/2698697/My-Solution-in-PYTHON | class Solution(object):
def deleteNode(self, node):
node.val = node.next.val
node.next = node.next.next | delete-node-in-a-linked-list | My Solution in --- PYTHON | A14K | 0 | 2 | delete node in a linked list | 237 | 0.753 | Medium | 4,444 |
https://leetcode.com/problems/delete-node-in-a-linked-list/discuss/2698356/3-Line-code-in-Python | class Solution:
# Simply duplicate the next node and delete the next node since it is given this is not the last node!!!
def deleteNode(self, node):
nn = node.next
node.val = nn.val
node.next = nn.next | delete-node-in-a-linked-list | 3 Line code in Python 🥶 | shiv-codes | 0 | 4 | delete node in a linked list | 237 | 0.753 | Medium | 4,445 |
https://leetcode.com/problems/delete-node-in-a-linked-list/discuss/2697795/Python-or-2-line-code | class Solution:
def deleteNode(self, node):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead.
"""
node.val = node.next.val
node.next = node.next.next | delete-node-in-a-linked-list | Python | 2 line code | KevinJM17 | 0 | 4 | delete node in a linked list | 237 | 0.753 | Medium | 4,446 |
https://leetcode.com/problems/delete-node-in-a-linked-list/discuss/2697098/python-solution-delete-node-in-linked-list | class Solution:
def deleteNode(self, node):
node.val=node.next.val
if node.next.next:
node.next=node.next.next
else:
node.next=None
return | delete-node-in-a-linked-list | python solution delete node in linked list | shashank_2000 | 0 | 3 | delete node in a linked list | 237 | 0.753 | Medium | 4,447 |
https://leetcode.com/problems/delete-node-in-a-linked-list/discuss/2696921/Python-Simple-Python-Solution-or-93-Faster | class Solution:
def deleteNode(self, node):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead.
"""
node.val = node.next.val
node.next = node.next.next | delete-node-in-a-linked-list | [ Python ] ✅✅ Simple Python Solution | 93% Faster 🥳✌👍 | ASHOK_KUMAR_MEGHVANSHI | 0 | 7 | delete node in a linked list | 237 | 0.753 | Medium | 4,448 |
https://leetcode.com/problems/delete-node-in-a-linked-list/discuss/2696705/Python3-Simple-Solution | class Solution:
def deleteNode(self, node):
node.val = node.next.val
node.next = node.next.next | delete-node-in-a-linked-list | Python3 Simple Solution | mediocre-coder | 0 | 1 | delete node in a linked list | 237 | 0.753 | Medium | 4,449 |
https://leetcode.com/problems/delete-node-in-a-linked-list/discuss/2696677/Python3-or-Traversal-or-Straight-Forward | class Solution:
def deleteNode(self, node):
# Solution - traversal
# Time - O(N)
# Space - O(1)
temp = node
prev = None
prev2 = None
while temp:
prev2 = prev
prev = temp
temp = temp.next
if temp:
prev.val = temp.val
prev2.next = None | delete-node-in-a-linked-list | Python3 | Traversal | Straight Forward | vikinam97 | 0 | 2 | delete node in a linked list | 237 | 0.753 | Medium | 4,450 |
https://leetcode.com/problems/delete-node-in-a-linked-list/discuss/2696219/Python | class Solution:
def deleteNode(self, node):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead.
"""
node.val = node.next.val
node.next = node.next.next | delete-node-in-a-linked-list | Python | blue_sky5 | 0 | 20 | delete node in a linked list | 237 | 0.753 | Medium | 4,451 |
https://leetcode.com/problems/product-of-array-except-self/discuss/744951/Product-of-array-except-self-Python3-Solution-with-a-Detailed-Explanation | class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
leftProducts = [0]*len(nums) # initialize left array
rightProducts = [0]*len(nums) # initialize right array
leftProducts[0] = 1 # the left most is 1
rightProducts[-1] = 1 # the right most is 1
res = [] # output
for i in range(1, len(nums)):
leftProducts[i] = leftProducts[i-1]*nums[i-1]
rightProducts[len(nums) - i - 1] = rightProducts[len(nums) - i]*nums[len(nums) - i]
for i in range(len(nums)):
res.append(leftProducts[i]*rightProducts[i])
return res | product-of-array-except-self | Product of array except self - Python3 Solution with a Detailed Explanation | peyman_np | 12 | 1,200 | product of array except self | 238 | 0.648 | Medium | 4,452 |
https://leetcode.com/problems/product-of-array-except-self/discuss/744951/Product-of-array-except-self-Python3-Solution-with-a-Detailed-Explanation | class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
res = []
p = 1
for i in range(len(nums)):
res.append(p)
p = p * nums[i]
p = 1
for i in range(len(nums) - 1, -1, -1):
res[i] = res[i] * p #1
p = p*nums[i]
return res | product-of-array-except-self | Product of array except self - Python3 Solution with a Detailed Explanation | peyman_np | 12 | 1,200 | product of array except self | 238 | 0.648 | Medium | 4,453 |
https://leetcode.com/problems/product-of-array-except-self/discuss/1476274/O(N2)-to-O(N)-oror-Thought-Process-Explained | class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
n = len(nums)
answer = [1] * n #this will hold our output
for i in range(0, n):
for j in range(0, n):
if i != j:
answer[i] = answer[i] * nums[j]
return answer | product-of-array-except-self | O(N^2) to O(N) || Thought Process Explained | aarushsharmaa | 6 | 570 | product of array except self | 238 | 0.648 | Medium | 4,454 |
https://leetcode.com/problems/product-of-array-except-self/discuss/2546343/Two-pass-solution | class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
res = [1 for i in range(len(nums))]
for i in range(1, len(nums)):
res[i] = nums[i-1] * res[i-1]
tmp = 1
for i in range(len(nums)-2,-1,-1):
tmp *= nums[i+1]
res[i] *= tmp
return res | product-of-array-except-self | 📌 Two pass solution | croatoan | 4 | 258 | product of array except self | 238 | 0.648 | Medium | 4,455 |
https://leetcode.com/problems/product-of-array-except-self/discuss/2005648/Highly-Efficient-Python-code-or-Beats-99-or-With-Explanantion | class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
dp=[]
product=1
for i in nums:
dp.append(product)
product*=i
product=1
for i in range(len(nums)-1,-1,-1):
dp[i]=dp[i]*product
product*=nums[i]
return dp | product-of-array-except-self | Highly Efficient Python code | Beats 99% | With Explanantion | RickSanchez101 | 4 | 399 | product of array except self | 238 | 0.648 | Medium | 4,456 |
https://leetcode.com/problems/product-of-array-except-self/discuss/2078944/Python-Solution-2-Approches | class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
# # 1. space = O(2n) = O(n) and time = O(n)
# prefixes = [1]*len(nums)
# postfixes = [1]*len(nums)
# #calculate prefix product array - each index will have total product of all elements BEFORE it
# prefix = 1
# for i in range(1,len(nums)):
# prefix *= nums[i-1]
# prefixes[i] = prefix
# #calculate postfix product array - each index will have total product of all elements AFTER it
# postfix = 1
# for i in range(len(nums)-2, -1,-1):
# postfix *= nums[i+1]
# postfixes[i] = postfix
# final = []
# for i,j in zip(prefixes,postfixes):
# final.append(i*j)
# return final
# 2. space = O(1) and time = O(n)
final = [1]*len(nums)
#Do the prefix product calculation
product = 1
for i in range(1, len(nums)):
product *= nums[i-1]
final[i] *= product
#Do the postfix product calculation
product = 1
for i in range(len(nums)-2, -1,-1):
product *= nums[i+1]
final[i] *= product
return final | product-of-array-except-self | Python Solution 2 Approches | sanapgovind1 | 3 | 265 | product of array except self | 238 | 0.648 | Medium | 4,457 |
https://leetcode.com/problems/product-of-array-except-self/discuss/2144756/Readable-Python-O(n)-and-O(1)-space-solutions-with-explanations | class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
# product of all numbers left of i
left_product = [1] * len(nums)
for i in range(1, len(nums)):
left_product[i] = nums[i-1] * left_product[i-1]
# product of all numbers right of i
right_product = [1] * len(nums)
for i in range(len(nums)-2, -1, -1):
right_product[i] = nums[i+1] * right_product[i+1]
# product of all numbers except i = product of all numbers left of i and all numbers right of i
return [a * b for a,b in zip(left_product, right_product)] | product-of-array-except-self | Readable Python O(n) and O(1) space solutions with explanations | rafikiiii | 2 | 364 | product of array except self | 238 | 0.648 | Medium | 4,458 |
https://leetcode.com/problems/product-of-array-except-self/discuss/2144756/Readable-Python-O(n)-and-O(1)-space-solutions-with-explanations | class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
answer = [0] * len(nums)
# product of all numbers before i
left_product = 1
for i in range(len(nums)):
# let answer[i] = product of numbers left of i
answer[i] = left_product
# update left_product to include i for the next iteration (i+1)
left_product *= nums[i]
# product of all numbers after i
right_product = 1
for i in reversed(range(len(nums))):
# now answer[i] = left_product * right_product for all i
answer[i] *= right_product
# update right_product to include i for next iteration (i-1)
right_product *= nums[i]
return answer | product-of-array-except-self | Readable Python O(n) and O(1) space solutions with explanations | rafikiiii | 2 | 364 | product of array except self | 238 | 0.648 | Medium | 4,459 |
https://leetcode.com/problems/product-of-array-except-self/discuss/1558245/Python-two-pass-solution | class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
total_prod = 1
res = []
for num in nums:
res.append(total_prod)
total_prod *= num
total_prod = 1
for i in range(len(nums)-1, -1, -1):
res[i] *= total_prod
total_prod *= nums[i]
return res | product-of-array-except-self | Python two pass solution | dereky4 | 2 | 654 | product of array except self | 238 | 0.648 | Medium | 4,460 |
https://leetcode.com/problems/product-of-array-except-self/discuss/1525666/Understandable-Python-code-for-beginners-with-and-without-extra-space | class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
left=[0]*len(nums)
right=[0]*len(nums)
left[0],right[-1]=nums[0],nums[-1]
for i in range(1,len(nums)):
left[i]=nums[i]*left[i-1]
for i in range(len(nums)-2,-1,-1):
right[i]=nums[i]*right[i+1]
for i in range(len(nums)):
if(i==0):
nums[i]=right[i+1]
elif(i==len(nums)-1):
nums[i]=left[i-1]
else:
nums[i]=left[i-1]*right[i+1]
return nums | product-of-array-except-self | Understandable Python code for beginners with and without extra space | kabiland | 2 | 213 | product of array except self | 238 | 0.648 | Medium | 4,461 |
https://leetcode.com/problems/product-of-array-except-self/discuss/1525666/Understandable-Python-code-for-beginners-with-and-without-extra-space | class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
out=[0]*len(nums)
out[0]=nums[0]
for i in range(1,len(nums)):
out[i]=nums[i]*out[i-1]
prod=1
out[-1]=out[-2]
for i in range(len(nums)-2,-1,-1):
prod=prod*nums[i+1]
if(i==0):
out[0]=prod
else:
out[i]=out[i-1]*prod
return out | product-of-array-except-self | Understandable Python code for beginners with and without extra space | kabiland | 2 | 213 | product of array except self | 238 | 0.648 | Medium | 4,462 |
https://leetcode.com/problems/product-of-array-except-self/discuss/2846283/Python-oror-96.15-Faster-oror-T.C.-%3AO(n)-S.C.-%3AO(1)-oror-Prefix-and-Postfix-Array | class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
prefix,n=1,len(nums)
answer=[1]
for i in range(1,n):
prefix*=nums[i-1]
answer.append(prefix)
postfix=1
for i in range(n-2,-1,-1):
postfix*=nums[i+1]
answer[i]*=postfix
return answer | product-of-array-except-self | Python || 96.15% Faster || T.C. :O(n) S.C. :O(1) || Prefix and Postfix Array | DareDevil_007 | 1 | 13 | product of array except self | 238 | 0.648 | Medium | 4,463 |
https://leetcode.com/problems/product-of-array-except-self/discuss/2642068/oror | class Solution(object):
def productExceptSelf(self, nums):
res=[1]*(len(nums))
prefix=1
for i in range(len(nums)):
res[i]=prefix
prefix*=nums[i]
postfix=1
for i in range(len(nums)-1,-1,-1):
res[i]*=postfix
postfix*=nums[i]
return res | product-of-array-except-self | 𝐒𝐢𝐦𝐩𝐥𝐞 𝐀𝐩𝐩𝐫𝐨𝐚𝐜𝐡|| 𝐒𝐨𝐥𝐮𝐭𝐢𝐨𝐧 𝐰𝐢𝐭𝐡 𝐞𝐱𝐩𝐥𝐚𝐧𝐚𝐭𝐢𝐨𝐧 | m_e_shivam | 1 | 173 | product of array except self | 238 | 0.648 | Medium | 4,464 |
https://leetcode.com/problems/product-of-array-except-self/discuss/2331077/Python-97.71-faster-or-Simplest-solution-with-explanation-or-Beg-to-Adv-or-Prefix-Sum | class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
answer = []
mul = 1
for i in range(len(nums)):
for j in range(len(nums)):
if i!=j:
mul = mul * nums[j]
answer.append(mul)
mul = 1
return answer | product-of-array-except-self | Python 97.71% faster | Simplest solution with explanation | Beg to Adv | Prefix Sum | rlakshay14 | 1 | 219 | product of array except self | 238 | 0.648 | Medium | 4,465 |
https://leetcode.com/problems/product-of-array-except-self/discuss/2331077/Python-97.71-faster-or-Simplest-solution-with-explanation-or-Beg-to-Adv-or-Prefix-Sum | class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
total_prod = 1
res = []
#leftProduct
#0(N) time
for num in nums:
res.append(total_prod)
total_prod *= num
# res=[1,1,2,6]
#rightProduct * leftProduct = answer
#0(N) time
total_prod = 1
for i in range(len(nums)-1, -1, -1): # for right product we are running the loop in reverse. 3, 2, 1, 0
res[i] *= total_prod # 6*1, 2*4, 1*12, 1*24 || [24, 12, 8, 6]
total_prod *= nums[i] # 1, 4, 12, 24
return res | product-of-array-except-self | Python 97.71% faster | Simplest solution with explanation | Beg to Adv | Prefix Sum | rlakshay14 | 1 | 219 | product of array except self | 238 | 0.648 | Medium | 4,466 |
https://leetcode.com/problems/product-of-array-except-self/discuss/1823078/Python-Simplest-solutions! | class Solution:
def productExceptSelf(self, nums):
n = len(nums)
l_products = [1] * n
r_products = [1] * n
for i in range(0, n-1):
l_products[i+1] = nums[i] * l_products[i]
for j in range(n-1, 0, -1):
r_products[j-1] = nums[j] * r_products[j]
answer = list(map(mul, l_products, r_products))
return answer | product-of-array-except-self | Python - Simplest solutions! | domthedeveloper | 1 | 338 | product of array except self | 238 | 0.648 | Medium | 4,467 |
https://leetcode.com/problems/product-of-array-except-self/discuss/1823078/Python-Simplest-solutions! | class Solution:
def productExceptSelf(self, nums):
n = len(nums)
products = [1] * n
left = 1
for i in range(0, n-1):
left *= nums[i]
products[i+1] = left
right = 1
for j in range(n-1, 0, -1):
right *= nums[j]
products[j-1] *= right
return products | product-of-array-except-self | Python - Simplest solutions! | domthedeveloper | 1 | 338 | product of array except self | 238 | 0.648 | Medium | 4,468 |
https://leetcode.com/problems/product-of-array-except-self/discuss/1779066/Python-easy-to-read-and-understand | class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
n = len(nums)
prefix = [1 for _ in range(n+2)]
suffix = [1 for _ in range(n+2)]
for i in range(1, n+1):
prefix[i] = prefix[i-1]*nums[i-1]
for i in range(n, 0, -1):
suffix[i] = suffix[i+1]*nums[i-1]
ans = []
for i in range(1, n+1):
ans.append(prefix[i-1]*suffix[i+1])
return ans | product-of-array-except-self | Python easy to read and understand | sanial2001 | 1 | 329 | product of array except self | 238 | 0.648 | Medium | 4,469 |
https://leetcode.com/problems/product-of-array-except-self/discuss/1738742/Self-understandable-Python-(2-methods-with-O(n)-time-%2B-constant-space) | class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
prefix_mul=[1]
sufix_mul=[1]
z=[]
x,y=1,1
res=list(reversed(nums))
for i in range(1,len(nums)):
x=x*nums[i-1]
prefix_mul.append(x)
y=y*res[i-1]
sufix_mul.append(y)
sufix_mul.reverse()
for i in range(len(nums)):
z.append(prefix_mul[i]*sufix_mul[i])
return z | product-of-array-except-self | Self understandable Python (2 methods with O(n) time + constant space) | goxy_coder | 1 | 135 | product of array except self | 238 | 0.648 | Medium | 4,470 |
https://leetcode.com/problems/product-of-array-except-self/discuss/1711146/WEEB-DOES-PYTHON-2-PASS | class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
curProd = 1
result = []
for i in range(len(nums)):
result.append(curProd)
curProd *= nums[i]
curProd = 1
for i in range(len(nums)-1, -1, -1):
result[i] *= curProd
curProd *= nums[i]
return result | product-of-array-except-self | WEEB DOES PYTHON 2 PASS | Skywalker5423 | 1 | 154 | product of array except self | 238 | 0.648 | Medium | 4,471 |
https://leetcode.com/problems/product-of-array-except-self/discuss/1370850/Python3-O(n)-time-and-O(n)-space-complexity-solution | class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
prefix = [0]*len(nums)
suffix = [0]*len(nums)
for i in range(len(nums)):
if i == 0:
prefix[i] = 1
else:
prefix[i] = prefix[i-1]*nums[i-1]
for i in range(len(nums)-1,-1,-1):
if i == len(nums)-1:
suffix[i] = 1
else:
suffix[i] = suffix[i+1]*nums[i+1]
for i in range(len(prefix)):
prefix[i] *= suffix[i]
return prefix | product-of-array-except-self | Python3 O(n) time and O(n) space complexity solution | EklavyaJoshi | 1 | 108 | product of array except self | 238 | 0.648 | Medium | 4,472 |
https://leetcode.com/problems/product-of-array-except-self/discuss/1080086/simple-python-O(n)-space-O(1) | class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
"""
agg = 6
output_arr =
[24,12,8,6]
"""
# edge case [1]
if len(nums) <= 1:
return nums
# initialize the arr
output_arr = [1] * len(nums)
# goes right to left
agg = 1
for idx in range(len(nums)-2, -1, -1):
agg *= nums[idx+1]
output_arr[idx] = agg
# goes left to right
agg = 1
for idx in range(1, len(nums)):
agg *= nums[idx-1]
output_arr[idx] *= agg
return output_arr | product-of-array-except-self | simple python O(n) space O(1) | xavloc | 1 | 82 | product of array except self | 238 | 0.648 | Medium | 4,473 |
https://leetcode.com/problems/product-of-array-except-self/discuss/2845134/Python3-greater-2-pass | class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
res = [1]
L = len(nums)
for i in range(L - 1):
res.append(res[-1] * nums[i])
prod = 1
for i in range(L - 2, -1, -1):
prod *= nums[i + 1]
res[i] = prod * res[i]
return res | product-of-array-except-self | Python3 -> 2 pass | mediocre-coder | 0 | 3 | product of array except self | 238 | 0.648 | Medium | 4,474 |
https://leetcode.com/problems/product-of-array-except-self/discuss/2843854/Python-or-PrefixPostfix-or-Comments-and-Explanation | class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
length = len(nums)
res = [1] * length # setting everything to 1 because if we set it to 0, then things get multiplied by 0
prev_postfix = 1 # having this here so we can actually do this in "O(1)" space by not saving the postfixes in another array
for i in range(length-1): # this saves the prefixes to i+1 because we're multiplying the first 3 prefixes to the last 3 postfixes in an offsetted way.
res[i+1] = nums[i] * res[i] # we basically leave the first element untouched in a prefix
print(res)
for i in range(length-1): # this multiplies the postfixes to the prefixes. like above, it's an offset so we only multiply the last 3 prefixes.
i = -1 - i
prev_postfix *= nums[i] # saves the postfix as talked about above
print(prev_postfix)
res[i-1] = res[i-1] * prev_postfix # since it's a postfix, we leave the end alone due to the nature of the problem and post/prefixes
# to expand on the problem further, we basically take the all of the left and right of the index that we're on and multiply all of them together.
return res | product-of-array-except-self | 🎉Python | Prefix/Postfix | Comments and Explanation | Arellano-Jann | 0 | 2 | product of array except self | 238 | 0.648 | Medium | 4,475 |
https://leetcode.com/problems/product-of-array-except-self/discuss/2838038/Easy-Python-solution | class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
prefix, suffix = 1,1
result_array = [1]*len(nums)
for i in range(len(nums)):
result_array[i] = prefix
prefix = prefix * nums[i]
for i in range(len(nums)-1,-1,-1):
result_array[i] = suffix * result_array[i]
suffix = suffix*nums[i]
return result_array | product-of-array-except-self | Easy Python solution | float_boat | 0 | 5 | product of array except self | 238 | 0.648 | Medium | 4,476 |
https://leetcode.com/problems/product-of-array-except-self/discuss/2834010/Python3-Beats-90-using-Hashmap-w-explaination | class Solution:
def product(self, arr: List[int], idx: int, prod = 1):
for i in range(len(arr)):
if i != idx:
prod *= arr[i]
return prod
def productExceptSelf(self, nums: List[int]) -> List[int]:
if len(set(nums)) == 1: [self.product(nums, 0) * len(nums)]
r, map = [], {}
for i in range(len(nums)):
if nums[i] not in map:
prod = self.product(nums,i)
map[nums[i]] = prod
r.append(prod)
else: r.append(map[nums[i]])
return r | product-of-array-except-self | ✅ [Python3] Beats 90% using Hashmap w/ explaination | m0nxt3r | 0 | 5 | product of array except self | 238 | 0.648 | Medium | 4,477 |
https://leetcode.com/problems/product-of-array-except-self/discuss/2827623/Python-simple-solution-(Runtime-16-Memory-18) | class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
left = [1]*len(nums)
right = [1]*len(nums)
sol = [1]*len(nums)
mul = 1
left[0] = nums[0]
right[-1] = nums[-1]
for i in range(len(nums)):
mul = mul*nums[i]
left[i] = mul
mul = 1
for i in range(len(nums)-1,-1,-1):
mul = mul*nums[i]
right[i] = mul
sol[0] = right[1]
sol[-1] = left[-2]
for i in range(1,len(nums)-1):
sol[i] = left[i-1]*right[i+1]
return sol | product-of-array-except-self | Python simple solution (Runtime 16%; Memory 18%) | BanarasiVaibhav | 0 | 6 | product of array except self | 238 | 0.648 | Medium | 4,478 |
https://leetcode.com/problems/product-of-array-except-self/discuss/2825025/Easy-python-solution | class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
rp = 1
result = []
#left pass
for i in range(len(nums)):
result.append(rp);
rp *= nums[i]
#right pass
rp = 1
for i in range(len(nums)-1, -1, -1):
result[i] *= rp
rp *= nums[i]
return result | product-of-array-except-self | Easy python solution | rustandruin | 0 | 2 | product of array except self | 238 | 0.648 | Medium | 4,479 |
https://leetcode.com/problems/product-of-array-except-self/discuss/2823918/SIMPLEST-SOLUTION-TC-O(N)-SC-O(1) | class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
zeros = 0
prod = 1
for i in nums:
if(i == 0):
zeros += 1
else:
prod *= i
if(zeros > 1):
return [0]*len(nums)
if(zeros == 1):
for i in range(len(nums)):
if(nums[i] == 0):
nums[i] = prod
else:
nums[i] = 0
if(zeros == 0):
for i in range(len(nums)):
if(nums[i] == 0):
nums[i] = prod
else:
nums[i] = prod//nums[i]
return nums | product-of-array-except-self | SIMPLEST SOLUTION TC = O(N), SC= O(1) | MAYANK-M31 | 0 | 3 | product of array except self | 238 | 0.648 | Medium | 4,480 |
https://leetcode.com/problems/product-of-array-except-self/discuss/2822536/Prefix-and-Postfix-without-extra-memory | class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
# to save memory, the prefix will be stored in the output
# array, then nums will be iterated in reverse to find the
# postfix while computing the final result
# the pre will initially be 1 and updated by multiplying
# the current number iterated and the pre
# the same process will follow with the postfix
# time O(n) space O(1) (output array doesn't count)
res = []
pre = post = 1
for i in range(len(nums)):
res.append(pre)
pre *= nums[i]
for i in range(len(nums) - 1, -1, -1):
res[i] = res[i] * post
post *= nums[i]
return res | product-of-array-except-self | Prefix and Postfix without extra memory | andrewnerdimo | 0 | 4 | product of array except self | 238 | 0.648 | Medium | 4,481 |
https://leetcode.com/problems/product-of-array-except-self/discuss/2822497/Prefix-and-Postfix-extra-memory | class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
# store the prefix result (the prod of all elements preceeding)
# store the postfix result (the prod of all elements coming after)
# the product at an index i is prefix[i] * postfix[i] which yields
# the correct product at that index if the number was ignored
# time O(n) space O(n)
prefix = nums.copy()
for i in range(1, len(prefix)):
prefix[i] = prefix[i] * prefix[i - 1]
postfix = nums.copy()
for i in range(len(nums) - 2, -1, -1):
postfix[i] = postfix[i] * postfix[i + 1]
nums[0] = postfix[1]
nums[-1] = prefix[-2]
for i in range(1, len(nums) - 1):
nums[i] = prefix[i - 1] * postfix[i + 1]
return nums | product-of-array-except-self | Prefix and Postfix extra memory | andrewnerdimo | 0 | 1 | product of array except self | 238 | 0.648 | Medium | 4,482 |
https://leetcode.com/problems/product-of-array-except-self/discuss/2822414/Keep-track-of-zeros | class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
# init prod as 1
# keep track of zeros seen
# if the number is non-zero get new prod
# otherwise increment count of zero
# if there's no zero's nums[i] = prod / nums[i]
# if there's 1 zero nums[i] = 0 if it's non-zero, otherwise
# the prod without zero
# if there's more than 1 zero, it's just all zeros for the size
# of nums
# time O(n) space O(1)
prod = 1
count = 0
for num in nums:
if num:
prod *= num
else:
count += 1
for i, num in enumerate(nums):
if count > 1:
nums[i] = 0
elif count == 1:
nums[i] = 0 if nums[i] else prod
else:
nums[i] = prod // num
return nums | product-of-array-except-self | Keep track of zeros | andrewnerdimo | 0 | 2 | product of array except self | 238 | 0.648 | Medium | 4,483 |
https://leetcode.com/problems/product-of-array-except-self/discuss/2818614/Prefix-and-Postfix-Calculation | class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
# answer is an array of 1s to start
answer = [1] * len(nums)
# pre and post fix calculation of product of array
# prefix runs forward and starts at 1
prefix = 1
for index in range(len(nums)) :
# at each index, multiply by prefix then update prefix
answer[index] = answer[index] * prefix
prefix = prefix * nums[index]
# postfix runs backward and starts at 1
postfix = 1
for index in range(len(nums)-1, -1, -1) :
# at each index, multiply by postfix then update postfix
answer[index] = answer[index] * postfix
postfix = postfix * nums[index]
# return answer when done
return answer | product-of-array-except-self | Prefix and Postfix Calculation | laichbr | 0 | 1 | product of array except self | 238 | 0.648 | Medium | 4,484 |
https://leetcode.com/problems/product-of-array-except-self/discuss/2814010/productExceptSelf | class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
# product except self
# prefix = [1, 2,6, 24]
# postfix = [24, 24, 12, 4]
result = [1] * (len(nums))
prefix = 1
postfix = 1
for i in range(len(nums)):
result[i] = prefix
prefix *= nums[i]
for i in range(len(nums) -1, -1, -1):
result[i] *= postfix
postfix *= nums[i]
return result | product-of-array-except-self | productExceptSelf | antukassaw1 | 0 | 5 | product of array except self | 238 | 0.648 | Medium | 4,485 |
https://leetcode.com/problems/product-of-array-except-self/discuss/2811239/Python-Prefix-and-suffix-O(n)-or-Full-explanation | class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
"""Initialise an array to keep track of products. Make one pass forwards over
the input array multiplying each respective product by the input values behind
it. Make one pass backwards, multiplying each product by the input values ahead
of it. Keep this multiplication O(n) by accumlating the product behind/ahead of
the current num (prefix/suffix), rather than multiplying it all out every time.
For example, take the input array [a, b, c, d]:
- Forwards pass operations: [1, a, ab, abc]
- Backwards pass operations [bcd, cd, d, 1]
- Multiply these together: [bcd, acd, abd, abc]
Args:
nums (List[int]): Input list of numbers
Returns:
List[int]: Array of non-inclusive products
"""
# Initialise accumulators
prefix = 1
suffix = 1
products = [1 for _ in nums]
# Do forwards and backwards operations simultaneously (i.e. one pass)
for i in range(len(nums)):
# Forwards operations: -> [1, a, ab, abc, ...]
products[i] *= prefix
prefix *= nums[i]
# Backwards operations: [..., bcd, cd, d, 1] <-
products[~i] *= suffix
suffix *= nums[~i]
return products | product-of-array-except-self | 🥇 [Python] Prefix and suffix - O(n) | Full explanation ✨ | LloydTao | 0 | 11 | product of array except self | 238 | 0.648 | Medium | 4,486 |
https://leetcode.com/problems/product-of-array-except-self/discuss/2810190/Running-product-oror-Python3 | class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
leftToRight, righToLeft = [1], [1]
for num in nums:
leftToRight.append(leftToRight[-1] * num)
leftToRight = leftToRight[1:]
for num in nums[::-1]:
righToLeft.append(righToLeft[-1] * num)
righToLeft = righToLeft[1:][::-1]
print(righToLeft, leftToRight)
ans = [righToLeft[1]]
for i in range(1, len(nums) - 1):
ans.append(leftToRight[i - 1] * righToLeft[i + 1])
ans.append(leftToRight[-2])
return ans | product-of-array-except-self | Running product || Python3 | joshua_mur | 0 | 2 | product of array except self | 238 | 0.648 | Medium | 4,487 |
https://leetcode.com/problems/product-of-array-except-self/discuss/2796331/Optimized-Solution | class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
res = [1] * (len(nums))
prefix = 1
for i in range(len(nums)):
res[i] = prefix
prefix *= nums[i]
postfix = 1
for i in range(len(nums) - 1, -1, -1):
res[i] *= postfix
postfix *= nums[i]
return res | product-of-array-except-self | Optimized Solution | swaruptech | 0 | 4 | product of array except self | 238 | 0.648 | Medium | 4,488 |
https://leetcode.com/problems/product-of-array-except-self/discuss/2788535/90-efficient-python-3 | class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
# calculate prefix product
prefix = 1
size = len(nums)
output = [1] * size
for i in range(size):
output[i] *= prefix
prefix *= nums[i]
posfix = 1
for j in range(size-1,-1,-1):
output[j] *= posfix
posfix *= nums[j]
return output | product-of-array-except-self | 90 % efficient python 3 | Dawit2119 | 0 | 3 | product of array except self | 238 | 0.648 | Medium | 4,489 |
https://leetcode.com/problems/product-of-array-except-self/discuss/2784101/Allegedly-simpler-to-come-up-with-(top-down) | class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
@cache
def fwd(i):
if i >= len(nums):
return 1
return nums[i] * fwd(i + 1)
@cache
def bck(i):
if i < 0:
return 1
return nums[i] * bck(i - 1)
answer = [0 for _ in nums]
answer[-1] = bck(len(nums) - 1)
for i, n in enumerate(nums):
answer[i] = bck(i - 1) * fwd(i + 1)
return answer | product-of-array-except-self | Allegedly simpler to come up with (top-down) | kqf | 0 | 3 | product of array except self | 238 | 0.648 | Medium | 4,490 |
https://leetcode.com/problems/product-of-array-except-self/discuss/2782825/Python-2-pass-Solution-or-O(n) | class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
n = len(nums)
left_to_right = [0 for _ in range(n)]
left_to_right[0] = nums[0]
right_to_left = [0 for _ in range(n)]
right_to_left[-1] = nums[-1]
for i in range(1, n):
left_to_right[i] = left_to_right[i-1] * nums[i]
for i in range(n - 2, -1, -1):
right_to_left[i] = right_to_left[i + 1] * nums[i]
ans = [0 for _ in range(n)]
ans[0] = right_to_left[1]
ans[-1] = left_to_right[-2]
for i in range(1, n - 1):
ans[i] = left_to_right[i-1] * right_to_left[i + 1]
return ans | product-of-array-except-self | Python 2 pass Solution | O(n) | chingisoinar | 0 | 7 | product of array except self | 238 | 0.648 | Medium | 4,491 |
https://leetcode.com/problems/product-of-array-except-self/discuss/2779345/Simple-Beginner-Friendly-Approach-or-O(N)-or-O(1) | class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
prod = 1
count_of_zero = 0
answer = [0] * len(nums)
for num in nums:
if num == 0:
count_of_zero += 1
else:
prod *= num
if count_of_zero > 1:
return answer
else:
for i in range(len(answer)):
if count_of_zero == 0:
answer[i] = prod // nums[i]
if count_of_zero == 1 and nums[i] == 0:
answer[i] = prod
return answer | product-of-array-except-self | Simple Beginner Friendly Approach | O(N) | O(1) | sonnylaskar | 0 | 4 | product of array except self | 238 | 0.648 | Medium | 4,492 |
https://leetcode.com/problems/product-of-array-except-self/discuss/2760700/title | class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
result=[1]*(len(nums))
prefix=1
for i in range(len(nums)):
result[i]=prefix
prefix*=nums[i]
suffix=1
for i in range(len(nums)-1,-1,-1):
result[i]*=suffix
suffix*=nums[i]
return result | product-of-array-except-self | title | urs_truely_teja | 0 | 2 | product of array except self | 238 | 0.648 | Medium | 4,493 |
https://leetcode.com/problems/product-of-array-except-self/discuss/2749973/Maths-wise-quite-easy | class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
first_lst = [nums[0]]
second_lst = [nums[-1]]
for i in range(1,len(nums)):
product = nums[i]*first_lst[-1]
first_lst.append(product)
second_nums = nums[::-1]
for i in range(1,len(second_nums)):
product = second_nums[i]*second_lst[-1]
second_lst.append(product)
second_lst = second_lst[::-1]
ans = []
for i in range(len(nums)):
if i == 0:
product = 1*second_lst[i+1]
elif i == len(nums)-1:
product = 1* first_lst[i-1]
else:
product = first_lst[i-1]*second_lst[i+1]
ans.append(product)
return ans | product-of-array-except-self | Maths wise quite easy | fellowshiptech | 0 | 7 | product of array except self | 238 | 0.648 | Medium | 4,494 |
https://leetcode.com/problems/product-of-array-except-self/discuss/2736908/Python-Easy-Solve | class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
n = len(nums)
prefix = [1] * n
suffix = [1] * n
curr_sum = 1
for i in range(n):
prefix[i] = curr_sum
curr_sum *= nums[i]
curr_sum = 1
for i in range(n-1 , -1, -1):
suffix[i] = prefix[i] * curr_sum
curr_sum *= nums[i]
return suffix | product-of-array-except-self | Python Easy Solve | anu1rag | 0 | 3 | product of array except self | 238 | 0.648 | Medium | 4,495 |
https://leetcode.com/problems/product-of-array-except-self/discuss/2726267/In-place-rightleft-calculation | class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
res = [1] * len(nums)
prefix = 1
for i in range(len(nums)):
res[i] = prefix
prefix = prefix * nums[i]
postfix = 1
for i in range(len(nums) - 1, -1, -1):
res[i] *= postfix
postfix *= nums[i]
return res | product-of-array-except-self | 💡 In place right/left calculation | meechos | 0 | 5 | product of array except self | 238 | 0.648 | Medium | 4,496 |
https://leetcode.com/problems/product-of-array-except-self/discuss/2712219/python3-oror-easy-oror-O(1)-Approach | class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
res=[1]*len(nums)
prefix=1
for i in range(len(nums)):
res[i]=prefix
prefix*=nums[i]
postfix=1
for i in range(len(nums)-1,-1,-1):
res[i]*=postfix
postfix*=nums[i]
return res | product-of-array-except-self | python3 || easy || O(1) Approach | _soninirav | 0 | 7 | product of array except self | 238 | 0.648 | Medium | 4,497 |
https://leetcode.com/problems/product-of-array-except-self/discuss/2711683/pj | class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
left = [1] * len(nums)
right = [1] * len(nums)
res = [1] * len(nums)
start_with = 1
for i, x in enumerate(nums):
left[i] = start_with
start_with = start_with * x
start_with = 1
for i in range(len(nums) - 1, -1, -1):
right[i] = start_with
start_with = start_with * nums[i]
for i in range(len(nums)):
res[i] = left[i] * right[i]
return res | product-of-array-except-self | pj | prashad12433 | 0 | 2 | product of array except self | 238 | 0.648 | Medium | 4,498 |
https://leetcode.com/problems/product-of-array-except-self/discuss/2695179/Python-solution-O(n)-time-complexity-and-O(1)-space-complexity | class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
res = [1]*len(nums)
prefix = 1
for i in range(len(nums)):
res[i] = prefix
prefix *= nums[i]
postfix = 1
for i in range(len(nums)-1,-1,-1):
res[i] = res[i] * postfix
postfix *= nums[i]
return res | product-of-array-except-self | Python solution O(n) time complexity and O(1) space complexity | Furat | 0 | 13 | product of array except self | 238 | 0.648 | Medium | 4,499 |
Subsets and Splits