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/increasing-decreasing-string/discuss/1685144/O(n)-simple-solution | class Solution:
def sortString(self, s: str) -> str:
char_count = {}
for c in s:
count = char_count.setdefault(c, 0)
char_count[c] = count + 1
uniq_s = sorted(list(char_count.keys()))
uniq_s = uniq_s + uniq_s[::-1]
new_s = []
while len(s) - len(new_s) > 0:
for c in uniq_s:
if char_count[c] > 0:
new_s.append(c)
char_count[c] -= 1
return "".join(new_s) | increasing-decreasing-string | O(n) simple solution | snagsbybalin | 0 | 98 | increasing decreasing string | 1,370 | 0.774 | Easy | 20,600 |
https://leetcode.com/problems/increasing-decreasing-string/discuss/1633829/Python-O(n)-time-O(n)-space-simulation-solution | class Solution:
def sortString(self, s: str) -> str:
count = defaultdict(int)
for c in s:
count[c] += 1
cnt = []
for c in sorted(count.keys()):
cnt.append([c, count[c]])
n = len(cnt)
s = sum(count.values())
i = 0
direc = 1
res = []
while s > 0: # modify cnt[i][1]
if direc == 1:
if i < n-1:
if cnt[i][1] > 0:
res.append(cnt[i][0])
cnt[i][1] -= 1
s -= 1
i += 1
else: # cnt[i][1] == 0
i += 1
else: # i == n-1
if cnt[i][1] > 0:
res.append(cnt[i][0])
cnt[i][1] -= 1
s -= 1
direc = -1
else: # cnt[i][1] == 0
direc = -1
else: # direc == -1
if i > 0:
if cnt[i][1] > 0:
res.append(cnt[i][0])
cnt[i][1] -= 1
s -= 1
i -= 1
else: # cnt[i][1] == 0
i -= 1
else: # i == 0
if cnt[i][1] > 0:
res.append(cnt[i][0])
cnt[i][1] -= 1
s -= 1
direc = 1
else: # cnt[i][1] == 0
direc = 1
return "".join(res) | increasing-decreasing-string | Python O(n) time, O(n) space simulation solution | byuns9334 | 0 | 159 | increasing decreasing string | 1,370 | 0.774 | Easy | 20,601 |
https://leetcode.com/problems/increasing-decreasing-string/discuss/1495920/Python-solution-with-hash-map-and-sorting-(90%2B-in-space-and-time) | class Solution(object):
def sortString(self, s):
"""
:type s: str
:rtype: str
"""
nums = len(s)
set_s = set(s)
# unique elements in sorted order
sorted_keys = sorted([c for c in set_s])
# frequency of each element (again in sorted order)
hash_map = {k: 0 for k in sorted_keys}
for c in s:
hash_map[c] += 1
result = ''
counter = 0
# to check the #number of elements left
while nums > 0:
# picking up the increasing and decreasing order
if counter % 2 == 1:
req = sorted_keys[::-1]
else:
req = sorted_keys
# reducing the frequency of each element
for k in req:
if hash_map[k] !=0:
result += k
hash_map[k] -= 1
nums -= 1
# didn't like this but we need to find a way to break this loop
if nums <= 0:
break
counter += 1
return result | increasing-decreasing-string | Python solution with hash map and sorting (90+ in space and time) | talos1904 | 0 | 118 | increasing decreasing string | 1,370 | 0.774 | Easy | 20,602 |
https://leetcode.com/problems/increasing-decreasing-string/discuss/1158067/Python-wo-counter | class Solution:
def sortString(self, s: str) -> str:
result = ''
dct = {}
for i in s:
dct[i] = dct.get(i, 0) + 1
reverse = False
while dct:
for i in dict(sorted(dct.items(), reverse=reverse)):
dct[i] -= 1
result += i
if not dct[i]:
del dct[i]
reverse = not reverse
return result | increasing-decreasing-string | [Python] w/o counter | cruim | 0 | 115 | increasing decreasing string | 1,370 | 0.774 | Easy | 20,603 |
https://leetcode.com/problems/increasing-decreasing-string/discuss/1027910/Python3-easy-to-understand-solution | class Solution:
def sortString(self, s: str) -> str:
string = ''
d = dict()
for i in s:
d[i] = d.get(i,0) + 1
while sum(d.values()) != 0:
for i in range(97,123):
if chr(i) in d and d[chr(i)] > 0:
string += chr(i)
d[chr(i)] -= 1
for i in range(122,96,-1):
if chr(i) in d and d[chr(i)] > 0:
string += chr(i)
d[chr(i)] -= 1
return string | increasing-decreasing-string | Python3 easy to understand solution | EklavyaJoshi | 0 | 178 | increasing decreasing string | 1,370 | 0.774 | Easy | 20,604 |
https://leetcode.com/problems/increasing-decreasing-string/discuss/707917/simple-of-simple-(counter) | class Solution:
def sortString(self, s: str) -> str:
l = len(s)
from collections import Counter
cnt = Counter(s)
now = 'a'
direction = 1
result = ""
while l > 0:
l -= 1
while cnt[now] == 0:
now = chr(ord(now) + direction)
direction = self.getDirection(now, direction)
result += now
cnt[now] -= 1
now = chr(ord(now) + direction)
direction = self.getDirection(now, direction)
return result
def getDirection(self, now, d):
if now > 'z':
d = -1
if now < 'a':
d = 1
return d | increasing-decreasing-string | simple of simple (counter) | seunggabi | 0 | 98 | increasing decreasing string | 1,370 | 0.774 | Easy | 20,605 |
https://leetcode.com/problems/increasing-decreasing-string/discuss/531944/Python3-a-7-line-solution | class Solution:
def sortString(self, s: str) -> str:
count = [0]*26
for c in s: count[ord(c)-97] += 1
ans, k = [], -1
while len(ans) < len(s):
ans.append("".join(chr(i+97) for i, c in enumerate(count) if c != 0)[::(k:=-k)])
count = [max(0, c-1) for c in count]
return "".join(ans) | increasing-decreasing-string | [Python3] a 7-line solution | ye15 | 0 | 134 | increasing decreasing string | 1,370 | 0.774 | Easy | 20,606 |
https://leetcode.com/problems/increasing-decreasing-string/discuss/1742958/Python-dollarolution | class Solution:
def sortString(self, s: str) -> str:
p = sorted(s)
d, v = {}, ''
# Count the number of each character in the string
for i in p:
if i not in d:
d[i] = 1
else:
d[i] += 1
# Run loops to add to the new string
while not all(value == 0 for value in d.values()):
for i in d:
if d[i] > 0:
v += i
d[i] -= 1
for i in sorted(d,reverse=True):
if d[i] > 0:
v += i
d[i] -= 1
return v | increasing-decreasing-string | Python $olution | AakRay | -2 | 195 | increasing decreasing string | 1,370 | 0.774 | Easy | 20,607 |
https://leetcode.com/problems/increasing-decreasing-string/discuss/1075784/Pythonic-simple-approach-using-sort-and-counter | class Solution:
def sortString(self, s: str) -> str:
count, res, flag = collections.Counter(sorted(s)), [], True
while count:
temp = list(count)
res += temp if flag else reversed(temp)
count -= collections.Counter(temp)
flag ^= True
return "".join(res) | increasing-decreasing-string | Pythonic, simple approach using sort & counter | Onlycst | -3 | 225 | increasing decreasing string | 1,370 | 0.774 | Easy | 20,608 |
https://leetcode.com/problems/find-the-longest-substring-containing-vowels-in-even-counts/discuss/1125562/Python3-bitmask | class Solution:
def findTheLongestSubstring(self, s: str) -> int:
ans = mask = 0
seen = {0: -1}
for i, c in enumerate(s):
if c in "aeiou":
mask ^= 1 << ("aeiou".find(c))
if mask in seen: ans = max(ans, i - seen[mask])
seen.setdefault(mask, i)
return ans | find-the-longest-substring-containing-vowels-in-even-counts | [Python3] bitmask | ye15 | 4 | 148 | find the longest substring containing vowels in even counts | 1,371 | 0.629 | Medium | 20,609 |
https://leetcode.com/problems/find-the-longest-substring-containing-vowels-in-even-counts/discuss/1428517/Python-3-or-Hash-Table-Bitmask-Tuple-O(N)-two-implementations-or-Explanation | class Solution:
def findTheLongestSubstring(self, s: str) -> int:
d = collections.defaultdict(lambda: sys.maxsize)
cur = (0, 0, 0, 0, 0) # current mask
ans = d[cur] = -1 # initialize result
vowel = {'a': 0, 'e': 1, 'i': 2, 'o': 3, 'u': 4} # index mapping
for i, c in enumerate(s):
if c in vowel: # if `c` is a vowel, update the `cur` (mask)
idx = vowel[c]
cur = cur[:idx] + (1-cur[idx],) + cur[idx+1:]
if d[cur] == sys.maxsize:
d[cur] = i # if mask is never recorded, recorded it since it's the lowest index of this current mask
ans = max(ans, i - d[cur]) # update `ans` by calculating `i - lower_idx_of_mask`
return ans | find-the-longest-substring-containing-vowels-in-even-counts | Python 3 | Hash Table, Bitmask, Tuple, O(N) two implementations | Explanation | idontknoooo | 3 | 253 | find the longest substring containing vowels in even counts | 1,371 | 0.629 | Medium | 20,610 |
https://leetcode.com/problems/find-the-longest-substring-containing-vowels-in-even-counts/discuss/1428517/Python-3-or-Hash-Table-Bitmask-Tuple-O(N)-two-implementations-or-Explanation | class Solution:
def findTheLongestSubstring(self, s: str) -> int:
d = {0: -1}
ans = cur = 0
vowel = {'a': 0, 'e': 1, 'i': 2, 'o': 3, 'u': 4}
for i, c in enumerate(s):
if c in vowel:
cur ^= 1 << vowel[c]
if cur not in d:
d[cur] = i
ans = max(ans, i - d[cur])
return ans | find-the-longest-substring-containing-vowels-in-even-counts | Python 3 | Hash Table, Bitmask, Tuple, O(N) two implementations | Explanation | idontknoooo | 3 | 253 | find the longest substring containing vowels in even counts | 1,371 | 0.629 | Medium | 20,611 |
https://leetcode.com/problems/find-the-longest-substring-containing-vowels-in-even-counts/discuss/1407696/Simple-Python-commented-line-by-line | class Solution:
def findTheLongestSubstring(self, s: str) -> int:
# define a dict for number of left shifts for each vowel
vowel2shift = {'a': 4, 'e': 3, 'i': 2, 'o': 1, 'u': 0}
# define a dict for the index of first appearance of a specific parity
parity2firstIdx = {0: -1}
# parity initialized to 00000, each vowel appear 0 time which is even
ret = parity = 0
# iterate through each letter of s
for i, letter in enumerate(s):
# if letter is a vowel, swap/toggle its corresponding bit
if letter in vowel2shift:
parity ^= 1 << vowel2shift[letter]
# if we've seen this particular parity before, it means each vowel
# appeared an even number of time between now and then
# odd + even = odd
# even + even = even
if parity in parity2firstIdx:
ret = max(ret, i-parity2firstIdx[parity])
# otherwise, record its index of first appearance
else:
parity2firstIdx[parity] = i
return ret | find-the-longest-substring-containing-vowels-in-even-counts | Simple Python commented line by line | Charlesl0129 | 2 | 223 | find the longest substring containing vowels in even counts | 1,371 | 0.629 | Medium | 20,612 |
https://leetcode.com/problems/find-the-longest-substring-containing-vowels-in-even-counts/discuss/1530785/Python-O(N)-Time-One-Pass-Solution | class Solution:
def findTheLongestSubstring(self, s: str) -> int:
indices = {a:i for i, a in enumerate('aeiou')}
lefts = {0:-1}
res = status = 0
for right, a in enumerate(s):
if a in indices:
status ^= 1 << indices[a]
if status not in lefts:
lefts[status] = right
res = max(res, right - lefts[status])
return res | find-the-longest-substring-containing-vowels-in-even-counts | [Python] O(N) Time One Pass Solution | licpotis | 1 | 216 | find the longest substring containing vowels in even counts | 1,371 | 0.629 | Medium | 20,613 |
https://leetcode.com/problems/find-the-longest-substring-containing-vowels-in-even-counts/discuss/1500440/Python3-O(n)-Solution-with-Explanations | class Solution:
def findTheLongestSubstring(self, s: str) -> int:
# one (int) variable to store vowel-related information
# e.g., 00000 (0)
# if a occurs, 00000 ^ 00001 = 00001 (1)
# if i occurs, 00001 ^ 00100 = 00101 (5)
# if a occurs, 00101 ^ 00001 = 00100 (4)
# ---------------------------------------------------------
# if at index 1, we have state 00101 (5)
# and at index 11, we have state 00101 (5) again,
# then we can claim this sub-array (from index 1 to 11) has even vowels
# with the evidence that 00101 ^ 00101 = 00000
# ---------------------------------------------------------
# Rationale
# 1. We one-pass the array & record the state at each element
# 2. If the current state has been recorded before, we compare to the leftmost index
# with the same state
vowels = {'a': 1, 'e': 2, 'i': 4, 'o': 8, 'u': 16}
d = {0: -1} # d: dictoray to record the leftmost indices of states
state, ans = 0, 0
for i, c in enumerate(s): # c: char
if c in vowels:
state ^= vowels[c]
# record the leftmost index with state v
if not (state in d):
d[state] = i
ans = max(ans, i-d[state])
return ans | find-the-longest-substring-containing-vowels-in-even-counts | Python3 - O(n) Solution with Explanations | tkuo-tkuo | 0 | 178 | find the longest substring containing vowels in even counts | 1,371 | 0.629 | Medium | 20,614 |
https://leetcode.com/problems/longest-zigzag-path-in-a-binary-tree/discuss/2559539/Python3-Iterative-DFS-Using-Stack-99-time-91-space-O(N)-time-O(N)-space | class Solution:
def longestZigZag(self, root: Optional[TreeNode]) -> int:
LEFT = 0
RIGHT = 1
stack = []
if root.left:
stack.append((root.left, LEFT, 1))
if root.right:
stack.append((root.right, RIGHT, 1))
longest = 0
while stack:
node, direction, count = stack.pop()
longest = max(longest, count)
if direction == LEFT:
if node.left:
stack.append((node.left, LEFT, 1))
if node.right:
stack.append((node.right, RIGHT, count+1))
else:
if node.right:
stack.append((node.right, RIGHT, 1))
if node.left:
stack.append((node.left, LEFT, count+1))
return longest | longest-zigzag-path-in-a-binary-tree | [Python3] Iterative DFS Using Stack - 99% time 91% space, - O(N) time O(N) space | rt500 | 0 | 35 | longest zigzag path in a binary tree | 1,372 | 0.598 | Medium | 20,615 |
https://leetcode.com/problems/longest-zigzag-path-in-a-binary-tree/discuss/2550193/Python-Concise-but-understandable-DFS | class Solution:
def longestZigZag(self, root: Optional[TreeNode]) -> int:
# initialize a instance variable in order to
# save the maximum path length
self.max_path = 0
# make the DFS
self.dfs(root, -1, 0)
# return path length
return self.max_path
def dfs(self, node, prev_direction, path_length):
# end condition for dfs
if node is None:
return
# add current length to max path
# print(path_length)
self.max_path = max(path_length, self.max_path)
if prev_direction == 1:
self.dfs(node.left, 1, 1)
self.dfs(node.right, 2, path_length+1)
else:
self.dfs(node.left, 1, path_length+1)
self.dfs(node.right, 2, 1) | longest-zigzag-path-in-a-binary-tree | [Python] - Concise but understandable DFS | Lucew | 0 | 24 | longest zigzag path in a binary tree | 1,372 | 0.598 | Medium | 20,616 |
https://leetcode.com/problems/longest-zigzag-path-in-a-binary-tree/discuss/2364847/python3 | class Solution:
def longestZigZag(self, root: Optional[TreeNode]) -> int:
if not root: return 0
self.res=0
def find(root,count,a):
if root:
if a=='r':
if root.left:
find(root.left,count+1,'l')
if root.right:
find(root.right,1,'r')
else:
if root.left:
find(root.left,1,'l')
if root.right:
find(root.right,count+1,'r')
self.res=max(self.res,count)
if root.right:find(root.right,1,'r');
if root.left:find(root.left,1,'l');
return self.res | longest-zigzag-path-in-a-binary-tree | python3 | deadlogic | 0 | 16 | longest zigzag path in a binary tree | 1,372 | 0.598 | Medium | 20,617 |
https://leetcode.com/problems/longest-zigzag-path-in-a-binary-tree/discuss/2190098/python-3-or-simple-dfs | class Solution:
def longestZigZag(self, root: Optional[TreeNode]) -> int:
self.res = 0
def helper(root):
if root is None:
return -1, -1
leftRight = helper(root.left)[1] + 1
rightLeft = helper(root.right)[0] + 1
self.res = max(self.res, leftRight, rightLeft)
return leftRight, rightLeft
helper(root)
return self.res | longest-zigzag-path-in-a-binary-tree | python 3 | simple dfs | dereky4 | 0 | 81 | longest zigzag path in a binary tree | 1,372 | 0.598 | Medium | 20,618 |
https://leetcode.com/problems/longest-zigzag-path-in-a-binary-tree/discuss/1790537/Python-DFS-check-left-and-right | class Solution:
def longestZigZag(self, root: Optional[TreeNode]) -> int:
# Time : O(n)
longest = 0
def traverse(node, next_direction, traveled_distance):
nonlocal longest
longest = max(longest, traveled_distance)
if node.right:
if next_direction == "right":
traverse(node.right, "left", traveled_distance + 1)
else:
# If not supposed to go right but still want to, start over again
traverse(node.right, "left", 1)
if node.left:
if next_direction == "left":
traverse(node.left, "right", traveled_distance + 1)
else:
traverse(node.left, "right", 1)
if root.left:
traverse(root.left, "right", 1)
if root.right:
traverse(root.right, "left", 1)
if not root.left and not root.right:
return 0
return longest | longest-zigzag-path-in-a-binary-tree | Python DFS check left and right | hitpoint6 | 0 | 38 | longest zigzag path in a binary tree | 1,372 | 0.598 | Medium | 20,619 |
https://leetcode.com/problems/longest-zigzag-path-in-a-binary-tree/discuss/1531022/Well-Coded-oror-92-faster-oror-Easy-to-understand | class Solution:
def longestZigZag(self, root: Optional[TreeNode]) -> int:
self.res = 0
def zigzag(root):
if root is None:
return (0,0)
l = zigzag(root.left)
r = zigzag(root.right)
local = (l[1]+1,r[0]+1)
self.res = max(self.res,max(local))
return local
zigzag(root)
return self.res-1 | longest-zigzag-path-in-a-binary-tree | 📌📌 Well-Coded || 92% faster || Easy-to-understand 🐍 | abhi9Rai | 0 | 105 | longest zigzag path in a binary tree | 1,372 | 0.598 | Medium | 20,620 |
https://leetcode.com/problems/longest-zigzag-path-in-a-binary-tree/discuss/1480006/Python-Clean-Postorder-DFS | class Solution:
def longestZigZag(self, root: Optional[TreeNode]) -> int:
def postorder(node = root):
nonlocal longest
if not node:
return (0, 0)
L, R = postorder(node.left), postorder(node.right)
M0, M1 = max(L[1]+1, 1), max(R[0]+1, 1)
longest = max(M0, M1, longest)
return (M0, M1)
longest = 0
postorder()
return longest-1 | longest-zigzag-path-in-a-binary-tree | [Python] Clean Postorder DFS | soma28 | 0 | 120 | longest zigzag path in a binary tree | 1,372 | 0.598 | Medium | 20,621 |
https://leetcode.com/problems/longest-zigzag-path-in-a-binary-tree/discuss/532041/Python3-iteratively-traverse-the-tree-(dfs) | class Solution:
def longestZigZag(self, root: TreeNode) -> int:
ans = 0
stack = [(root, 0, None)] #(node, length, child)
while stack:
node, n, left = stack.pop()
if node:
ans = max(ans, n)
stack.append((node.left, 1 if left else n+1, 1))
stack.append((node.right, n+1 if left else 1, 0))
return ans | longest-zigzag-path-in-a-binary-tree | [Python3] iteratively traverse the tree (dfs) | ye15 | 0 | 45 | longest zigzag path in a binary tree | 1,372 | 0.598 | Medium | 20,622 |
https://leetcode.com/problems/longest-zigzag-path-in-a-binary-tree/discuss/532041/Python3-iteratively-traverse-the-tree-(dfs) | class Solution:
def longestZigZag(self, root: TreeNode) -> int:
def fn(node):
"""Return #nodes on longest ZigZag path starting at given node"""
nonlocal ans
if node is None: return (0, 0)
(_, r1), (l2, _) = fn(node.left), fn(node.right)
ans = max(ans, r1+1, l2+1)
return (r1+1, l2+1)
ans = 0
fn(root)
return ans-1 | longest-zigzag-path-in-a-binary-tree | [Python3] iteratively traverse the tree (dfs) | ye15 | 0 | 45 | longest zigzag path in a binary tree | 1,372 | 0.598 | Medium | 20,623 |
https://leetcode.com/problems/maximum-sum-bst-in-binary-tree/discuss/1377976/Python-O(n)-short-readable-solution | class Solution:
def maxSumBST(self, root: TreeNode) -> int:
tot = -math.inf
def dfs(node):
nonlocal tot
if not node:
return 0, math.inf, -math.inf
l_res, l_min, l_max = dfs(node.left)
r_res, r_min, r_max = dfs(node.right)
# if maintains BST property
if l_max<node.val<r_min:
res = node.val + l_res + r_res
tot = max(tot, res)
# keep track the min and max values of the subtree
return res, min(l_min,node.val), max(r_max, node.val)
else:
return 0, -math.inf, math.inf
return max(dfs(root)[0], tot) | maximum-sum-bst-in-binary-tree | Python O(n), short readable solution | arsamigullin | 1 | 170 | maximum sum bst in binary tree | 1,373 | 0.392 | Hard | 20,624 |
https://leetcode.com/problems/maximum-sum-bst-in-binary-tree/discuss/1112936/Python3-post-order-dfs | class Solution:
def maxSumBST(self, root: TreeNode) -> int:
def fn(node):
"""Collect info while traversing the tree in post-order."""
if not node: return True, inf, -inf, 0, 0 # bst flag | min | max | sum
ltf, lmn, lmx, lsm, lval = fn(node.left)
rtf, rmn, rmx, rsm, rval = fn(node.right)
lmn = min(lmn, node.val)
rmx = max(rmx, node.val)
sm = lsm + rsm + node.val
if ltf and rtf and lmx < node.val < rmn:
return True, lmn, rmx, sm, max(lval, rval, sm)
return False, lmn, rmx, sm, max(lval, rval)
return fn(root)[-1] | maximum-sum-bst-in-binary-tree | [Python3] post-order dfs | ye15 | 1 | 95 | maximum sum bst in binary tree | 1,373 | 0.392 | Hard | 20,625 |
https://leetcode.com/problems/maximum-sum-bst-in-binary-tree/discuss/2741962/Deisgned-a-class-for-NodeVal | class Solution:
def maxSumBST(self, root: Optional[TreeNode]) -> int:
self.val = 0
self.BST(root).summ
return self.val
def BST(self, root):
if not root:
return NodeValue(-math.inf, math.inf, 0)
l = self.BST(root.left)
r = self.BST(root.right)
if l.maxNode < root.val and r.minNode > root.val:
self.val = max(self.val, root.val + l.summ + r.summ)
return NodeValue(max(r.maxNode, root.val), min(l.minNode, root.val), root.val + l.summ + r.summ)
return NodeValue(math.inf, -math.inf, 0)
class NodeValue:
def __init__(self, maxNode, minNode, summ):
self.maxNode = maxNode
self.minNode = minNode
self.summ = summ | maximum-sum-bst-in-binary-tree | Deisgned a class for NodeVal | hacktheirlives | 0 | 3 | maximum sum bst in binary tree | 1,373 | 0.392 | Hard | 20,626 |
https://leetcode.com/problems/maximum-sum-bst-in-binary-tree/discuss/2564815/Short-Python-Implementation-with-divide-and-conquer-in-O(n) | class Solution:
def find(self, node):
if node is None:
return 0, 0, inf, -inf
l_best, l_sum, l_min, l_max = self.find(node.left)
r_best, r_sum, r_min, r_max = self.find(node.right)
l_min, r_max = min(node.val, l_min), max(node.val, r_max)
if l_sum != -inf and r_sum != -inf and l_max < node.val < r_min:
return max(l_best, r_best, l_sum + r_sum + node.val), l_sum + r_sum + node.val, l_min, r_max
else:
return max(l_best, r_best), -inf, l_min, r_max
def maxSumBST(self, root: Optional[TreeNode]) -> int:
return self.find(root)[0] | maximum-sum-bst-in-binary-tree | Short Python Implementation with divide and conquer in O(n) | metaphysicalist | 0 | 18 | maximum sum bst in binary tree | 1,373 | 0.392 | Hard | 20,627 |
https://leetcode.com/problems/maximum-sum-bst-in-binary-tree/discuss/2053485/Python-or-DFS-or-O(n)-time-O(1)-space | class Solution:
def maxSumBST(self, root: Optional[TreeNode]) -> int:
max_sum = 0
def traverse(root):
nonlocal max_sum
if root is None:
return 1, inf, -inf, 0
is_l, min_l, max_l, sum_l = traverse(root.left)
is_r, min_r, max_r, sum_r = traverse(root.right)
if is_l and is_r and max_l < root.val < min_r:
cur = sum_l + sum_r + root.val
max_sum = max(cur, max_sum)
min_l = min(min_l, root.val)
max_r = max(max_r, root.val)
return 1, min_l, max_r, cur
else:
return 0, 0, 0, 0
traverse(root)
return max_sum | maximum-sum-bst-in-binary-tree | Python | DFS | O(n) time O(1) space | Kiyomi_ | 0 | 55 | maximum sum bst in binary tree | 1,373 | 0.392 | Hard | 20,628 |
https://leetcode.com/problems/maximum-sum-bst-in-binary-tree/discuss/531976/Python-DFS-Solution-Easy-understand | class Solution:
def maxSumBST(self, root: TreeNode):
self.max = 0
def dfs(root):
if not root : return ("N" , 0)
l_v , l_acc = dfs(root.left)
r_v , r_acc = dfs(root.right)
if (l_v == "N" and r_v == "N") or (l_v == "N" and isinstance(r_v, int) and r_v > root.val ) or (isinstance(l_v, int) and l_v < root.val and r_v == "N" ) or isinstance(l_v, int) and isinstance(r_v, int) and l_v < root.val < r_v:
now_acc = l_acc + r_acc + root.val
self.max = max(self.max , now_acc)
return (root.val ,now_acc )
else:
return (root.val , -sys.maxsize )
dfs(root)
return self.max | maximum-sum-bst-in-binary-tree | [Python] DFS Solution , Easy understand | mike840609 | 0 | 56 | maximum sum bst in binary tree | 1,373 | 0.392 | Hard | 20,629 |
https://leetcode.com/problems/generate-a-string-with-characters-that-have-odd-counts/discuss/1232027/Easy-code-in-python-with-explanation. | class Solution:
def generateTheString(self, n: int) -> str:
a="a"
b="b"
if n%2==0:
return (((n-1)*a)+b)
return (n*a) | generate-a-string-with-characters-that-have-odd-counts | Easy code in python with explanation. | souravsingpardeshi | 2 | 183 | generate a string with characters that have odd counts | 1,374 | 0.776 | Easy | 20,630 |
https://leetcode.com/problems/generate-a-string-with-characters-that-have-odd-counts/discuss/1797988/Python-3-or-one-line-solution | class Solution:
def generateTheString(self, n: int) -> str:
return "a"*n if n%2 == 1 else "a"*(n-1)+"b" | generate-a-string-with-characters-that-have-odd-counts | ✔Python 3 | one line solution | Coding_Tan3 | 1 | 66 | generate a string with characters that have odd counts | 1,374 | 0.776 | Easy | 20,631 |
https://leetcode.com/problems/generate-a-string-with-characters-that-have-odd-counts/discuss/1219248/Python3-or-One-liner-or-String | class Solution:
def generateTheString(self, n: int) -> str:
# we can use any of the 2 alphabets of our choice
return "v" * n if n % 2 else "v" * (n-1) + "m" | generate-a-string-with-characters-that-have-odd-counts | Python3 | One-liner | String | codemonk1307 | 1 | 49 | generate a string with characters that have odd counts | 1,374 | 0.776 | Easy | 20,632 |
https://leetcode.com/problems/generate-a-string-with-characters-that-have-odd-counts/discuss/1166022/Python3-Simple-Solution | class Solution:
def generateTheString(self, n: int) -> str:
if(n % 2 == 0): return 'a' + 'b' * (n - 1)
return 'a' * n | generate-a-string-with-characters-that-have-odd-counts | [Python3] Simple Solution | VoidCupboard | 1 | 55 | generate a string with characters that have odd counts | 1,374 | 0.776 | Easy | 20,633 |
https://leetcode.com/problems/generate-a-string-with-characters-that-have-odd-counts/discuss/669204/Python-simple-solution | class Solution:
def generateTheString(self, n: int) -> str:
if n%2 == 0 and (n//2)%2 != 0:
return 'a'*(n//2)+'b'*(n//2)
elif n%2 == 0 and (n//2)%2 == 0:
return 'a'*((n//2)+1)+'b'*((n//2)-1)
else:
return 'a'*n | generate-a-string-with-characters-that-have-odd-counts | Python simple solution | aj_to_rescue | 1 | 89 | generate a string with characters that have odd counts | 1,374 | 0.776 | Easy | 20,634 |
https://leetcode.com/problems/generate-a-string-with-characters-that-have-odd-counts/discuss/2770984/Python-or-LeetCode-or-1374.-Generate-a-String-With-Characters-That-Have-Odd-Counts | class Solution:
def generateTheString(self, n: int) -> str:
if n % 2:
return "a" * n
else:
return "a" * (n - 1) + "b" | generate-a-string-with-characters-that-have-odd-counts | Python | LeetCode | 1374. Generate a String With Characters That Have Odd Counts | UzbekDasturchisiman | 0 | 6 | generate a string with characters that have odd counts | 1,374 | 0.776 | Easy | 20,635 |
https://leetcode.com/problems/generate-a-string-with-characters-that-have-odd-counts/discuss/2770984/Python-or-LeetCode-or-1374.-Generate-a-String-With-Characters-That-Have-Odd-Counts | class Solution:
def generateTheString(self, n: int) -> str:
return "a" * n if n % 2 else "a" * (n - 1) + "b" | generate-a-string-with-characters-that-have-odd-counts | Python | LeetCode | 1374. Generate a String With Characters That Have Odd Counts | UzbekDasturchisiman | 0 | 6 | generate a string with characters that have odd counts | 1,374 | 0.776 | Easy | 20,636 |
https://leetcode.com/problems/generate-a-string-with-characters-that-have-odd-counts/discuss/2770984/Python-or-LeetCode-or-1374.-Generate-a-String-With-Characters-That-Have-Odd-Counts | class Solution:
def generateTheString(self, n: int) -> str:
return 'b' + 'ab'[n & 1] * (n - 1) | generate-a-string-with-characters-that-have-odd-counts | Python | LeetCode | 1374. Generate a String With Characters That Have Odd Counts | UzbekDasturchisiman | 0 | 6 | generate a string with characters that have odd counts | 1,374 | 0.776 | Easy | 20,637 |
https://leetcode.com/problems/generate-a-string-with-characters-that-have-odd-counts/discuss/2770984/Python-or-LeetCode-or-1374.-Generate-a-String-With-Characters-That-Have-Odd-Counts | class Solution:
def generateTheString(self, n: int) -> str:
s = ""
g = "abcdefghijklmnopqrs"
i = 0
while not (n == 1):
if n % 2 == 0:
# n juft son va qolqiq 0 ga teng.
if (n // 2) % 2 == 0:
# juft son
s += ((n // 2) + 1)*g[i]
i += 1
n = (n // 2) - 1
else:
# toq son
s += (n // 2)*g[i]
i += 1
n = n // 2
else:
# n toq son va qoldiq 1 ga teng.
if (n // 2) % 2 == 0:
# juft son
s += ((n // 2) + 1)*g[i]
i += 1
n = (n // 2)
else:
# toq son
s += (n // 2)*g[i]
i += 1
n = (n // 2) + 1
s += 1*g[i]
return s | generate-a-string-with-characters-that-have-odd-counts | Python | LeetCode | 1374. Generate a String With Characters That Have Odd Counts | UzbekDasturchisiman | 0 | 6 | generate a string with characters that have odd counts | 1,374 | 0.776 | Easy | 20,638 |
https://leetcode.com/problems/generate-a-string-with-characters-that-have-odd-counts/discuss/2449347/1-Line-Fastest-Python-Code-(-Simple-) | class Solution:
def generateTheString(self, n: int) -> str:
return "a"*(n-1)+"b" if n%2 == 0 else "a"*n | generate-a-string-with-characters-that-have-odd-counts | 1 Line Fastest Python Code ( Simple ) | SouravSingh49 | 0 | 38 | generate a string with characters that have odd counts | 1,374 | 0.776 | Easy | 20,639 |
https://leetcode.com/problems/generate-a-string-with-characters-that-have-odd-counts/discuss/2111289/Python-simple-solution | class Solution:
def generateTheString(self, n: int) -> str:
return 'a'*(n-1) + 'b' if n % 2 == 0 else 'a' if n == 1 else 'a'*(n-2) + 'b' + 'c' | generate-a-string-with-characters-that-have-odd-counts | Python simple solution | StikS32 | 0 | 43 | generate a string with characters that have odd counts | 1,374 | 0.776 | Easy | 20,640 |
https://leetcode.com/problems/generate-a-string-with-characters-that-have-odd-counts/discuss/1933666/Python-One-Liner-%2B-Explanation-%2B-Pattern | class Solution:
def generateTheString(self, n):
return "a" * n if n % 2 else "a"*(n-1) + "b" | generate-a-string-with-characters-that-have-odd-counts | Python - One Liner + Explanation + Pattern | domthedeveloper | 0 | 67 | generate a string with characters that have odd counts | 1,374 | 0.776 | Easy | 20,641 |
https://leetcode.com/problems/generate-a-string-with-characters-that-have-odd-counts/discuss/1884255/Python-easy-solution | class Solution:
def generateTheString(self, n: int) -> str:
if n % 2 == 0:
return "x" + "y" * (n - 1)
return "x" * n | generate-a-string-with-characters-that-have-odd-counts | Python easy solution | alishak1999 | 0 | 77 | generate a string with characters that have odd counts | 1,374 | 0.776 | Easy | 20,642 |
https://leetcode.com/problems/generate-a-string-with-characters-that-have-odd-counts/discuss/1814337/python-3-one-liner | class Solution:
def generateTheString(self, n: int) -> str:
return 'a' * (n - 1) + ('a' if n % 2 else 'b') | generate-a-string-with-characters-that-have-odd-counts | python 3 one liner | dereky4 | 0 | 48 | generate a string with characters that have odd counts | 1,374 | 0.776 | Easy | 20,643 |
https://leetcode.com/problems/generate-a-string-with-characters-that-have-odd-counts/discuss/1789832/1-Line-Python-Solution-oror-70-Faster-(36ms)-oror-Memory-Less-than-80 | class Solution:
def generateTheString(self, n: int) -> str:
return 'a'*(n-1)+'b' if n%2==0 else 'a'*n | generate-a-string-with-characters-that-have-odd-counts | 1-Line Python Solution || 70% Faster (36ms) || Memory Less than 80% | Taha-C | 0 | 46 | generate a string with characters that have odd counts | 1,374 | 0.776 | Easy | 20,644 |
https://leetcode.com/problems/generate-a-string-with-characters-that-have-odd-counts/discuss/1742973/Python-dollarolution | class Solution:
def generateTheString(self, n: int) -> str:
if n%2==0:
return ('a'*(n-1) + 'b')
else:
return ('a'*n) | generate-a-string-with-characters-that-have-odd-counts | Python $olution | AakRay | 0 | 63 | generate a string with characters that have odd counts | 1,374 | 0.776 | Easy | 20,645 |
https://leetcode.com/problems/generate-a-string-with-characters-that-have-odd-counts/discuss/1560510/faster-than-~97 | class Solution:
def generateTheString(self, n: int) -> str:
a,b,s = 'a','b',""
if n%2==0:
s += a
s += (b*(n-1))
else:
s += a*n
return s | generate-a-string-with-characters-that-have-odd-counts | faster than ~97% | anandanshul001 | 0 | 65 | generate a string with characters that have odd counts | 1,374 | 0.776 | Easy | 20,646 |
https://leetcode.com/problems/generate-a-string-with-characters-that-have-odd-counts/discuss/1534560/Python-one-line | class Solution:
def generateTheString(self, n: int) -> str:
if n %2 == 0:
return "a" * (n-1) + "b"
else:
return "a"*n | generate-a-string-with-characters-that-have-odd-counts | Python one line | byuns9334 | 0 | 45 | generate a string with characters that have odd counts | 1,374 | 0.776 | Easy | 20,647 |
https://leetcode.com/problems/generate-a-string-with-characters-that-have-odd-counts/discuss/1028785/Python3-solution | class Solution:
def generateTheString(self, n: int) -> str:
if n%2==0:
return 'a' * (n-1) + 'b'
else:
return 'a' * n | generate-a-string-with-characters-that-have-odd-counts | Python3 solution | EklavyaJoshi | 0 | 45 | generate a string with characters that have odd counts | 1,374 | 0.776 | Easy | 20,648 |
https://leetcode.com/problems/generate-a-string-with-characters-that-have-odd-counts/discuss/532800/Python3%3A-Straight-forward-with-inline-comments | class Solution:
def generateTheString(self, n: int) -> str:
if n == 0:
return ''
# If odd just return that number 'a'
if n % 2 != 0:
return 'a' * n
# If even subtract one as 'a' with one 'b'
else:
first = n - 1
first_char = 'a' * first
return first_char + 'b' | generate-a-string-with-characters-that-have-odd-counts | Python3: Straight forward with inline comments | dentedghost | 0 | 106 | generate a string with characters that have odd counts | 1,374 | 0.776 | Easy | 20,649 |
https://leetcode.com/problems/generate-a-string-with-characters-that-have-odd-counts/discuss/532772/Python-O(n)-by-list-and-join.-90%2B-w-Comment | class Solution:
def generateTheString(self, n: int) -> str:
result = ['a'] * n
if n & 1 == 0:
# handle for even legnth
result[-1] = 'b'
return ''.join(result) | generate-a-string-with-characters-that-have-odd-counts | Python O(n) by list and join. 90%+ [w/ Comment] | brianchiang_tw | 0 | 189 | generate a string with characters that have odd counts | 1,374 | 0.776 | Easy | 20,650 |
https://leetcode.com/problems/generate-a-string-with-characters-that-have-odd-counts/discuss/532637/Python3-simple-one-line | class Solution:
def generateTheString(self, n: int) -> str:
return "a"*n if n & 1 else "a"*(n-1) + "b" | generate-a-string-with-characters-that-have-odd-counts | [Python3] simple one-line | ye15 | 0 | 66 | generate a string with characters that have odd counts | 1,374 | 0.776 | Easy | 20,651 |
https://leetcode.com/problems/number-of-times-binary-string-is-prefix-aligned/discuss/1330283/Python3-solution-O(n)-time-and-O(1)-space-complexity | class Solution:
def numTimesAllBlue(self, light: List[int]) -> int:
max = count = 0
for i in range(len(light)):
if max < light[i]:
max = light[i]
if max == i + 1:
count += 1
return count | number-of-times-binary-string-is-prefix-aligned | Python3 solution O(n) time and O(1) space complexity | EklavyaJoshi | 4 | 312 | number of times binary string is prefix aligned | 1,375 | 0.659 | Medium | 20,652 |
https://leetcode.com/problems/number-of-times-binary-string-is-prefix-aligned/discuss/532546/Python-O(n)%3A-compare-current-sum-with-supposed-sum | class Solution:
def numTimesAllBlue(self, light: List[int]) -> int:
res = 0
curr_sum = 0
object_sum = 0
for i, bulb in enumerate(light):
object_sum += i + 1
curr_sum += bulb
if curr_sum == object_sum:
res += 1
return res | number-of-times-binary-string-is-prefix-aligned | Python O(n): compare current sum with supposed sum | MockCode | 3 | 271 | number of times binary string is prefix aligned | 1,375 | 0.659 | Medium | 20,653 |
https://leetcode.com/problems/number-of-times-binary-string-is-prefix-aligned/discuss/1133177/Python-easy-solution-99-faster-98-less-memory | class Solution:
def numTimesAllBlue(self, light: List[int]) -> int:
max=0
c=0
for i in range(len(light)):
if(light[i]>max):
max=light[i]
if(max==i+1):
c=c+1
return c | number-of-times-binary-string-is-prefix-aligned | Python easy solution 99% faster, 98% less memory | Rajashekar_Booreddy | 2 | 358 | number of times binary string is prefix aligned | 1,375 | 0.659 | Medium | 20,654 |
https://leetcode.com/problems/number-of-times-binary-string-is-prefix-aligned/discuss/2839622/One-iteration-TC-O(n)-SC-O(1) | class Solution:
def numTimesAllBlue(self, flips: List[int]) -> int:
s,maxi,res = 0,0,0
for i in flips:
if i > maxi:
maxi = i
s += i
if s == (maxi * (maxi+1))//2:
res +=1
return res | number-of-times-binary-string-is-prefix-aligned | One iteration, TC O(n), SC O(1) | jeevanjoyal77 | 0 | 2 | number of times binary string is prefix aligned | 1,375 | 0.659 | Medium | 20,655 |
https://leetcode.com/problems/number-of-times-binary-string-is-prefix-aligned/discuss/2795654/Python-beat-100 | class Solution:
def numTimesAllBlue(self, flips: List[int]) -> int:
l=len(flips)
summ=0
actual=0
ans=0
for i in range(l):
summ+=flips[i]
actual+=(i+1)
if summ==actual:
ans+=1
return ans | number-of-times-binary-string-is-prefix-aligned | Python beat 100% | RjRahul003 | 0 | 3 | number of times binary string is prefix aligned | 1,375 | 0.659 | Medium | 20,656 |
https://leetcode.com/problems/number-of-times-binary-string-is-prefix-aligned/discuss/2526194/python-simple-solution | class Solution:
def numTimesAllBlue(self, flips: List[int]) -> int:
ans = 0
largest = 0
for i,n in enumerate(flips):
largest = max(largest, n)
if largest == i+1:
ans+=1
return ans | number-of-times-binary-string-is-prefix-aligned | python simple solution | li87o | 0 | 26 | number of times binary string is prefix aligned | 1,375 | 0.659 | Medium | 20,657 |
https://leetcode.com/problems/time-needed-to-inform-all-employees/discuss/1206574/Python3-Path-compression-(Clean-code-beats-99) | class Solution:
def numOfMinutes(self, n: int, headID: int, manager: List[int], informTime: List[int]) -> int:
def find(i):
if manager[i] != -1:
informTime[i] += find(manager[i])
manager[i] = -1
return informTime[i]
return max(map(find, range(n))) | time-needed-to-inform-all-employees | [Python3] Path compression (Clean code, beats 99%) | SPark9625 | 10 | 351 | time needed to inform all employees | 1,376 | 0.584 | Medium | 20,658 |
https://leetcode.com/problems/time-needed-to-inform-all-employees/discuss/1840606/Python3-or-Very-Simple-w-Explanation-or-100 | class Solution:
def numOfMinutes(self, n: int, headID: int, manager: List[int], informTime: List[int]) -> int:
def calculateTime(n: int) -> int:
if manager[n] != -1:
informTime[n] += calculateTime(manager[n])
manager[n] = -1
return informTime[n]
for idx in range(len(manager)):
calculateTime(idx)
return max(informTime) | time-needed-to-inform-all-employees | Python3 | Very Simple w/ Explanation | 100% | casmith1987 | 5 | 209 | time needed to inform all employees | 1,376 | 0.584 | Medium | 20,659 |
https://leetcode.com/problems/time-needed-to-inform-all-employees/discuss/1606637/Easiest-Approach-oror-Well-coded-and-Explained | class Solution:
def numOfMinutes(self, n: int, headID: int, manager: List[int], informTime: List[int]) -> int:
graph = defaultdict(list)
for e,m in enumerate(manager):
graph[m].append(e)
q = [[headID,0]]
res = 0
while q:
newq = []
local = 0
for m,t in q:
res = max(res,t)
for e in graph[m]:
newq.append([e,t+informTime[m]])
q = newq[::]
return res | time-needed-to-inform-all-employees | 📌📌 Easiest Approach || Well-coded & Explained 🐍 | abhi9Rai | 3 | 214 | time needed to inform all employees | 1,376 | 0.584 | Medium | 20,660 |
https://leetcode.com/problems/time-needed-to-inform-all-employees/discuss/532680/Python3-dfs-recursively-and-iteratively | class Solution:
def numOfMinutes(self, n: int, headID: int, manager: List[int], informTime: List[int]) -> int:
subordinate = dict() #employee tree
for i, m in enumerate(manager): subordinate.setdefault(m, []).append(i)
def dfs(node):
return informTime[node] + max((dfs(n) for n in subordinate.get(node, [])), default=0)
return dfs(headID) | time-needed-to-inform-all-employees | [Python3] dfs recursively & iteratively | ye15 | 2 | 90 | time needed to inform all employees | 1,376 | 0.584 | Medium | 20,661 |
https://leetcode.com/problems/time-needed-to-inform-all-employees/discuss/532680/Python3-dfs-recursively-and-iteratively | class Solution:
def numOfMinutes(self, n: int, headID: int, manager: List[int], informTime: List[int]) -> int:
subordinate = dict() #employee tree
for i, m in enumerate(manager): subordinate.setdefault(m, []).append(i)
ans = 0
stack = [(headID, 0)] #id-time
while stack: #dfs
i, t = stack.pop()
ans = max(ans, t)
for ii in subordinate.get(i, []): stack.append((ii, t + informTime[i]))
return ans | time-needed-to-inform-all-employees | [Python3] dfs recursively & iteratively | ye15 | 2 | 90 | time needed to inform all employees | 1,376 | 0.584 | Medium | 20,662 |
https://leetcode.com/problems/time-needed-to-inform-all-employees/discuss/2304676/Python3-DFS | class Solution:
result = 0
def get_result(self,headId,manager_dic,informTime,time):
if len(manager_dic[headId])==0:
self.result = max(self.result,time)
return
for i in manager_dic[headId]:
self.get_result(i,manager_dic,informTime,time+informTime[headId])
def numOfMinutes(self, n: int, headID: int, manager: List[int], informTime: List[int]) -> int:
manager_dic = {}
self.result = 0
for i in range(n):
manager_dic[i] = []
for i in range(n):
if manager[i]!=-1:
manager_dic[manager[i]].append(i)
#print(manager_dic)
self.get_result(headID,manager_dic,informTime,0)
return self.result | time-needed-to-inform-all-employees | 📌 Python3 DFS | Dark_wolf_jss | 1 | 44 | time needed to inform all employees | 1,376 | 0.584 | Medium | 20,663 |
https://leetcode.com/problems/time-needed-to-inform-all-employees/discuss/1882795/Python-or-DFS-O(N) | class Solution:
def numOfMinutes(self, n: int, headID: int, manager: List[int], informTime: List[int]) -> int:
subordinates = defaultdict(list)
for i, emp in enumerate(manager): subordinates[emp].append(i)
stack = [[headID, 0]]
time = 0
while stack:
man, man_time = stack.pop()
time = max(time, man_time)
for subordinate in subordinates[man]:
stack.append([subordinate, man_time + informTime[man]])
return time | time-needed-to-inform-all-employees | Python | DFS - O(N) | rbhandu | 1 | 141 | time needed to inform all employees | 1,376 | 0.584 | Medium | 20,664 |
https://leetcode.com/problems/time-needed-to-inform-all-employees/discuss/2770930/Python-or-Recursionor-10-LOC | class Solution:
def numOfMinutes(self, n: int, headID: int, manager: List[int], informTime: List[int]) -> int:
graph = defaultdict(list)
#create graph
for i in range(len(manager)):
if manager[i] != -1:
graph[manager[i]].append(i)
#return max time needed for each employee.
def helper(node):
ans = 0
for c in graph[node]:
ans = max(ans, informTime[node] + helper(c))
return ans
return helper(headID) | time-needed-to-inform-all-employees | Python | Recursion| 10 LOC | __vaka | 0 | 1 | time needed to inform all employees | 1,376 | 0.584 | Medium | 20,665 |
https://leetcode.com/problems/time-needed-to-inform-all-employees/discuss/2760178/BFS-solution-keeping-the-time-for-each-node. | class Solution:
def numOfMinutes(self, n: int, headID: int, manager: List[int], informTime: List[int]) -> int:
hashmap = defaultdict(list)
for i, id in enumerate(manager):
if id != -1:
hashmap[id].append(i)
queue = deque([(headID, 0)])
res = 0
while queue:
t = 0
for _ in range(len(queue)):
curr, t = queue.popleft()
t += informTime[curr]
queue.extend([(id, t) for id in hashmap[curr]])
res = max(res, t)
return res | time-needed-to-inform-all-employees | BFS solution keeping the time for each node. | michaelniki | 0 | 2 | time needed to inform all employees | 1,376 | 0.584 | Medium | 20,666 |
https://leetcode.com/problems/time-needed-to-inform-all-employees/discuss/2686357/Python-SimpleEasyPrecise-DFS-Clean-Code | class Solution:
def numOfMinutes(self, n: int, headID: int, manager: List[int], informTime: List[int]) -> int:
from collections import defaultdict
d = defaultdict(list)
for idx, (val,price) in enumerate(zip(manager,informTime)):
d[val].append((idx,price))
def dfs(root):
if d.get(root,None) is None: return 0
else: return max(max([dfs(val)+price]) for val, price in d[root])
return dfs(-1) | time-needed-to-inform-all-employees | [Python] Simple/Easy/Precise DFS - Clean Code | girraj_14581 | 0 | 10 | time needed to inform all employees | 1,376 | 0.584 | Medium | 20,667 |
https://leetcode.com/problems/time-needed-to-inform-all-employees/discuss/2289496/Python3-BFS-solution | class Solution:
def numOfMinutes(self, n: int, headID: int, manager: List[int], informTime: List[int]) -> int:
# Level order traversal
# headID is root of tree
q = deque([headID])
# Maintain a inform time at particular node
total_times = [0] * n
childs = {i: [] for i in range(n)}
for i in range(len(manager)):
if manager[i] != -1:
childs[manager[i]].append(i)
while q:
node = q.popleft()
for ch in childs[node]:
# When you reach node, maintain a time to reach there
total_times[ch] = total_times[node] + informTime[node]
q.append(ch)
return max(total_times) | time-needed-to-inform-all-employees | [Python3] BFS solution | Gp05 | 0 | 42 | time needed to inform all employees | 1,376 | 0.584 | Medium | 20,668 |
https://leetcode.com/problems/time-needed-to-inform-all-employees/discuss/2204061/Graph-oror-DFS | class Solution:
def dfs(self, manager, informTime, minutesRequired, maximum, graph):
minutesRequired = max(minutesRequired, maximum)
for employee in graph[manager]:
maximum += informTime[manager]
minutesRequired = self.dfs(employee, informTime, minutesRequired, maximum, graph)
maximum -= informTime[manager]
return minutesRequired
def numOfMinutes(self, n: int, headID: int, manager: List[int], informTime: List[int]) -> int:
graph = {i : [] for i in range(n)}
for idx, val in enumerate(manager):
if val != -1:
graph[val].append(idx)
minutesRequired = 0
maximum = 0
minutesRequired = self.dfs(headID, informTime, minutesRequired, maximum, graph)
return minutesRequired | time-needed-to-inform-all-employees | Graph || DFS | Vaibhav7860 | 0 | 71 | time needed to inform all employees | 1,376 | 0.584 | Medium | 20,669 |
https://leetcode.com/problems/time-needed-to-inform-all-employees/discuss/2137107/python-3-oror-simple-dfs | class Solution:
def numOfMinutes(self, n: int, headID: int, managers: List[int], informTimes: List[int]) -> int:
subs = [[] for _ in range(n)]
for sub, manager in enumerate(managers):
if sub != headID:
subs[manager].append(sub)
def dfs(manager):
if not subs[manager]:
return 0
return informTimes[manager] + max(dfs(sub) for sub in subs[manager])
return dfs(headID) | time-needed-to-inform-all-employees | python 3 || simple dfs | dereky4 | 0 | 110 | time needed to inform all employees | 1,376 | 0.584 | Medium | 20,670 |
https://leetcode.com/problems/time-needed-to-inform-all-employees/discuss/2083653/Easy-Python-Recursive-DP-with-Cache-Decorator-(4-lines-of-code) | class Solution:
def numOfMinutes(self, n: int, headID: int, manager: List[int], informTime: List[int]) -> int:
@cache
def rec(personID):
if personID == headID:
return informTime[personID]
else:
return rec(manager[personID]) + informTime[personID]
# We could compress this further to 4 lines of code at the cost of readability
#@cache
#def rec(personID):
# return informTime[personID] if personID == headID else rec(manager[personID]) + informTime[personID]
return max([rec(personID) for personID in range(n)]) | time-needed-to-inform-all-employees | Easy Python, Recursive DP with Cache Decorator (4 lines of code) | boris17 | 0 | 49 | time needed to inform all employees | 1,376 | 0.584 | Medium | 20,671 |
https://leetcode.com/problems/time-needed-to-inform-all-employees/discuss/2047155/Python-simple-DFS | class Solution:
def numOfMinutes(self, n: int, headID: int, manager: List[int], informTime: List[int]) -> int:
graph = defaultdict(list)
for i, v in enumerate(manager) :
graph[v].append(i)
def dfs(n) :
ans = 0
for v in graph[n] :
ans = max(ans, dfs(v)+informTime[n])
return ans
ans = dfs(headID)
return ans | time-needed-to-inform-all-employees | Python simple DFS | runtime-terror | 0 | 83 | time needed to inform all employees | 1,376 | 0.584 | Medium | 20,672 |
https://leetcode.com/problems/time-needed-to-inform-all-employees/discuss/2025059/Python-easy-to-read-and-understand-or-dfs | class Solution:
def dfs(self, graph, node, visit, informTime):
ans = 0
visit.add(node)
for nei in graph[node]:
if nei not in visit:
ans = max(ans, self.dfs(graph, nei, visit, informTime) + informTime[node])
return ans
def numOfMinutes(self, n: int, headID: int, manager: List[int], informTime: List[int]) -> int:
graph = {i:[] for i in range(n)}
for i, val in enumerate(manager):
if val == -1:
continue
graph[i].append(val)
graph[val].append(i)
visit = set()
return self.dfs(graph, headID, visit, informTime) | time-needed-to-inform-all-employees | Python easy to read and understand | dfs | sanial2001 | 0 | 71 | time needed to inform all employees | 1,376 | 0.584 | Medium | 20,673 |
https://leetcode.com/problems/time-needed-to-inform-all-employees/discuss/1935472/Python3-EXPLAINED-DFS-O(N)-97-faster-97-memory-efficient | class Solution:
def numOfMinutes(self, n: int, headID: int, manager: List[int], informTime: List[int]) -> int:
self.manager = manager
self.informTime = informTime
# Store the previously calculated times in this list.
self.minutes = [-1] * n
self.minutes[headID] = 0 # 0 minutes to inform the head
m = 0 # Stores the max minutes so far
# For each employee, we look at how many minutes it took to inform his/her manager.
# We take that and add how much time the manager takes to inform the current employee.
# That is the total time taken to inform that employee
# The maximum value of the minues list will be our answer
for i in range(n):
if self.minutes[i] == -1:
self.findMinutes(i)
if self.minutes[i] > m: # Calculate maximum value
m = self.minutes[i]
return m
def findMinutes(self, ind):
# If the time taken for this employee has already been calculated, return it.
if self.minutes[ind] != -1:
return self.minutes[ind]
# Calculate the time taken to inform this employee based on his/her manager
man = self.manager[ind]
val = self.minutes[ind] = self.findMinutes(man) + self.informTime[man]
return val | time-needed-to-inform-all-employees | [Python3] [EXPLAINED] DFS O(N) 97% faster, 97% memory efficient | akhileshravi | 0 | 99 | time needed to inform all employees | 1,376 | 0.584 | Medium | 20,674 |
https://leetcode.com/problems/time-needed-to-inform-all-employees/discuss/1820286/Python-Backtracking | class Solution:
def numOfMinutes(self, n: int, headID: int, manager: List[int], informTime: List[int]) -> int:
graph = [[] for i in range(n)]
for i, m in enumerate(manager):
if m == -1: continue
graph[m].append(i)
def backtrack(curr, total, runningSum = 0):
if informTime[curr] == 0:
total[0] = max(total[0], runningSum)
for neigh in graph[curr]:
runningSum += informTime[curr]
backtrack(neigh, total, runningSum)
runningSum -= informTime[curr]
total = [0]
backtrack(headID, total)
return total[0] | time-needed-to-inform-all-employees | Python Backtracking | Rush_P | 0 | 39 | time needed to inform all employees | 1,376 | 0.584 | Medium | 20,675 |
https://leetcode.com/problems/time-needed-to-inform-all-employees/discuss/1635261/python3-bad-but-easy-solution-DFS-%2Bmemoization-with-explanation | class Solution:
def __init__(self):
self.structure = {} #structure maintains the mapping of manager and its reportee
self.memo = {} #memo stands for the time that an employee notify everyone reports (no matter directly or indirectly) to him/her
def numOfMinutes(self, n: int, headID: int, manager: List[int], informTime: List[int]) -> int:
#init the structure mapping
if len(manager) <= 1:return 0
for i in range(n):
if manager[i] == -1:continue
if manager[i] not in self.structure.keys():
self.structure[manager[i]] = [i]
else:
self.structure[manager[i]].append(i)
#DFSfunction to evaluate the time consumption
def helper(curr):
if curr in self.memo.keys():
return self.memo[curr]
ans = informTime[curr]
if curr not in self.structure.keys():
return ans
stack = self.structure[curr]
temp = 0
for i in stack:
temp = max(temp, helper(i))
return ans + temp
return helper(headID) | time-needed-to-inform-all-employees | python3 bad but easy solution, DFS +memoization with explanation | 752937603 | 0 | 55 | time needed to inform all employees | 1,376 | 0.584 | Medium | 20,676 |
https://leetcode.com/problems/time-needed-to-inform-all-employees/discuss/1441802/Python3or-or-Both-DFS-BFS-Solution | class Solution:
def numOfMinutes(self, n: int, headID: int, manager: List[int], informTime: List[int]) -> int:
child=[[] for i in range(n)]
dist=[0 for i in range(n)]
dist[headID]=0
for i in range(n):
if manager[i]!=-1:
child[manager[i]].append(i)
self.dfs(headID,child,dist,informTime)
return max(dist)
def dfs(self,par,child,dist,informTime):
for it in child[par]:
dist[it]=dist[par]+informTime[par]
self.dfs(it,child,dist,informTime)
return | time-needed-to-inform-all-employees | [Python3| | Both DFS/ BFS Solution | swapnilsingh421 | 0 | 68 | time needed to inform all employees | 1,376 | 0.584 | Medium | 20,677 |
https://leetcode.com/problems/time-needed-to-inform-all-employees/discuss/1301902/python3-bfs | class Solution:
def numOfMinutes(self, n: int, headID: int, manager: List[int], informTime: List[int]) -> int:
D=defaultdict(list)
for i in range(n):
if manager[i]!=-1:
D[manager[i]].append(i)
Max=0
q=[[headID,0]]
while q:
a,time=q.pop(0)
Max=max(time,Max)
for i in D[a]:
q.append([i,time+informTime[a]])
return Max | time-needed-to-inform-all-employees | python3 bfs | ketan_raut | 0 | 81 | time needed to inform all employees | 1,376 | 0.584 | Medium | 20,678 |
https://leetcode.com/problems/time-needed-to-inform-all-employees/discuss/1160038/SIMPLE-PYTHON-CODE | class Solution:
def numOfMinutes(self, n: int, headID: int, manager: List[int], info: List[int]) -> int:
graph = collections.defaultdict(list)
for i , node in enumerate(manager):
if node != -1:
graph[node].append(i)
time = [ float("inf")]*n
time[headID] = 0
#print(graph)
def dfs(node,t):
for nei in graph[node]:
if time[nei] == float("inf"):
time[nei] = t+info[node]
dfs(nei,t + info[node])
dfs(headID,0)
return max(time) | time-needed-to-inform-all-employees | SIMPLE PYTHON CODE | rupkatha | 0 | 84 | time needed to inform all employees | 1,376 | 0.584 | Medium | 20,679 |
https://leetcode.com/problems/time-needed-to-inform-all-employees/discuss/959333/Python3-Soluion-using-dfs-approach | class Solution:
def __init__(self):
self.result = [0]
def dfs(self,count,head,informTime,time):
self.result[0] = max(self.result[0],time)
for emp in count[head]:
self.dfs(count,emp,informTime,time+informTime[head])
def numOfMinutes(self, n: int, headID: int, manager: List[int], informTime: List[int]) -> int:
count = collections.defaultdict(list)
for i in range(len(manager)):
count[manager[i]].append(i)
self.dfs(count,headID,informTime,0)
return self.result[0] | time-needed-to-inform-all-employees | Python3 Soluion using dfs approach | swap2001 | 0 | 56 | time needed to inform all employees | 1,376 | 0.584 | Medium | 20,680 |
https://leetcode.com/problems/frog-position-after-t-seconds/discuss/1092590/Python-basic-DFS-from-a-new-grad | class Solution:
def frogPosition(self, n: int, edges: List[List[int]], t: int, target: int) -> float:
if target==1:
if t>=1 and len(edges)>=1:
return 0
adj = collections.defaultdict(list)
for i in edges:
adj[min(i[0],i[1])].append(max(i[1],i[0]))
def traversal(curr, target,t):
if curr==target:
if t==0 or len(adj[curr])==0:
return 1
return 0
if t==0:
return 0
for child in adj[curr]:
prob = traversal(child, target, t-1)/len(adj[curr])
if prob>0:
return prob
return 0
return traversal(1,target,t) | frog-position-after-t-seconds | Python basic DFS from a new grad | yb233 | 1 | 142 | frog position after t seconds | 1,377 | 0.361 | Hard | 20,681 |
https://leetcode.com/problems/frog-position-after-t-seconds/discuss/532713/Python3-bfs-tree-traversal | class Solution:
def frogPosition(self, n: int, edges: List[List[int]], t: int, target: int) -> float:
tree = dict()
for i, j in edges:
if i > j: i, j = j, i
tree.setdefault(i-1, []).append(j-1)
queue, time = [(0, 1)], 0 #node-prob
while queue and time <= t: #bfs
tmp = []
for node, prob in queue:
if node == target-1: return 0 if time < t and node in tree else prob
for n in tree.get(node, []): tmp.append((n, prob/len(tree[node])))
queue, time = tmp, time+1
return 0 | frog-position-after-t-seconds | [Python3] bfs tree traversal | ye15 | 1 | 79 | frog position after t seconds | 1,377 | 0.361 | Hard | 20,682 |
https://leetcode.com/problems/frog-position-after-t-seconds/discuss/2592320/DFS-in-Python3-faster-than-90 | class Solution:
def dfs(self, node, target, t, prob):
self.visited.add(node)
if t == 0:
return prob if node == target else 0.0
children = set()
for v in self.graph[node]:
if v not in self.visited:
children.add(v)
if not children:
return prob if node == target else 0.0
for v in children:
p = self.dfs(v, target, t-1, prob / len(children))
if p > 0:
return p
return 0.0
def frogPosition(self, n: int, edges: List[List[int]], t: int, target: int) -> float:
self.graph = defaultdict(set)
for v, u in edges:
self.graph[v].add(u)
self.graph[u].add(v)
self.visited = set()
return self.dfs(1, target, t, 1.0) | frog-position-after-t-seconds | DFS in Python3, faster than 90% | metaphysicalist | 0 | 13 | frog position after t seconds | 1,377 | 0.361 | Hard | 20,683 |
https://leetcode.com/problems/frog-position-after-t-seconds/discuss/2534436/Python-Readable-DFS-Solution-(Commented) | class Solution:
def frogPosition(self, n: int, edges: List[List[int]], t: int, target: int) -> float:
# connections
self.conn = collections.defaultdict(list)
# get the connections
for edge in edges:
self.conn[edge[0]].append(edge[1])
self.conn[edge[1]].append(edge[0])
# safe the probability
self.prob = 0
# make an array for the visited nodes
# since these are only identified by
# an increasing int, we can use an array
# of bools
self.visited = [False]*n
self.visited[0] = True
# make a dfs - during dfs we always will
# add probability of path if we found a valid
# one
self.dfs(1, 1, t, target)
return self.prob
def dfs(self, current, prob, time, target):
# if time is over we need to check
# whether we are at the target
# otherwise we just return
# -> stop condition 3b
if time == 0:
if current == target:
self.prob += prob
return
# get the current nodes we can visit
visible = self.conn[current]
# get the amount of nodes we can
# visit and have not already visited
amount = 0
for node in visible:
# guard clause if we visited the node
if self.visited[node-1]:
continue
# increase the amount of nodes we can visit
amount += 1
# check whether we can visit any nodes
if amount:
# check whether we are at target and therefore target is out
# stop condition 3c
if current == target:
return
# calculate the updated probability and time
updated_time = time-1
updated_probability = prob*(1/amount)
# go through all nodes we have not visited
for node in visible:
# guard clause to skip nodes we have visited
if self.visited[node-1]:
continue
# set the current node as visited
self.visited[current-1] = True
# traverse further and with updated values
self.dfs(node, updated_probability, updated_time, target)
# reset that we visited this node
self.visited[current-1] = False
# we can not visit any further nodes
# stop condition 3a
else:
# check whether we are at target
if current == target:
self.prob += prob
return | frog-position-after-t-seconds | [Python] - Readable DFS Solution (Commented) | Lucew | 0 | 25 | frog position after t seconds | 1,377 | 0.361 | Hard | 20,684 |
https://leetcode.com/problems/frog-position-after-t-seconds/discuss/1975915/Python3-solution | class Solution:
def frogPosition(self, n: int, edges: List[List[int]], t: int, target: int) -> float:
def gen_adjacency():
adj = collections.defaultdict(list)
for a, b in edges:
adj[a].append(b)
adj[b].append(a)
return adj
def dfs(node, cumprob, time):
canjump = sum(1 for neigh in adj[node] if neigh not in visited)
if node==target:
if (time <= t and not canjump) or (time==t and canjump):
self.ans = cumprob
return
visited.add(node)
if canjump:
prob = 1/canjump
else:
return
for neigh in adj[node]:
if neigh not in visited:
dfs(neigh, cumprob * prob, time+1)
visited = set()
adj = gen_adjacency()
self.ans = 0
dfs(node=1, cumprob=1, time=0)
return self.ans | frog-position-after-t-seconds | Python3 solution | dalechoi | 0 | 27 | frog position after t seconds | 1,377 | 0.361 | Hard | 20,685 |
https://leetcode.com/problems/frog-position-after-t-seconds/discuss/1308867/python-bfs-(92ms-Fast) | class Solution:
def frogPosition(self, n: int, edges: List[List[int]], t: int, target: int) -> float:
if n==1:
return 1.0
D=defaultdict(list)
for i,j in edges:
D[i].append(j)
D[j].append(i)
L=[[-1,0]]*(n+1)
L[1]=[1.0,0]
q=[(1,1,0)]
visited=set()
astro=0
while q:
node,prob,time=q.pop(0)
visited.add(node)
for new_node in D[node]:
if new_node not in visited:
new_prob=prob*(1/(len(D[node]) if astro==0 else len(D[node])-1))
q.append((new_node,new_prob,time+1))
L[new_node]=list([new_prob,time+1])
astro+=1
end_nodes=[]
for d in D:
if len(D[d])==1:
end_nodes.append(d)
if 1 in end_nodes:
end_nodes.remove(1)
if target in end_nodes:
if L[target][1]>t:
return 0.0
return L[target][0]
else:
if L[target][1]==t:
return L[target][0]
return 0.0 | frog-position-after-t-seconds | python bfs (92ms-Fast) | ketan_raut | 0 | 95 | frog position after t seconds | 1,377 | 0.361 | Hard | 20,686 |
https://leetcode.com/problems/frog-position-after-t-seconds/discuss/704301/Python-BFS | class Solution:
def frogPosition(self, n: int, edges: List[List[int]], t: int, target: int) -> float:
if target==1:
return 1.0 if len(edges)==0 else 0.0
# note it's a undirected graph
graph=[{} for _ in range(n+1)]
for src,dst in edges:
graph[src][dst]=1
graph[dst][src]=1
# do a bfs
queue=[(1,1.0)]
next=[]
for time in range(t):
for node,p in queue:
for child in graph[node]:
del graph[child][node]
if child==target:
if time==t-1 or len(graph[child])<1:
return p/len(graph[node])
else:
return 0.0
next.append((child,p/len(graph[node])))
queue=next
next=[]
return 0.0 | frog-position-after-t-seconds | [Python] BFS | lkwq007 | 0 | 72 | frog position after t seconds | 1,377 | 0.361 | Hard | 20,687 |
https://leetcode.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/discuss/2046151/Python-Simple-2-approaches-Recursion(3-liner)-and-Morris | class Solution:
def getTargetCopy(self, node1: TreeNode, node2: TreeNode, target: TreeNode) -> TreeNode:
if not node1 or target == node1: # if node1 is null, node2 will also be null
return node2
return self.getTargetCopy(node1.left, node2.left, target) or self.getTargetCopy(node1.right, node2.right, target) | find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree | Python Simple 2 approaches - Recursion(3 liner) and Morris | constantine786 | 20 | 1,900 | find a corresponding node of a binary tree in a clone of that tree | 1,379 | 0.87 | Easy | 20,688 |
https://leetcode.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/discuss/2046151/Python-Simple-2-approaches-Recursion(3-liner)-and-Morris | class Solution:
def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
curr1=original
curr2=cloned
found = None
while curr1:
if not curr1.left:
if curr1==target:
found=curr2
curr1=curr1.right
curr2=curr2.right
else:
temp1 = curr1.left
temp2 = curr2.left
while temp1.right and temp1.right!=curr1:
temp1=temp1.right
temp2=temp2.right
if temp1.right==curr1:
temp1.right=None
temp2.right=None
if curr1 == target:
found=curr2
curr1=curr1.right
curr2=curr2.right
else:
temp1.right=curr1
temp2.right=curr2
curr1=curr1.left
curr2=curr2.left
return found | find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree | Python Simple 2 approaches - Recursion(3 liner) and Morris | constantine786 | 20 | 1,900 | find a corresponding node of a binary tree in a clone of that tree | 1,379 | 0.87 | Easy | 20,689 |
https://leetcode.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/discuss/2046277/Python-DFS-few-lines | class Solution:
def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
if original is None:
return
elif original == target:
return cloned
else:
return self.getTargetCopy(original.left, cloned.left, target) or self.getTargetCopy(original.right, cloned.right, target) | find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree | Python DFS few lines | darleisoares | 6 | 459 | find a corresponding node of a binary tree in a clone of that tree | 1,379 | 0.87 | Easy | 20,690 |
https://leetcode.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/discuss/1001866/Python3-iterative-preorder-dfs | class Solution:
def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
stack = [(original, cloned)]
while stack:
x, y = stack.pop()
if x == target: return y
if x:
stack.append((x.left, y.left))
stack.append((x.right, y.right)) | find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree | [Python3] iterative preorder dfs | ye15 | 4 | 117 | find a corresponding node of a binary tree in a clone of that tree | 1,379 | 0.87 | Easy | 20,691 |
https://leetcode.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/discuss/1763982/Python-Simple-Solution | class Solution:
def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
if cloned is None:
return cloned
if cloned.val == target.val:
return cloned
a = self.getTargetCopy(original, cloned.left, target)
if a is not None:
return a
else:
return self.getTargetCopy(original, cloned.right, target) | find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree | Python Simple Solution | anCoderr | 2 | 110 | find a corresponding node of a binary tree in a clone of that tree | 1,379 | 0.87 | Easy | 20,692 |
https://leetcode.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/discuss/2047078/Python3-Solution-Simple-DFS | class Solution:
def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
st = [cloned]
while st:
cur = st.pop()
if cur.val == target.val:
return cur
if cur.right:
st.append(cur.right)
if cur.left:
st.append(cur.left) | find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree | Python3 Solution Simple DFS | jeboria | 1 | 77 | find a corresponding node of a binary tree in a clone of that tree | 1,379 | 0.87 | Easy | 20,693 |
https://leetcode.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/discuss/2046141/Python3-or-Easy-Explanation-or-Recursion | class Solution:
def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
# print(target)
if original is None:
return None
if original == target:
return cloned
return self.getTargetCopy(original.left, cloned.left, target) or \
self.getTargetCopy(original.right, cloned.right, target) | find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree | Python3 | Easy Explanation | Recursion | prithuls | 1 | 34 | find a corresponding node of a binary tree in a clone of that tree | 1,379 | 0.87 | Easy | 20,694 |
https://leetcode.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/discuss/1337919/Python3-Iterative-and-simple-4-line | class Solution:
def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
queue = [False, cloned] # False denotes the end of the queue
while node := queue.pop(): # While false hasn't been reached the loop will continue
if node.val == target.val: return node # Checking if the current node is the target value
queue += filter(None, (node.right, node.left)) # Appending next nodes to queue if they are not None | find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree | [Python3] Iterative and simple 4-line | vscala | 1 | 71 | find a corresponding node of a binary tree in a clone of that tree | 1,379 | 0.87 | Easy | 20,695 |
https://leetcode.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/discuss/1332588/Simple-Solution-with-O(1) | class Solution:
def dfs(self, root, n):
if not root:
return n
return max(self.dfs(root.left, n+1),self.dfs(root.right, n+1))
def maxDepth(self, root: TreeNode) -> int:
return self.dfs(root, 0)
``` | find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree | Simple Solution, with O(1) | deleted_user | 1 | 88 | find a corresponding node of a binary tree in a clone of that tree | 1,379 | 0.87 | Easy | 20,696 |
https://leetcode.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/discuss/2498158/Recursive-Python-NLR-Easy | class Solution:
def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
if original.val == target.val:
return cloned
if original.left is not None:
result = self.getTargetCopy(
original = original.left,
cloned = cloned.left,
target = target
)
if result is not None:
return result
if original.right is not None:
result = self.getTargetCopy(
original = original.right,
cloned = cloned.right,
target = target
)
if result is not None:
return result | find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree | Recursive Python NLR Easy | cengleby86 | 0 | 17 | find a corresponding node of a binary tree in a clone of that tree | 1,379 | 0.87 | Easy | 20,697 |
https://leetcode.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/discuss/2094431/Python-DFS-%2B-BFS-Simple-Solution | class Solution:
def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
########################## DFS ############################
val = [None]
def dfs(tree):
if not tree:
return
if tree.val == target.val:
val[0] = tree
return
dfs(tree.left)
dfs(tree.right)
dfs(cloned)
return val[0]
########################## BFS ############################
q = deque([cloned])
while q:
node = q.popleft()
if node.val == target.val:
return node
if node.left:
q.append(node.left)
if node.right:
q.append(node.right) | find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree | Python DFS + BFS, Simple Solution | Hejita | 0 | 175 | find a corresponding node of a binary tree in a clone of that tree | 1,379 | 0.87 | Easy | 20,698 |
https://leetcode.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/discuss/2048759/Python-Recursive-Approach | class Solution:
def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
if not original or target==original:
return cloned
return self.getTargetCopy(original.left,cloned.left,target) or self.getTargetCopy(original.right,cloned.right,target) | find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree | Python Recursive Approach | backpropagator | 0 | 29 | find a corresponding node of a binary tree in a clone of that tree | 1,379 | 0.87 | Easy | 20,699 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.