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/relative-sort-array/discuss/1397234/Python3-Faster-Than-90.34-Memory-Less-Than-97.02 | class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
from collections import Counter
arr2_new = set(arr2)
a, b = [], []
for i in arr1:
if i in arr2_new:
a.append(i)
else:
b.append(i)
c = Counter(a)
res = []
for i in arr2:
res += [i] * c[i]
return res + sorted(b) | relative-sort-array | Python3 Faster Than 90.34%, Memory Less Than 97.02% | Hejita | 0 | 95 | relative sort array | 1,122 | 0.684 | Easy | 17,600 |
https://leetcode.com/problems/relative-sort-array/discuss/1352213/Python-solution-easy-to-understand | class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
output = []
# Sort the elements of arr1 such that the relative ordering of items in arr1 are the same as in arr2
for i in arr2:
for j in range(len(arr1)):
if arr1[j] == i:
output.append(arr1[j])
# Elements that don't appear in arr2 should be placed at the end of arr1 in ascending order
for i in sorted(arr1):
if i not in arr2:
output.append(i)
return output | relative-sort-array | Python solution easy to understand | tianshuhuang6 | 0 | 95 | relative sort array | 1,122 | 0.684 | Easy | 17,601 |
https://leetcode.com/problems/relative-sort-array/discuss/1319199/Python-fast-and-simple | class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
hm = {e: i for i, e in enumerate(arr2)}
return sorted(arr1, key = lambda x: hm.get(x, x + 1000)) | relative-sort-array | Python, fast and simple | MihailP | 0 | 138 | relative sort array | 1,122 | 0.684 | Easy | 17,602 |
https://leetcode.com/problems/relative-sort-array/discuss/1069279/My-Python3-solution-faster-than-79-less-memory-than-44 | class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
lookup_table = {a:i for i, a in enumerate(arr2)}
lookup_table.update({b:j for j, b in enumerate(sorted(arr1), start=len(arr2)) if b not in arr2})
reverse_lookup = {v:k for k, v in lookup_table.items()}
new_arr1 = sorted([lookup_table[a] for a in arr1])
return [reverse_lookup[a] for a in new_arr1] | relative-sort-array | My Python3 solution faster than 79% less memory than 44% | mhviraf | 0 | 102 | relative sort array | 1,122 | 0.684 | Easy | 17,603 |
https://leetcode.com/problems/relative-sort-array/discuss/1059957/Python-3 | class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
key = dict().fromkeys(arr2, 0)
temp = []
while arr1:
n = arr1.pop()
if n in key:
key[n] += 1
continue
temp.append(n)
return [el for el, i in key.items() for _ in range(i)] + sorted(temp) | relative-sort-array | Python 3 | ctarriba9 | 0 | 89 | relative sort array | 1,122 | 0.684 | Easy | 17,604 |
https://leetcode.com/problems/relative-sort-array/discuss/1010520/one-of-the-solution | class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
new_arr = []
for i in arr2:
arr = [i] * arr1.count(i)
new_arr.extend(arr)
new_arr.extend(sorted([i for i in arr1 if i not in arr2]))
return new_arr | relative-sort-array | one of the solution | izekchen0222 | 0 | 44 | relative sort array | 1,122 | 0.684 | Easy | 17,605 |
https://leetcode.com/problems/relative-sort-array/discuss/994790/2-Lines-99-Faster-with-Explanation-(Python3)%3A-24-ms | class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
arr2_dict = {arr2[i]:i for i in range(len(arr2))}
return sorted(arr1, key=lambda x: arr2_dict[x] if x in arr2_dict else x+1000) | relative-sort-array | 2 Lines, 99% Faster with Explanation (Python3): 24 ms | EddyLin | 0 | 81 | relative sort array | 1,122 | 0.684 | Easy | 17,606 |
https://leetcode.com/problems/relative-sort-array/discuss/951659/Python3-Simple-with-maintaining-pointer | class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
element_occurance = Counter(arr1)
arr3 = [0]*len(arr1)
ptr=0
for val in arr2:
no = element_occurance[val]
for j in range(0, no):
arr3[ptr+j] = val
ptr+=no
other = []
for n in arr1:
if n not in arr2:
other.append(n)
other.sort()
arr3[ptr:] = other
return arr3 | relative-sort-array | [Python3] Simple with maintaining pointer | vimoxshah | 0 | 39 | relative sort array | 1,122 | 0.684 | Easy | 17,607 |
https://leetcode.com/problems/relative-sort-array/discuss/721631/Python-Solution-with-Space-Complexity-Better-Than-95.41 | class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
res = []
counter = collections.Counter(arr1)
for i in arr2:
res += [i] * counter.pop(i)
res = res + sorted([i for i in arr1 if i not in arr2])
return res | relative-sort-array | Python Solution with Space Complexity Better Than 95.41% | parkershamblin | 0 | 195 | relative sort array | 1,122 | 0.684 | Easy | 17,608 |
https://leetcode.com/problems/relative-sort-array/discuss/721631/Python-Solution-with-Space-Complexity-Better-Than-95.41 | class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
d = {}
for i, v in enumerate(arr2):
d[v] = i
res = []
for i in arr2:
res += [i] * arr1.count(i)
res = res + sorted(i for i in arr1 if i not in arr2)
return res | relative-sort-array | Python Solution with Space Complexity Better Than 95.41% | parkershamblin | 0 | 195 | relative sort array | 1,122 | 0.684 | Easy | 17,609 |
https://leetcode.com/problems/relative-sort-array/discuss/335542/Python-one-liner-solution | class Solution(object):
def relativeSortArray(self, arr1, arr2):
return sorted(arr1, key=lambda x: (arr2.index(x) if x in arr2 else 2000, x)) | relative-sort-array | Python one liner solution | Bakugo | 0 | 78 | relative sort array | 1,122 | 0.684 | Easy | 17,610 |
https://leetcode.com/problems/relative-sort-array/discuss/1715849/Python3-one-liner | class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
return sorted(arr1, key=lambda x: (arr2.index(x) if x in arr2 else math.inf, x)) | relative-sort-array | Python3 one liner | hitmannypac | -1 | 80 | relative sort array | 1,122 | 0.684 | Easy | 17,611 |
https://leetcode.com/problems/lowest-common-ancestor-of-deepest-leaves/discuss/1760394/Python-easy-to-understand-and-read-or-DFS | class Solution:
def ht(self, node):
if not node:
return 0
return max(self.ht(node.left), self.ht(node.right)) + 1
def dfs(self, node):
if not node:
return None
left, right = self.ht(node.left), self.ht(node.right)
if left == right:
return node
if left > right:
return self.dfs(node.left)
if left < right:
return self.dfs(node.right)
def lcaDeepestLeaves(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
return self.dfs(root) | lowest-common-ancestor-of-deepest-leaves | Python easy to understand and read | DFS | sanial2001 | 4 | 184 | lowest common ancestor of deepest leaves | 1,123 | 0.706 | Medium | 17,612 |
https://leetcode.com/problems/lowest-common-ancestor-of-deepest-leaves/discuss/2408115/python-soln-using-heap-with-dfs | class Solution:
def lcaDeepestLeaves(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if not root.left and not root.right:
return root
stk=[[-1,root,[]]]
hp=[]
dic={}
heapq.heapify(hp)
while stk:
temp=stk.pop()
dic[temp[1].val]=temp[1]
heapq.heappush(hp,[temp[0],temp[1].val,temp[2]])
new=[*temp[2],temp[1].val]
if temp[1].left:
stk.append([temp[0]-1,temp[1].left,new])
if temp[1].right:
stk.append([temp[0]-1,temp[1].right,new])
ans=[heapq.heappop(hp)]
while hp[0][0]==ans[-1][0]:
ans.append(heapq.heappop(hp))
ans[-1][2]=set(ans[-1][2])
if len(ans)==1:
return dic[ans[0][1]]
for i in range(-1,-len(ans[0][2])-1,-1):
b=True
for j in range(1,len(ans)):
if ans[0][-1][i] not in ans[j][-1]:
b=False
if b:
return dic[ans[0][-1][i]]
return dic[ans[0][-1][-1]] | lowest-common-ancestor-of-deepest-leaves | python soln using heap with dfs | benon | 0 | 24 | lowest common ancestor of deepest leaves | 1,123 | 0.706 | Medium | 17,613 |
https://leetcode.com/problems/lowest-common-ancestor-of-deepest-leaves/discuss/2315479/python-3-or-bfs-%2B-dfs | class Solution:
def lcaDeepestLeaves(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
maxDepth = 0
deepestLeaves = 1
q = collections.deque([(root, 0)])
while q:
curRoot, curDepth = q.popleft()
if curDepth > maxDepth:
maxDepth = curDepth
deepestLeaves = 0
deepestLeaves += 1
if curRoot.left:
q.append((curRoot.left, curDepth + 1))
if curRoot.right:
q.append((curRoot.right, curDepth + 1))
if maxDepth == 0:
return root
if deepestLeaves == 1:
return curRoot
self.lca = None
self.lcaDepth = -1
def dfs(root, curDepth):
if root is None:
return 0
if curDepth == maxDepth:
return 1
n = dfs(root.left, curDepth + 1) + dfs(root.right, curDepth + 1)
if n == deepestLeaves and curDepth > self.lcaDepth:
self.lca = root
self.lcaDepth = curDepth
return n
dfs(root, 0)
return self.lca | lowest-common-ancestor-of-deepest-leaves | python 3 | bfs + dfs | dereky4 | 0 | 55 | lowest common ancestor of deepest leaves | 1,123 | 0.706 | Medium | 17,614 |
https://leetcode.com/problems/lowest-common-ancestor-of-deepest-leaves/discuss/2289962/Python3-Finding-Deepest-leaves-and-doing-LCA-of-them | class Solution:
def lcaDeepestLeaves(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
# Find all the deepest leaves
q = deque([root])
while q:
res = []
for i in range(len(q)):
node = q.popleft()
if node:
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
res.append(node.val)
# find LCA of deepest leaves
def lca(root):
if not root:
return None
if root.val in res:
return root
left = lca(root.left)
right = lca(root.right)
if left and right:
return root
if not left:
return right
else:
return left
return lca(root) | lowest-common-ancestor-of-deepest-leaves | [Python3] Finding Deepest leaves and doing LCA of them | Gp05 | 0 | 27 | lowest common ancestor of deepest leaves | 1,123 | 0.706 | Medium | 17,615 |
https://leetcode.com/problems/lowest-common-ancestor-of-deepest-leaves/discuss/1865250/Python3-DFS-solution | class Solution:
def lcaDeepestLeaves(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
'''
DFS, check the height of left and right
if left==right, the node itself is the LCA
if left>right, the LCA stays in the left side
if left <right, the LCA stays in the right side
'''
return self.helper(root,0)[0]
def helper(self, root, height):
if root is None:
return (None,0)
left=self.helper(root.left, height)
right=self.helper(root.right,height)
if left[1]==right[1]:
return (root,left[1]+1)
if left[1]>right[1]:
return (left[0],left[1]+1)
if left[1]<right[1]:
return (right[0],right[1]+1) | lowest-common-ancestor-of-deepest-leaves | Python3 DFS solution | muzhang90 | 0 | 86 | lowest common ancestor of deepest leaves | 1,123 | 0.706 | Medium | 17,616 |
https://leetcode.com/problems/lowest-common-ancestor-of-deepest-leaves/discuss/1778625/Python3-Solution-with-using-dfs | class Solution:
def __init__(self):
self.res = None
self.max_depth = 0
def traversal(self, node, cur_depth):
if not node:
return cur_depth
l_depth = self.traversal(node.left, cur_depth + 1)
r_depth = self.traversal(node.right, cur_depth + 1)
self.max_depth = max(self.max_depth, l_depth, r_depth)
if l_depth == r_depth == self.max_depth:
self.res = node
return max(l_depth, r_depth)
def lcaDeepestLeaves(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
self.traversal(root, 0)
return self.res | lowest-common-ancestor-of-deepest-leaves | [Python3] Solution with using dfs | maosipov11 | 0 | 74 | lowest common ancestor of deepest leaves | 1,123 | 0.706 | Medium | 17,617 |
https://leetcode.com/problems/lowest-common-ancestor-of-deepest-leaves/discuss/1774803/Python3-solution-using-BFS | class Solution:
def lcaDeepestLeaves(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
from collections import deque
q=deque()
q.append(root)
while q:
first=None
last=None
n=len(q)
for i in range(n):
node=q.popleft()
if i==0:
first=node
last=node
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
mydict={}
def Parents(root,parent):
if not root:
return
mydict[root]=parent
Parents(root.left,root)
Parents(root.right,root)
Parents(root,None)
s=set()
while first!=None:
s.add(first)
first=mydict[first]
while last!=None:
if last in s:
return last
last=mydict[last] | lowest-common-ancestor-of-deepest-leaves | Python3 solution using BFS | Karna61814 | 0 | 57 | lowest common ancestor of deepest leaves | 1,123 | 0.706 | Medium | 17,618 |
https://leetcode.com/problems/lowest-common-ancestor-of-deepest-leaves/discuss/1406441/python3-or-height%2Bfindnodes%2Blca-or-Brute-Force | class Solution:
def lcaDeepestLeaves(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
h=self.height(root) #find height
self.find=[]
self.findroot(root,1,h) #find all roots at that height
if len(self.find)==1: # if only one root is there then return it
return self.find[0]
lca=self.lca(root,self.find[0],self.find[1]) #find lca of first two roots
for i in range(2,len(self.find)):
lca=self.lca(root,lca,self.find[i]) #find lca of (lca of first 2 roots and next root)
return lca
def lca(self,root,a,b): #lca function to find lca
if not root:
return
if root==a or root==b:
return root
ln=self.lca(root.left,a,b)
rn=self.lca(root.right,a,b)
if ln and rn:
return root
elif ln:
return ln
else:
return rn
def findroot(self,root,lvl,h): #find all root at height h
if not root:
return
if lvl==h:
self.find.append(root)
self.findroot(root.left,lvl+1,h)
self.findroot(root.right,lvl+1,h)
def height(self,root): #find height of binary tree
if not root:
return 0
lh=self.height(root.left)
rh=self.height(root.right)
return 1+max(lh,rh) | lowest-common-ancestor-of-deepest-leaves | python3 | height+findnodes+lca | Brute Force | swapnilsingh421 | 0 | 37 | lowest common ancestor of deepest leaves | 1,123 | 0.706 | Medium | 17,619 |
https://leetcode.com/problems/lowest-common-ancestor-of-deepest-leaves/discuss/1345882/Python-3-DSU-or-O(n)-T-or-O(n)-S | class Solution:
def lcaDeepestLeaves(self, root: TreeNode) -> TreeNode:
import collections
class DSU:
def __init__(self):
self._to_parent = dict()
self._to_lvl = dict()
def make(self, x, lvl):
self._to_parent[x] = x
self._to_lvl[x] = lvl
def lvl(self, x):
return self._to_lvl[x]
def find(self, x):
if self._to_parent[x] is x:
return x
self._to_parent[x] = self.find(self._to_parent[x])
return self._to_parent[x]
def union(self, x, y):
import random
x_mark = self.find(x)
y_mark = self.find(y)
if random.randint(0, 1):
self._to_parent[x_mark] = y_mark
else:
self._to_parent[y_mark] = x_mark
dsu = DSU()
to_parent = dict()
q = collections.deque()
to_parent[root] = None
q.appendleft((root, 0))
deepest_leaves = []
max_lvl = -1
while len(q) > 0:
v, lvl = q.pop()
if max_lvl < lvl:
max_lvl = lvl
deepest_leaves = [v]
else:
deepest_leaves.append(v)
for ch in (v.left, v.right):
if ch is not None:
to_parent[ch] = v
q.appendleft((ch, lvl+1))
node = deepest_leaves[0]
dsu.make(node, max_lvl)
lvl = max_lvl
while node is not None:
prev = node
node = to_parent[node]
lvl -= 1
def dfs(v):
if v is None or v is prev:
return
dsu.make(v, lvl)
if v is not node:
dsu.union(node, v)
dfs(v.left)
dfs(v.right)
dfs(node)
target_lvl = min(dsu.lvl(leave) for leave in deepest_leaves)
lvl = max_lvl
node = deepest_leaves[0]
while lvl != target_lvl:
lvl -= 1
node = to_parent[node]
return node | lowest-common-ancestor-of-deepest-leaves | Python 3 DSU | O(n) T | O(n) S | CiFFiRO | 0 | 36 | lowest common ancestor of deepest leaves | 1,123 | 0.706 | Medium | 17,620 |
https://leetcode.com/problems/lowest-common-ancestor-of-deepest-leaves/discuss/1239567/Simple-solution-using-BFS-and-DFS | class Solution:
def lcaDeepestLeaves(self, root: TreeNode) -> TreeNode:
if not root:
return None
def get_deepest_nodes() -> List[TreeNode]:
queue = collections.deque([(root, 0)])
deepest_nodes = set()
deepest_level = 0
while queue:
node, node_level = queue.popleft()
if node_level > deepest_level:
deepest_nodes.clear()
deepest_level = node_level
deepest_nodes.add(node)
if node.left:
queue.append((node.left, node_level + 1))
if node.right:
queue.append((node.right, node_level + 1))
return deepest_nodes
def lca(node, deepest_nodes):
if not node:
return None
if node in deepest_nodes:
return node
left_result = lca(node.left, deepest_nodes)
right_result = lca(node.right, deepest_nodes)
if left_result and right_result:
return node
return left_result or right_result
deepest_nodes = get_deepest_nodes()
return lca(root, deepest_nodes) | lowest-common-ancestor-of-deepest-leaves | Simple solution using BFS and DFS | kapilsh | 0 | 142 | lowest common ancestor of deepest leaves | 1,123 | 0.706 | Medium | 17,621 |
https://leetcode.com/problems/lowest-common-ancestor-of-deepest-leaves/discuss/940631/Python3-dfs-O(N) | class Solution:
def lcaDeepestLeaves(self, root: TreeNode) -> TreeNode:
@lru_cache(None)
def fn(node):
"""Return height of tree rooted at node."""
if not node: return 0
return 1 + max(fn(node.left), fn(node.right))
node = root
while node:
left, right = fn(node.left), fn(node.right)
if left == right: return node
elif left > right: node = node.left
else: node = node.right | lowest-common-ancestor-of-deepest-leaves | [Python3] dfs O(N) | ye15 | 0 | 77 | lowest common ancestor of deepest leaves | 1,123 | 0.706 | Medium | 17,622 |
https://leetcode.com/problems/longest-well-performing-interval/discuss/1495771/For-Beginners-oror-Well-Explained-oror-97-faster-oror-Easy-to-understand | class Solution:
def longestWPI(self, hours: List[int]) -> int:
dic = defaultdict(int)
dummy = [1 if hours[0]>8 else -1]
for h in hours[1:]:
c = 1 if h>8 else -1
dummy.append(dummy[-1]+c)
res = 0
for i in range(len(dummy)):
if dummy[i]>0:
res = max(res,i+1)
else:
if dummy[i]-1 in dic:
res = max(res,i-dic[dummy[i]-1])
if dummy[i] not in dic:
dic[dummy[i]] = i
return res | longest-well-performing-interval | 📌📌 For-Beginners || Well-Explained || 97% faster || Easy-to-understand 🐍 | abhi9Rai | 4 | 471 | longest well performing interval | 1,124 | 0.346 | Medium | 17,623 |
https://leetcode.com/problems/longest-well-performing-interval/discuss/2183607/PYTHON-or-AS-INTERVIEWER-WANTS-orEXPLAINED-WITH-PICTURE-or-FAST-or-HASHMAP-%2B-PREFIX_SUM-or | class Solution:
def longestWPI(self, hours: List[int]) -> int:
n = len(hours)
ans = 0
prefix_sum = [0]*n
d = {}
for i in range(n):
prefix_sum[i] = 1 if hours[i] > 8 else -1
prefix_sum[i] += prefix_sum[i-1]
if prefix_sum[i] > 0 :
ans = i + 1
else:
if prefix_sum[i] - 1 in d:
j = d[prefix_sum[i] - 1]
if i - j > ans: ans = i - j
if prefix_sum[i] not in d: d[prefix_sum[i]] = i
return ans | longest-well-performing-interval | PYTHON | AS INTERVIEWER WANTS |EXPLAINED WITH PICTURE | FAST | HASHMAP + PREFIX_SUM | | reaper_27 | 3 | 234 | longest well performing interval | 1,124 | 0.346 | Medium | 17,624 |
https://leetcode.com/problems/longest-well-performing-interval/discuss/388562/Solution-in-Python-3-(beats-~90)-(six-lines)-(Dictionary) | class Solution:
def longestWPI(self, h: List[int]) -> int:
h, M, D = list(itertools.accumulate([2*(i > 8)-1 for i in h])), 0, {}
for i, s in enumerate(h):
if s > 0: M = i + 1
elif s - 1 in D: M = max(M, i - D[s-1])
elif s not in D: D[s] = i
return M
- Junaid Mansuri
(LeetCode ID)@hotmail.com | longest-well-performing-interval | Solution in Python 3 (beats ~90%) (six lines) (Dictionary) | junaidmansuri | 2 | 589 | longest well performing interval | 1,124 | 0.346 | Medium | 17,625 |
https://leetcode.com/problems/longest-well-performing-interval/discuss/2618613/Python3-Solution-or-O(n) | class Solution:
def longestWPI(self, A):
curr, ans, D = 0, 0, {}
for e, i in enumerate(map(lambda x: (-1, 1)[x > 8], A)):
curr += i
D[curr] = D.get(curr, e)
ans = e + 1 if curr > 0 else max(ans, e - D.get(curr - 1, e))
return ans | longest-well-performing-interval | ✔ Python3 Solution | O(n) | satyam2001 | 1 | 64 | longest well performing interval | 1,124 | 0.346 | Medium | 17,626 |
https://leetcode.com/problems/longest-well-performing-interval/discuss/2379209/Python3-or-PrefixSum-Approach | class Solution:
def longestWPI(self, hours: List[int]) -> int:
prefixSum=0
hmap=defaultdict(int)
ans=0
for length,hour in enumerate(hours):
prefixSum+=1 if hour>8 else -1
if prefixSum>0:ans=max(ans,length+1)
if prefixSum not in hmap:
hmap[prefixSum]=length
if prefixSum-1 in hmap:
ans=max(ans,length-hmap[prefixSum-1])
return ans | longest-well-performing-interval | [Python3] | PrefixSum Approach | swapnilsingh421 | 0 | 69 | longest well performing interval | 1,124 | 0.346 | Medium | 17,627 |
https://leetcode.com/problems/smallest-sufficient-team/discuss/334630/Python-Optimized-backtracking-with-explanation-and-code-comments-88-ms | class Solution:
def smallestSufficientTeam(self, req_skills: List[str], people: List[List[str]]) -> List[int]:
# Firstly, convert all the sublists in people into sets for easier processing.
for i, skills in enumerate(people):
people[i] = set(skills)
# Remove all skill sets that are subset of another skillset, by replacing the subset with an
# empty set. We do this rather than completely removing, so that indexes aren't
# disrupted (which is a pain to have to sort out later).
for i, i_skills in enumerate(people):
for j, j_skills in enumerate(people):
if i != j and i_skills.issubset(j_skills):
people[i] = set()
# Now build up a dictionary of skills to the people who can perform them. The backtracking algorithm
# will use this.
skills_to_people = collections.defaultdict(set)
for i, skills in enumerate(people):
for skill in skills:
skills_to_people[skill].add(i)
people[i] = set(skills)
# Keep track of some data used by the backtracking algorithm.
self.unmet_skills = set(req_skills) # Backtracking will remove and readd skills here as needed.
self.smallest_length = math.inf # Smallest team length so far.
self.current_team = [] # Current team members.
self.best_team = [] # Best team we've found, i,e, shortest team that covers skills/
# Here is the backtracking algorithm.
def meet_skill(skill=0):
# Base case: All skills are met.
if not self.unmet_skills:
# If the current team is smaller than the previous we found, update it.
if self.smallest_length > len(self.current_team):
self.smallest_length = len(self.current_team)
self.best_team = self.current_team[::] # In Python, this makes a copy of a list.
return # So that we don't carry out the rest of the algorithm.
# If this skill is already met, move onto the next one.
if req_skills[skill] not in self.unmet_skills:
return meet_skill(skill + 1)
# Note return is just to stop rest of code here running. Return values
# are not caught and used.
# Otherwise, consider all who could meet the current skill.
for i in skills_to_people[req_skills[skill]]:
# Add this person onto the team by updating the backtrading data.
skills_added_by_person = people[i].intersection(self.unmet_skills)
self.unmet_skills = self.unmet_skills - skills_added_by_person
self.current_team.append(i)
# Do the recursive call to further build the team.
meet_skill(skill + 1)
# Backtrack by removing the person from the team again.
self.current_team.pop()
self.unmet_skills = self.unmet_skills.union(skills_added_by_person)
# Kick off the algorithm.
meet_skill()
return self.best_team | smallest-sufficient-team | Python - Optimized backtracking with explanation and code comments [88 ms] | Hai_dee | 44 | 3,100 | smallest sufficient team | 1,125 | 0.47 | Hard | 17,628 |
https://leetcode.com/problems/smallest-sufficient-team/discuss/1201778/Python3-top-down-dp | class Solution:
def smallestSufficientTeam(self, req_skills: List[str], people: List[List[str]]) -> List[int]:
mp = {skill : i for i, skill in enumerate(req_skills)} # digitized skills
cand = []
for skills in people:
val = 0
for skill in skills:
val |= 1 << mp[skill] # digitized skill
cand.append(val)
@cache
def fn(i, mask):
"""Return smallest sufficient team of people[i:] for skills in mask."""
if mask == 0: return []
if i == len(people): return [0]*100 # impossible
if not (mask & cand[i]): return fn(i+1, mask)
return min(fn(i+1, mask), [i] + fn(i+1, mask & ~cand[i]), key=len)
return fn(0, (1 << len(req_skills)) - 1) | smallest-sufficient-team | [Python3] top-down dp | ye15 | 7 | 429 | smallest sufficient team | 1,125 | 0.47 | Hard | 17,629 |
https://leetcode.com/problems/smallest-sufficient-team/discuss/974537/Python3-DFS-with-memo-and-Bitmask-or-Prune-by-sort | class Solution:
def smallestSufficientTeam(self, req_skills: List[str], people: List[List[str]]) -> List[int]:
n_skills = len(req_skills)
n_people = len(people)
# index skills
skill_map = {x: i for i, x in enumerate(req_skills)}
# descending sort by length of skills per person
people = sorted([(i, x) for i, x in enumerate(people)], key=lambda x: -len(x[1]))
# bit people skill
people_bit = {}
for i, p in people:
tmp = 0
for s in p:
tmp |= 1 << skill_map[s]
# if a person skill cannot be covered from pervious people then added
if all(x | tmp != x for x in people_bit): people_bit[tmp] = i
# reverse skill set and id
people_bit = {v: k for k, v in people_bit.items()}
cands = [*people_bit.keys()]
# final answer and size for recording minimum team size
self.ans = None
self.size = float('inf')
@lru_cache(None)
def dp(i, mask, team):
if mask == (1 << n_skills) - 1 and self.size > len(team):
self.size = len(team)
self.ans = team
return
if i == len(cands):
return
# if current person has skill not covered by previous included skills
if mask | people_bit[cands[i]] != mask:
dp(i + 1, mask | people_bit[cands[i]], tuple(set(team)|{cands[i]}))
dp(i + 1, mask, team)
dp(0, 0, tuple())
return self.ans | smallest-sufficient-team | [Python3] DFS with memo & Bitmask | Prune by sort | chestnut890123 | 3 | 332 | smallest sufficient team | 1,125 | 0.47 | Hard | 17,630 |
https://leetcode.com/problems/number-of-equivalent-domino-pairs/discuss/405437/Python3-Concise-and-Efficient | class Solution:
def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:
m = collections.defaultdict(int)
ans = 0
for a, b in dominoes:
if a > b: a, b = b, a
v = 10*a + b
if v in m:
ans += m[v]
m[v] += 1
return ans | number-of-equivalent-domino-pairs | Python3 - Concise and Efficient | luojl | 6 | 310 | number of equivalent domino pairs | 1,128 | 0.469 | Easy | 17,631 |
https://leetcode.com/problems/number-of-equivalent-domino-pairs/discuss/1871033/PYTHON-DICTIONARY-solution-with-explanation-(252ms) | class Solution:
def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:
#Keep track of the dominoes with a dictionary
#counter[ DOMINO ] = COUNT
counter = defaultdict( int );
#Total will be the total number of pairs
total = 0;
#Go through all of the dominoes
for i in range( len ( dominoes ) ):
#Check the pair at the index
pair = dominoes[ i ];
#Pull the two values
first = pair[ 0 ];
second = pair[ 1 ];
#Sort them by value
#This way, the reversed matches will go into the same count
smaller = min ( first, second );
bigger = max( first, second );
#Reassemble into tuple
#This will act as our key for each domino
pair_sorted = ( smaller, bigger );
#If the current domino is already in our counter
#Add to the total the previous matches
#That is
#If we have already added matching dominoes
#Our current one will match with all the previous
if pair_sorted in counter:
total += counter[ pair_sorted ];
#Lastly, we increment the count of the current
counter [ pair_sorted ] += 1;
return total; | number-of-equivalent-domino-pairs | PYTHON DICTIONARY solution with explanation (252ms) | greg_savage | 4 | 247 | number of equivalent domino pairs | 1,128 | 0.469 | Easy | 17,632 |
https://leetcode.com/problems/number-of-equivalent-domino-pairs/discuss/1811069/3-Lines-Python-Solution-oror-75-Faster-oror-Memory-less-than-60 | class Solution:
def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:
counter = defaultdict(int)
for domino in dominoes: counter[tuple(sorted(domino))] +=1
return sum([n*(n-1)//2 for n in counter.values()]) | number-of-equivalent-domino-pairs | 3-Lines Python Solution || 75% Faster || Memory less than 60% | Taha-C | 1 | 138 | number of equivalent domino pairs | 1,128 | 0.469 | Easy | 17,633 |
https://leetcode.com/problems/number-of-equivalent-domino-pairs/discuss/1439836/Python3-Nice-Hack-to-use-Dictionary-Faster-Than-94 | class Solution:
def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:
d, c = dict(), 0
for i in dominoes:
if i[0] > i[1]:
i[0], i[1] = i[1], i[0]
if (i[0], i[1]) not in d:
d[(i[0], i[1])] = 1
else:
d[(i[0], i[1])] += 1
for j in d:
if d[j] > 1:
c += d[j] * (d[j] - 1) // 2
return c | number-of-equivalent-domino-pairs | Python3 Nice Hack to use Dictionary, Faster Than 94% | Hejita | 1 | 137 | number of equivalent domino pairs | 1,128 | 0.469 | Easy | 17,634 |
https://leetcode.com/problems/number-of-equivalent-domino-pairs/discuss/2833306/Sum-of-natural-numbers-with-graph-to-explain. | class Solution:
def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:
# To calculate:
# - Image a bunch of equivalent pairs as a graph with edges between every node.
# 2 -> 1
# 3 -> 2 + 1 = 2
# 4 -> 3 + 2 + 1 = 6
# i.e. (n - 1) * n // 2
d = Counter((min(x, y), max(x, y)) for x, y in dominoes)
return sum((v - 1) * v // 2 for v in d.values()) | number-of-equivalent-domino-pairs | Sum of natural numbers, with graph to explain. | demindiro | 0 | 2 | number of equivalent domino pairs | 1,128 | 0.469 | Easy | 17,635 |
https://leetcode.com/problems/number-of-equivalent-domino-pairs/discuss/2656835/Python%2BCounter | class Solution:
def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:
s=[]
for a, b in dominoes:
if a > b: a, b = b, a
v = 10*a + b
s.append(v)
return sum(map(lambda x :x*(x-1)//2,Counter(s).values())) | number-of-equivalent-domino-pairs | Python+Counter | Leox2022 | 0 | 8 | number of equivalent domino pairs | 1,128 | 0.469 | Easy | 17,636 |
https://leetcode.com/problems/number-of-equivalent-domino-pairs/discuss/1822734/Python-Straightforward-Solution-w-O(n)-RuntimeSpace-Complexity | class Solution:
def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:
def sort_domino(domino):
if domino[0] < domino[1]: return (domino[0], domino[1])
else: return (domino[1], domino[0])
count = 0
counts = {}
for domino in dominoes:
d = sort_domino(domino)
if d in counts:
count += counts[d]
counts[d] += 1
else: counts[d] = 1
return count | number-of-equivalent-domino-pairs | [Python] Straightforward Solution w/ O(n) Runtime/Space Complexity | shawntor | 0 | 120 | number of equivalent domino pairs | 1,128 | 0.469 | Easy | 17,637 |
https://leetcode.com/problems/number-of-equivalent-domino-pairs/discuss/1352306/Python-straight-forward-solution-using-dictionary-mapping | class Solution:
def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:
# create mapping that stores the occurences of every possible dominoes (including the reverse form) from dominoes list
mapping = {}
for i in dominoes:
if (i[0],i[1]) in mapping:
mapping[(i[0],i[1])] += 1
elif (i[1],i[0]) in mapping:
mapping[(i[1],i[0])] += 1
else:
mapping[(i[0],i[1])] = 1
# generate total count of domino pairs
# for dominoes that occured more than once, use binomial coefficient (n choose 2) to get the number of possible pairs
count = 0
for i in mapping:
if mapping[i]>1:
count = count + mapping[i]*(mapping[i]-1)/2
return int(count) | number-of-equivalent-domino-pairs | Python straight forward solution using dictionary mapping | tianshuhuang6 | 0 | 161 | number of equivalent domino pairs | 1,128 | 0.469 | Easy | 17,638 |
https://leetcode.com/problems/number-of-equivalent-domino-pairs/discuss/1242313/Python3-simple-solution-using-dictionary | class Solution:
def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:
d = {}
for i in dominoes:
i = tuple(i)
if i[::-1] in d:
d[i[::-1]] += 1
elif i in d:
d[i] += 1
else:
d[i] = 0
return sum([(i*(i+1))//2 for i in d.values()]) | number-of-equivalent-domino-pairs | Python3 simple solution using dictionary | EklavyaJoshi | 0 | 111 | number of equivalent domino pairs | 1,128 | 0.469 | Easy | 17,639 |
https://leetcode.com/problems/number-of-equivalent-domino-pairs/discuss/1204497/Time-Limit-Exceeded-in-Python3 | class Solution:
def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:
count = 0
for i in range(len(dominoes)):
for j in range(i+1, len(dominoes)):
if set(dominoes[i]) == set(dominoes[j]):
count += 1
return count | number-of-equivalent-domino-pairs | Time Limit Exceeded in Python3 | themotaguy | 0 | 127 | number of equivalent domino pairs | 1,128 | 0.469 | Easy | 17,640 |
https://leetcode.com/problems/number-of-equivalent-domino-pairs/discuss/494127/Python-236ms22MB-Solution-(-~97.5100) | class Solution:
def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:
cntlist = [0] * 100
res = 0
for d1, d2 in dominoes:
ds = d1 * 10 + d2 if d1 > d2 else d2 * 10 + d1 # Compute hash keys
tmp = cntlist[ds] # Slight speed improvement
res += tmp # This way is faster than computing nC2
cntlist[ds] = tmp + 1
return res | number-of-equivalent-domino-pairs | Python 236ms/22MB Solution ( ~97.5%/100%) | X_D | 0 | 161 | number of equivalent domino pairs | 1,128 | 0.469 | Easy | 17,641 |
https://leetcode.com/problems/number-of-equivalent-domino-pairs/discuss/405051/Decent-Python-Soution-100-memory-efficient | class Solution:
def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:
domino = []
for x in dominoes:
x.sort()
domino.append(str(x))
m = []
for x in set(domino):
t = domino.count(x)
if t==1:
pass
else:
m.append(t)
sums=0
for t in m:
sums+=t*(t-1)//2
return sums | number-of-equivalent-domino-pairs | Decent Python Soution 100% memory efficient | saffi | 0 | 280 | number of equivalent domino pairs | 1,128 | 0.469 | Easy | 17,642 |
https://leetcode.com/problems/number-of-equivalent-domino-pairs/discuss/341421/Solution-in-Python-3 | class Solution:
def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:
s, D = 0, {}
for d in dominoes:
x = tuple(sorted(d))
if x in D:
D[x] += 1
else:
D[x] = 0
return sum([i*(i+1)//2 for i in list(D.values())])
- Python 3
- Junaid Mansuri | number-of-equivalent-domino-pairs | Solution in Python 3 | junaidmansuri | 0 | 292 | number of equivalent domino pairs | 1,128 | 0.469 | Easy | 17,643 |
https://leetcode.com/problems/shortest-path-with-alternating-colors/discuss/712063/Python-DFS | class Solution:
def shortestAlternatingPaths(self, n, red_edges, blue_edges):
neighbors = [[[], []] for _ in range(n)]
ans = [[0, 0]]+[[2*n, 2*n] for _ in range(n-1)]
for u, v in red_edges: neighbors[u][0].append(v)
for u, v in blue_edges: neighbors[u][1].append(v)
def dfs(u, c, dist):
for v in neighbors[u][c]:
if dist+1<ans[v][c]:
ans[v][c] = dist+1
dfs(v, 1-c, dist+1)
dfs(0, 0, 0)
dfs(0, 1, 0)
return [x if x<2*n else -1 for x in map(min, ans)] | shortest-path-with-alternating-colors | Python DFS | stuxen | 5 | 226 | shortest path with alternating colors | 1,129 | 0.43 | Medium | 17,644 |
https://leetcode.com/problems/shortest-path-with-alternating-colors/discuss/2309280/Python3-BFS-solution | class Solution:
def shortestAlternatingPaths(self, n: int, redEdges: List[List[int]], blueEdges: List[List[int]]) -> List[int]:
edges = {0: defaultdict(list), 1: defaultdict(list)}
for src,dest in redEdges:
edges[0][src].append(dest)
for src,dest in blueEdges:
edges[1][src].append(dest)
queue,result1, result2 = [(0,0,0),(0,1,0)], [float("inf")]*n, [float("inf")]*n
result1[0], result2[0] = 0, 0
while queue:
node, direction, distance = queue.pop(0)
for neighbour in edges[direction][node]:
if direction and result2[neighbour] > distance + 1:
result2[neighbour] = 1 + distance
queue.append((neighbour, 1 - direction, 1 + distance))
elif not direction and result1[neighbour] > distance + 1:
result1[neighbour] = 1 + distance
queue.append((neighbour, 1 - direction, 1 + distance))
for i in range(n):
result1[i] = min(result1[i], result2[i])
if result1[i] == float("inf"):
result1[i] = -1
return result1 | shortest-path-with-alternating-colors | 📌 Python3 BFS solution | Dark_wolf_jss | 1 | 36 | shortest path with alternating colors | 1,129 | 0.43 | Medium | 17,645 |
https://leetcode.com/problems/shortest-path-with-alternating-colors/discuss/2159305/Python3-BFS-with-comments | class Solution:
def shortestAlternatingPaths(self, n: int, redEdges: List[List[int]], blueEdges: List[List[int]]) -> List[int]:
# shortest = BFS
# there can be cycles so alternating paths after a cycle can be different
# tracking visited is not just about the node, also includes the colors
from collections import defaultdict
g = defaultdict(list)
for a, b in redEdges:
g[a].append((b, 'red'))
for u, v in blueEdges:
g[u].append((v, 'blue'))
answer = [-1 for _ in range(n)]
from collections import deque
q = deque([(0, 'red', 0), (0, 'blue', 0)]) # can start from either blue or red. represents node, color, dist
visited = set() # track the nodes we've visited so we don't hit a cycle
# init visited and answer of first node!
visited.add((0, 'red'))
visited.add((0, 'blue'))
answer[0] = 0
while q:
node, color, dist = q.popleft()
for nei, neicolor in g[node]:
if (nei, neicolor) in visited or color == neicolor:
continue
if answer[nei] < 0:
answer[nei] = dist + 1
q.append((nei, neicolor, dist + 1))
visited.add((nei, neicolor))
return answer | shortest-path-with-alternating-colors | Python3 BFS, with comments | normalpersontryingtopayrent | 1 | 44 | shortest path with alternating colors | 1,129 | 0.43 | Medium | 17,646 |
https://leetcode.com/problems/shortest-path-with-alternating-colors/discuss/1491509/Python3-or-BFS-Algo | class Solution:
def shortestAlternatingPaths(self, n: int, red_edges: List[List[int]], blue_edges: List[List[int]]) -> List[int]:
adj=[[] for i in range(n)]
dist=[-1 for i in range(n)]
dist[0]=0
q,vis=[],set()
for i,j in red_edges:
adj[i].append([j,"R"])
for i,j in blue_edges:
adj[i].append([j,"B"])
q.append([0,""])
vis.add((0," "))
lvl=0
while q:
lvl+=1
size=len(q)
for i in range(size):
ele=q.pop(0)
for neigh,color in adj[ele[0]]:
if ele[1]!=color and (neigh,color) not in vis:
if dist[neigh]==-1:
dist[neigh]=lvl
else:
dist[neigh]=min(dist[neigh],lvl)
q.append([neigh,color])
vis.add((neigh,color))
return dist | shortest-path-with-alternating-colors | [Python3] | BFS Algo | swapnilsingh421 | 1 | 109 | shortest path with alternating colors | 1,129 | 0.43 | Medium | 17,647 |
https://leetcode.com/problems/shortest-path-with-alternating-colors/discuss/2640427/Python-BFS | class Solution:
def shortestAlternatingPaths(self, n: int, redEdges: List[List[int]], blueEdges: List[List[int]]) -> List[int]:
distances = [-1 for _ in range(n)]
adjList = {}
adjList[1] = defaultdict(list)
adjList[-1] = defaultdict(list)
for s,d in redEdges:
adjList[1][s].append((d,1))
for s,d in blueEdges:
adjList[-1][s].append((d,-1))
q = [[0,-1,0],[0,1,0]]
visited = set()
while q:
length = len(q)
for _ in range(length):
node,color,distance = q.pop(0)
if distances[node] == -1:
distances[node] = distance
visited.add((node,color))
for nei,_ in adjList[-color][node]:
if (nei,-color) not in visited:
q.append([nei,-color,distance+1])
return distances | shortest-path-with-alternating-colors | Python BFS | gurucharandandyala | 0 | 53 | shortest path with alternating colors | 1,129 | 0.43 | Medium | 17,648 |
https://leetcode.com/problems/shortest-path-with-alternating-colors/discuss/2510271/Python-90-faster-easy | class Solution:
def shortestAlternatingPaths(self, n: int, red: List[List[int]], blue: List[List[int]]) -> List[int]:
graph = defaultdict(list)
# Build graph
for u,v in red:
graph[u].append((v, 1)) # 1 as red
for u, v in blue:
graph[u].append((v, -1)) # -1 as blue
# distance of source always = 0
def bfs():
visited = []
res = [-1] * n
res[0] = 0
q= deque()
q.append([0,1])
q.append([0,-1])
visited.append([0,1])
visited.append([0,-1])
step = 0
while q:
step+=1
for i in range(len(q)):
node, node_color = q.popleft()
for child,child_color in graph[node]:
if child_color == -node_color:
if res[child]==-1:
res[child] = step
if [child,child_color] not in visited:
q.append([child,child_color])
visited.append([child,child_color])
return res
return bfs() | shortest-path-with-alternating-colors | Python 90% faster easy | Abhi_009 | 0 | 25 | shortest path with alternating colors | 1,129 | 0.43 | Medium | 17,649 |
https://leetcode.com/problems/shortest-path-with-alternating-colors/discuss/2502936/python3-BFS-with-color-checks-sol-for-reference. | class Solution:
def shortestAlternatingPaths(self, n: int, redEdges: List[List[int]], blueEdges: List[List[int]]) -> List[int]:
RED = 0
BLUE = 1
graph = defaultdict(lambda: defaultdict(lambda: defaultdict(int)))
for s,e in redEdges:
graph[s][RED][e] = True
if not graph[s][BLUE]:
graph[s][BLUE] = {}
for s,e in blueEdges:
graph[s][BLUE][e] = True
if not graph[s][RED]:
graph[s][RED] = {}
st = [[0, 0, 1],[0, 0, 0]]
visited = {}
dists = [float('inf')]*n
dists[0] = 0
while st:
dist, node, prev = heapq.heappop(st)
for nei in graph[node]:
new_color = 1-prev
for nei in graph[node][new_color]:
if (node, nei, new_color) not in visited:
visited[(node, nei, new_color)] = True
dists[nei] = min(dists[nei], dist + 1)
st.append((dist+1, nei, new_color))
return [i if i != float('inf') else -1 for i in dists] | shortest-path-with-alternating-colors | [python3] BFS with color checks sol for reference. | vadhri_venkat | 0 | 25 | shortest path with alternating colors | 1,129 | 0.43 | Medium | 17,650 |
https://leetcode.com/problems/shortest-path-with-alternating-colors/discuss/2319307/Python3-Intuitive-BFS-with-examples | class Solution:
def shortestAlternatingPaths(self, n: int, redEdges: List[List[int]], blueEdges: List[List[int]]) -> List[int]:
ans=[float('inf')]*(n)
ans[0]=0
graph=defaultdict(list)
for i,j in redEdges:
graph[i].append([j,1,0])
for i,j in blueEdges:
graph[i].append([j,2,0])
queue=deque()
queue.append([0,0,0])
visited=set()
visited.add((0,0))
while queue:
node,color,dist=queue.popleft()
ans[node]=min(ans[node],dist)
for adj,adjColor,_ in graph[node]:
if color!=adjColor and (adj,adjColor) not in visited:
visited.add((adj,adjColor))
queue.append([adj,adjColor,dist+1])
for i in range(len(ans)):
if ans[i]==float('inf'):
ans[i]=-1
return ans | shortest-path-with-alternating-colors | [Python3] Intuitive BFS with examples | _vaishalijain | 0 | 57 | shortest path with alternating colors | 1,129 | 0.43 | Medium | 17,651 |
https://leetcode.com/problems/shortest-path-with-alternating-colors/discuss/2191011/PYTHON-SOL-or-BRUTE-FORCE-TO-OPTIMIZATION-or-FULL-EXPLANATION-or | class Solution:
def shortestAlternatingPaths(self, n: int, redEdges: List[List[int]], blueEdges: List[List[int]]) -> List[int]:
# n = no. of nodes in directed graph -> ( 0 to n - 1 )
# each edge is either red or blue
# there can be self edges and parallel edges
# given two arrays :
# 1. redEdges[i] = [a,b] means there is redEdge from a to b
# 2. blueEdge[i] = [a,b] means there is blueEdge from a to b
# return answer of length n where answer[x] is length of shortest path ..
# from node 0 to node x such that the edge colors alternate along the path ...
# -1 if papth does not exist
canGo = defaultdict(list)
red,blue = {},{}
for i,j in redEdges:
red[(i,j)] = True
canGo[i].append(j)
for i,j in blueEdges:
blue[(i,j)] = True
canGo[i].append(j)
ans =[-1]*n
ans[0] = 0
for target in range(1,n):
queue = [(0,0,None)]
visited = {(0,None):True}
while queue:
node,dis,color = queue.pop(0)
if node == target:
ans[target] = dis
break
for nodes in canGo[node]:
b,r = (node,nodes) in blue, (node,nodes) in red
if color == 1:
# we can go with r
if r == False or (nodes,0) in visited: continue
visited[(nodes,0)] = True
queue.append((nodes,dis+1,0))
elif color == 0:
# we can go with b
if b == False or (nodes,1) in visited: continue
visited[(nodes,1)] = True
queue.append((nodes,dis+1,1))
else:
# we can go with any of them
if r == True and (nodes,0) not in visited:
visited[(nodes,0)] = True
queue.append((nodes,dis+1,0))
if b == True and (nodes,1) not in visited:
visited[(nodes,1)] = True
queue.append((nodes,dis+1,1))
return ans | shortest-path-with-alternating-colors | PYTHON SOL | BRUTE FORCE TO OPTIMIZATION | FULL EXPLANATION | | reaper_27 | 0 | 99 | shortest path with alternating colors | 1,129 | 0.43 | Medium | 17,652 |
https://leetcode.com/problems/shortest-path-with-alternating-colors/discuss/2191011/PYTHON-SOL-or-BRUTE-FORCE-TO-OPTIMIZATION-or-FULL-EXPLANATION-or | class Solution:
def shortestAlternatingPaths(self, n: int, redEdges: List[List[int]], blueEdges: List[List[int]]) -> List[int]:
canGo = defaultdict(list)
red,blue = {},{}
for i,j in redEdges:
red[(i,j)] = True
canGo[i].append(j)
for i,j in blueEdges:
blue[(i,j)] = True
canGo[i].append(j)
ans =[-1]*n
heap = [(0,0,None)]
visited = {(0,None): True}
while heap:
dis,node,color = heapq.heappop(heap)
if ans[node] == -1: ans[node] = dis
for adj in canGo[node]:
r,b = (node,adj) in red ,(node,adj) in blue
if color == 0:
# we can go via blue
if b == False or (adj,1) in visited: continue
visited[(adj,1)] = True
heapq.heappush(heap,(dis+1,adj,1))
elif color == 1:
# we can go via red
if r == False or (adj,0) in visited: continue
visited[(adj,0)] = True
heapq.heappush(heap,(dis+1,adj,0))
else:
# can go via both red and blue
if b == True and (adj,1) not in visited:
visited[(adj,1)] = True
heapq.heappush(heap,(dis+1,adj,1))
if r == True and (adj,0) not in visited:
visited[(adj,0)] = True
heapq.heappush(heap,(dis+1,adj,0))
return ans | shortest-path-with-alternating-colors | PYTHON SOL | BRUTE FORCE TO OPTIMIZATION | FULL EXPLANATION | | reaper_27 | 0 | 99 | shortest path with alternating colors | 1,129 | 0.43 | Medium | 17,653 |
https://leetcode.com/problems/shortest-path-with-alternating-colors/discuss/2125899/Python-or-BFS-or-XOR-or-Faster-than-98-or-Memory-97 | class Solution:
def shortestAlternatingPaths(self, n: int, redEdges: List[List[int]], blueEdges: List[List[int]]) -> List[int]:
# Lists: Color x node
graph = [[[] for _ in range(n)] for _ in range(2)]
seen = [[False] * n for _ in range(2)]
res = [-1] * n
q = deque([(0,0,0), (0,1,0)])
# Phase 1: Build the graph
# Red: color=0
# Blue: color=1
for e in redEdges:
graph[0][e[0]].append(e[1])
for e in blueEdges:
graph[1][e[0]].append(e[1])
# Phase 2: BFS
while q:
node, color, step = q.popleft()
# Record minimum step when visiting a node 1st time
if res[node] == -1:
res[node] = step
# Switch color
color ^= 1
for n in graph[color][node]:
if not seen[color][n]:
seen[color][n] = True
q.append((n, color, step+1))
return res | shortest-path-with-alternating-colors | Python | BFS | XOR | Faster than 98% | Memory 97% | slbteam08 | 0 | 37 | shortest path with alternating colors | 1,129 | 0.43 | Medium | 17,654 |
https://leetcode.com/problems/shortest-path-with-alternating-colors/discuss/1168948/Python3-bfs | class Solution:
def shortestAlternatingPaths(self, n: int, red_edges: List[List[int]], blue_edges: List[List[int]]) -> List[int]:
graph = {}
for u, v in red_edges: graph.setdefault(u, []).append((v, 0))
for u, v in blue_edges: graph.setdefault(u, []).append((v, 1))
queue = [(0, -1)]
dist = [[inf]*2 for _ in range(n)]
k = 0
while queue:
newq = []
for n, c in queue:
if dist[n][c] > k:
dist[n][c] = k
for nn, cc in graph.get(n, []):
if cc != c: newq.append((nn, cc))
queue = newq
k += 1
return [x if x < inf else -1 for x in map(min, dist)] | shortest-path-with-alternating-colors | [Python3] bfs | ye15 | 0 | 102 | shortest path with alternating colors | 1,129 | 0.43 | Medium | 17,655 |
https://leetcode.com/problems/shortest-path-with-alternating-colors/discuss/1029224/python-code-but-downvote-this-please | class Solution:
def shortestAlternatingPaths(self, n: int, red_edges: List[List[int]], blue_edges: List[List[int]]) -> List[int]:
red_adjList = self.createAdjList(red_edges)
blue_adjList = self.createAdjList(blue_edges)
q = deque([(0, 'red'), (0, 'blue')])
shortest_paths = [float('inf')]*n
level = 0
visited = set([])
while q:
for _ in range(len(q)):
cur_num, cur_color = q.popleft()
opposite_color = 'red' if cur_color == 'blue' else 'blue'
# update shortest path for cur_num if level is less than
# shortest_paths[cur_num]
shortest_paths[cur_num] = min(level, shortest_paths[cur_num])
if opposite_color == "red" and (opposite_color, cur_num) not in visited:
visited.add((opposite_color, cur_num))
neighbors = blue_adjList[cur_num]
for child in neighbors:
q.append((child, opposite_color))
if opposite_color == "blue" and (opposite_color, cur_num) not in visited:
visited.add((opposite_color, cur_num))
neighbors = red_adjList[cur_num]
for child in neighbors:
q.append((child, opposite_color))
level+=1
return [x if x != float('inf') else -1 for x in shortest_paths ]
def createAdjList(self, edges):
adjList = defaultdict(list)
for i, j in edges:
adjList[i].append(j)
return adjList | shortest-path-with-alternating-colors | python code but downvote this please | Skywalker5423 | -4 | 129 | shortest path with alternating colors | 1,129 | 0.43 | Medium | 17,656 |
https://leetcode.com/problems/minimum-cost-tree-from-leaf-values/discuss/1510611/Greedy-Approach-oror-97-faster-oror-Well-Explained | class Solution:
def mctFromLeafValues(self, arr: List[int]) -> int:
arr = [float('inf')] + arr + [float('inf')]
n, res = len(arr), 0
while n>3:
mi = min(arr)
ind = arr.index(mi)
if arr[ind-1]<arr[ind+1]:
res+=arr[ind-1]*arr[ind]
else:
res+=arr[ind+1]*arr[ind]
arr.remove(mi)
n = len(arr)
return res | minimum-cost-tree-from-leaf-values | 📌📌 Greedy-Approach || 97% faster || Well-Explained 🐍 | abhi9Rai | 21 | 769 | minimum cost tree from leaf values | 1,130 | 0.685 | Medium | 17,657 |
https://leetcode.com/problems/minimum-cost-tree-from-leaf-values/discuss/520825/Python3-a-greedy-algo | class Solution:
def mctFromLeafValues(self, arr: List[int]) -> int:
ans = 0
while len(arr) > 1:
i = arr.index(min(arr))
ans += arr.pop(i)*min(arr[max(0,i-1):i+1])
return ans | minimum-cost-tree-from-leaf-values | [Python3] a greedy algo | ye15 | 4 | 433 | minimum cost tree from leaf values | 1,130 | 0.685 | Medium | 17,658 |
https://leetcode.com/problems/minimum-cost-tree-from-leaf-values/discuss/520825/Python3-a-greedy-algo | class Solution:
def mctFromLeafValues(self, arr: List[int]) -> int:
ans = 0
stack = []
for x in arr:
while stack and stack[-1] <= x:
val = stack.pop()
ans += val * min(stack[-1] if stack else inf, x)
stack.append(x)
return ans + sum(stack[i-1]*stack[i] for i in range(1, len(stack))) | minimum-cost-tree-from-leaf-values | [Python3] a greedy algo | ye15 | 4 | 433 | minimum cost tree from leaf values | 1,130 | 0.685 | Medium | 17,659 |
https://leetcode.com/problems/minimum-cost-tree-from-leaf-values/discuss/2214041/PYTHON-or-EXPLAINED-WITH-PICTURES-or-DP-or-TABULATION-or-INTUITIVE-or | class Solution:
def mctFromLeafValues(self, arr: List[int]) -> int:
n = len(arr)
d = {}
def findMax(start,end):
if (start,end) in d: return d[(start,end)]
maxx = start
for i in range(start+1,end+1):
if arr[maxx] < arr[i] : maxx = i
d[(start,end)] = arr[maxx]
return arr[maxx]
dp = [[float('inf') for i in range(n)] for j in range(n)]
for gap in range(n):
for row in range(n - gap):
col = row + gap
if gap == 0:
dp[row][col] = 0
elif gap == 1:
dp[row][col] = arr[row] * arr[col]
else:
for k in range(row,col):
val = dp[row][k] + findMax(row,k) * findMax(k+1,col) + dp[k+1][col]
if val < dp[row][col]: dp[row][col] = val
return dp[0][-1] | minimum-cost-tree-from-leaf-values | PYTHON | EXPLAINED WITH PICTURES | DP | TABULATION | INTUITIVE | | reaper_27 | 2 | 166 | minimum cost tree from leaf values | 1,130 | 0.685 | Medium | 17,660 |
https://leetcode.com/problems/minimum-cost-tree-from-leaf-values/discuss/2827616/Python-(Simple-DP) | class Solution:
def mctFromLeafValues(self, arr):
@lru_cache(None)
def dfs(i,j):
if j<=i:
return 0
res = float("inf")
for k in range(i+1,j+1):
res = min(res,dfs(i,k-1) + dfs(k,j) + max(arr[i:k])*max(arr[k:j+1]))
return res
return dfs(0,len(arr)-1) | minimum-cost-tree-from-leaf-values | Python (Simple DP) | rnotappl | 0 | 1 | minimum cost tree from leaf values | 1,130 | 0.685 | Medium | 17,661 |
https://leetcode.com/problems/minimum-cost-tree-from-leaf-values/discuss/2360268/Python3-Solution-with-using-greedy | class Solution:
def mctFromLeafValues(self, arr: List[int]) -> int:
res = 0
while len(arr) > 1:
index = arr.index(min(arr))
if 0 < index < len(arr) - 1:
res += arr[index] * min(arr[index - 1], arr[index + 1])
else:
res += arr[index] * arr[index + 1] if index == 0 else arr[index] * arr[index - 1]
arr.pop(index)
return res | minimum-cost-tree-from-leaf-values | [Python3] Solution with using greedy | maosipov11 | 0 | 43 | minimum cost tree from leaf values | 1,130 | 0.685 | Medium | 17,662 |
https://leetcode.com/problems/minimum-cost-tree-from-leaf-values/discuss/1418861/PYTHON3-DFS-SOLUTION | class Solution:
def mctFromLeafValues(self, arr: List[int]) -> int:
# creating an 2-D array to store values that are already occurred
dp = [[0 for i in range(len(arr))] for j in range(len(arr))]
def DFS(arr, left, right):
if dp[left][right]:
return dp[left][right]
# this will help in break when array length is 1
if left == right:
return 0
max_ = float("inf")
for i in range(left, right):
# max value of left list
left_max = max(arr[left : i + 1])
# max value of right list
right_max = max(arr[i + 1 : right + 1])
# iteration over left array
left_sum = DFS(arr, left, i)
# iteration over right array
right_sum = DFS(arr, i + 1, right)
max_ = min(max_, left_max * right_max + left_sum + right_sum)
dp[left][right] = max_
return max_
return DFS(arr, 0, len(arr) - 1) | minimum-cost-tree-from-leaf-values | PYTHON3 DFS SOLUTION | _shubham28 | 0 | 270 | minimum cost tree from leaf values | 1,130 | 0.685 | Medium | 17,663 |
https://leetcode.com/problems/minimum-cost-tree-from-leaf-values/discuss/938873/Simple-DP-Python-Solution | class Solution:
def __init__(self):
self.m={}
def mctFromLeafValues(self, arr: List[int]) -> int:
def find_max(st,end,arr):
if arr[st:end+1]==[]:
return 0
return max(arr[st:end+1])
def helper(st,en,arr):
if st==en:
self.m[str(st)+" "+str(en)]=0
return 0
if (en-st)==1:
self.m[str(st)+" "+str(en)]=arr[st]*arr[en]
return arr[st]*arr[en]
if str(st)+" "+str(en) in self.m:
return self.m[str(st)+" "+str(en)]
ans=float("inf")
for i in range(st,en):
a=find_max(st,i,arr)
b=find_max(i+1,en,arr)
temp=helper(st,i,arr)+helper(i+1,en,arr)
ans=min(ans,temp+(a*b))
self.m[str(st)+" "+str(en)]=ans
return ans
return helper(0,len(arr)-1,arr) | minimum-cost-tree-from-leaf-values | Simple DP Python Solution | Ayu-99 | 0 | 312 | minimum cost tree from leaf values | 1,130 | 0.685 | Medium | 17,664 |
https://leetcode.com/problems/maximum-of-absolute-value-expression/discuss/1835078/Python-3-or-O(n)O(1) | class Solution:
def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:
minA = minB = minC = minD = math.inf
maxA = maxB = maxC = maxD = -math.inf
for i, (num1, num2) in enumerate(zip(arr1, arr2)):
minA = min(minA, i + num1 + num2)
maxA = max(maxA, i + num1 + num2)
minB = min(minB, i + num1 - num2)
maxB = max(maxB, i + num1 - num2)
minC = min(minC, i - num1 + num2)
maxC = max(maxC, i - num1 + num2)
minD = min(minD, i - num1 - num2)
maxD = max(maxD, i - num1 - num2)
return max(maxA - minA, maxB - minB,
maxC - minC, maxD - minD) | maximum-of-absolute-value-expression | Python 3 | O(n)/O(1) | dereky4 | 2 | 322 | maximum of absolute value expression | 1,131 | 0.494 | Medium | 17,665 |
https://leetcode.com/problems/maximum-of-absolute-value-expression/discuss/2839641/Easy-Python-and-Beats-96-along-with-explanation | class Solution:
def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:
'''
|a1[i]-a1[j]| + |a2[i]-a2[j]| + |i-j|
total 2(+ or -)**(no. of modules) == 2**3 cases
--> a1[i]-a1[j]+a2[i]-a2[j]+i-j
== (a1[i]+a2[i]+i) - (a1[j]+a2[j]+j)
--> a1[i]-a1[j]+a2[i]-a2[j]-i-j
== (a1[i]+a2[i]-i) - (a1[j]+a2[j]-j)
...etc
'''
val1,val2,val3,val4=[],[],[],[]
for i in range(len(arr1)):
val1.append(i+arr1[i]+arr2[i])
val2.append(i+arr1[i]-arr2[i])
val3.append(i-arr1[i]+arr2[i])
val4.append(i-arr1[i]-arr2[i])
ans=0
ans=max(ans,max(val1)-min(val1))
ans=max(ans,max(val2)-min(val2))
ans=max(ans,max(val3)-min(val3))
ans=max(ans,max(val4)-min(val4))
return ans | maximum-of-absolute-value-expression | Easy Python and Beats 96% along with explanation | shileshkumar | 0 | 1 | maximum of absolute value expression | 1,131 | 0.494 | Medium | 17,666 |
https://leetcode.com/problems/maximum-of-absolute-value-expression/discuss/2728740/Easy-Python-approach | class Solution:
def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:
A=[]
B=[]
C=[]
D=[]
n=len(arr1)
for i in range(n):
A.append(arr1[i]+arr2[i]+i)
B.append(arr1[i]+arr2[i]-i)
C.append(arr1[i]-arr2[i]+i)
D.append(arr1[i]-arr2[i]-i)
a=max(A)-min(A)
b=max(B)-min(B)
c=max(C)-min(C)
d=max(D)-min(D)
return max(a,b,c,d) | maximum-of-absolute-value-expression | Easy Python approach | DhruvBagrecha | 0 | 2 | maximum of absolute value expression | 1,131 | 0.494 | Medium | 17,667 |
https://leetcode.com/problems/maximum-of-absolute-value-expression/discuss/1168974/Python3-linear-sweep | class Solution:
def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:
ans = 0
for p, q in (1, 1), (1, -1), (-1, 1), (-1, -1):
val = low = inf
for i, (x, y) in enumerate(zip(arr1, arr2)):
ans = max(ans, p*x + q*y + i - low)
low = min(low, p*x + q*y + i)
return ans | maximum-of-absolute-value-expression | [Python3] linear sweep | ye15 | 0 | 327 | maximum of absolute value expression | 1,131 | 0.494 | Medium | 17,668 |
https://leetcode.com/problems/maximum-of-absolute-value-expression/discuss/341833/Solution-in-Python-3 | class Solution:
def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:
M = 0
for c in [[1,1],[1,-1],[-1,1],[-1,-1]]:
m = float('inf')
for i in [arr1[i]*c[0]+arr2[i]*c[1]+i for i in range(len(arr1))]:
if i < m: m = i
if i - m > M: M = i - m
return M
- Python 3
- Junaid Mansuri | maximum-of-absolute-value-expression | Solution in Python 3 | junaidmansuri | 0 | 477 | maximum of absolute value expression | 1,131 | 0.494 | Medium | 17,669 |
https://leetcode.com/problems/n-th-tribonacci-number/discuss/350547/Solution-in-Python-3-(beats-~100) | class Solution:
def tribonacci(self, n: int) -> int:
a, b, c = 0, 1, 1
for i in range(n): a, b, c = b, c, a + b + c
return a
- Junaid Mansuri | n-th-tribonacci-number | Solution in Python 3 (beats ~100%) | junaidmansuri | 14 | 1,600 | n th tribonacci number | 1,137 | 0.633 | Easy | 17,670 |
https://leetcode.com/problems/n-th-tribonacci-number/discuss/2614221/93-Faster-Solution-or-4-Different-Approach-or-Python | class Solution(object):
def sol(self, n, dp):
if n == 0: return 0
if n == 1 or n == 2: return 1
if dp[n] != 0: return dp[n]
dp[n] = self.sol(n - 1, dp) + self.sol(n - 2, dp) + self.sol(n - 3, dp)
return dp[n]
def tribonacci(self, n):
dp = [0] * (n + 1)
return self.sol(n, dp) | n-th-tribonacci-number | 93% Faster Solution | 4 Different Approach | Python | its_krish_here | 13 | 460 | n th tribonacci number | 1,137 | 0.633 | Easy | 17,671 |
https://leetcode.com/problems/n-th-tribonacci-number/discuss/1416952/Python-oror-Easy-Solution-oror-beat-~99 | class Solution:
def tribonacci(self, n: int) -> int:
lst = [-1 for i in range(n + 1)]
def fun(n):
if n == 0:
return 0
if n == 1:
return 1
if n == 2:
return 1
if lst[n] == -1:
lst[n] = fun(n - 1) + fun(n - 2) + fun(n - 3)
return lst[n]
return fun(n) | n-th-tribonacci-number | Python || Easy Solution || beat ~99 % | naveenrathore | 4 | 209 | n th tribonacci number | 1,137 | 0.633 | Easy | 17,672 |
https://leetcode.com/problems/n-th-tribonacci-number/discuss/2570259/Python-Elegant-and-Short-or-Recursive-Iterative-or-LRU-cache | class Solution:
"""
Time: O(n)
Memory: O(n)
"""
@lru_cache(maxsize=None)
def tribonacci(self, n: int) -> int:
if n < 1:
return 0
if n < 3:
return 1
return self.tribonacci(n - 1) + self.tribonacci(n - 2) + self.tribonacci(n - 3)
class Solution:
"""
Time: O(n)
Memory: O(1)
"""
def tribonacci(self, n: int) -> int:
a, b, c = 0, 1, 1
for _ in range(n):
a, b, c = b, c, a + b + c
return a | n-th-tribonacci-number | Python Elegant & Short | Recursive / Iterative | LRU-cache | Kyrylo-Ktl | 3 | 121 | n th tribonacci number | 1,137 | 0.633 | Easy | 17,673 |
https://leetcode.com/problems/n-th-tribonacci-number/discuss/391787/Python-Better-than-100-space-and-89-time | class Solution:
def tribonacci(self, n: int) -> int:
memo = [0, 1, 1]
if n < 2:
return memo[n]
for i in range(2,n):
memo.append(memo[-1] + memo[-2] + memo[-3])
return memo[-1] | n-th-tribonacci-number | Python - Better than 100% space and 89% time | stevogabe7 | 2 | 318 | n th tribonacci number | 1,137 | 0.633 | Easy | 17,674 |
https://leetcode.com/problems/n-th-tribonacci-number/discuss/2217670/Iterative-Python-or-95 | class Solution:
def tribonacci(self, n: int) -> int:
if n==0 or n==1:
return n
if n==2:
return 1
dp = [0 for i in range(n+1)]
dp[0] = 0
dp[1] = 1
dp[2] = 1
idx=3
while idx<=n:
dp[idx] = dp[idx-1] + dp[idx-2] + dp[idx-3]
idx+=1
return dp[n] | n-th-tribonacci-number | Iterative Python | 95% | bliqlegend | 1 | 59 | n th tribonacci number | 1,137 | 0.633 | Easy | 17,675 |
https://leetcode.com/problems/n-th-tribonacci-number/discuss/1844992/Python-Dp-with-Memoization | class Solution:
dic = {}
def tribonacci(self, n: int) -> int:
if(n<=0):
return 0
if(n==1 or n==2):
return 1
if(n in self.dic):
return self.dic[n]
else:
self.dic[n] = self.tribonacci(n-3) + self.tribonacci(n-2) + self.tribonacci(n-1)
return self.tribonacci(n-3) + self.tribonacci(n-2) + self.tribonacci(n-1) | n-th-tribonacci-number | [Python] Dp with Memoization | kevin_thelly | 1 | 106 | n th tribonacci number | 1,137 | 0.633 | Easy | 17,676 |
https://leetcode.com/problems/n-th-tribonacci-number/discuss/1815490/Python3-or-Bottom-Up-Approach | class Solution:
def tribonacci(self, n: int) -> int:
if n==0: return 0
if n==1 or n==2: return 1
c=[0,1,1]
i=1
while i<n-1:
c.append(c[-1]+c[-2]+c[-3])
i+=1
return c[-1] | n-th-tribonacci-number | Python3 | Bottom-Up Approach | Anilchouhan181 | 1 | 63 | n th tribonacci number | 1,137 | 0.633 | Easy | 17,677 |
https://leetcode.com/problems/n-th-tribonacci-number/discuss/1752005/C%2B%2B-Java-Python3-Simple-DP-Solution-(Top-Down-and-Bottom-Up) | class Solution:
def tribonacci(self, n: int) -> int:
def dp(n: int) -> int:
if n == 0:
return 0
if n == 1:
return 1
if n == 2:
return 1
if n not in memo:
memo[n] = dp(n-1)+dp(n-2) + dp(n-3)
return memo[n]
memo = {}
return dp(n) | n-th-tribonacci-number | ✅ [C++ / Java / Python3] Simple DP Solution (Top-Down & Bottom-Up) | JawadNoor | 1 | 59 | n th tribonacci number | 1,137 | 0.633 | Easy | 17,678 |
https://leetcode.com/problems/n-th-tribonacci-number/discuss/1752005/C%2B%2B-Java-Python3-Simple-DP-Solution-(Top-Down-and-Bottom-Up) | class Solution:
def tribonacci(self, n: int) -> int:
result = []
result.append(0)
result.append(1)
result.append(1)
if n < 3:
return result[n]
else:
for i in range(3, n+1):
result.append(result[i-3]+result[i-2]+result[i-1])
return result[n] | n-th-tribonacci-number | ✅ [C++ / Java / Python3] Simple DP Solution (Top-Down & Bottom-Up) | JawadNoor | 1 | 59 | n th tribonacci number | 1,137 | 0.633 | Easy | 17,679 |
https://leetcode.com/problems/n-th-tribonacci-number/discuss/1539560/Python-2-Method-to-Solve-this-Problem | class Solution:
def tribonacci(self, n: int) -> int:
first, second, third = 0, 1, 1
for _ in range(n):
first, second, third = second, third, first + second + third
else:
return first | n-th-tribonacci-number | Python 2 Method to Solve this Problem | aaffriya | 1 | 82 | n th tribonacci number | 1,137 | 0.633 | Easy | 17,680 |
https://leetcode.com/problems/n-th-tribonacci-number/discuss/1539560/Python-2-Method-to-Solve-this-Problem | class Solution:
def tribonacci(self, n: int) -> int:
if n < 2: return n
elif n == 2 : return 1
f = list((0, 1, 1))
for x in range(2, n):
f.append(f[-1] + f[-2] + f[-3])
else:
return f[-1] | n-th-tribonacci-number | Python 2 Method to Solve this Problem | aaffriya | 1 | 82 | n th tribonacci number | 1,137 | 0.633 | Easy | 17,681 |
https://leetcode.com/problems/n-th-tribonacci-number/discuss/1483405/Python-4-lines | class Solution:
def tribonacci(self, n: int) -> int:
arr = [0, 1, 1]
if n <= 2: return arr[n]
for i in range(2, n): arr.append(sum(arr[-3:]))
return arr[-1] | n-th-tribonacci-number | Python 4 lines | SmittyWerbenjagermanjensen | 1 | 83 | n th tribonacci number | 1,137 | 0.633 | Easy | 17,682 |
https://leetcode.com/problems/n-th-tribonacci-number/discuss/1483007/Simple-oror-94-faster-oror-Easy-to-Understand | class Solution:
def tribonacci(self, n: int) -> int:
a,b,c = 0,1,1
if n==0: return a
if n==1: return b
if n==2: return c
for i in range(3,n+1):
tmp=a+b+c
a,b,c = b,c,tmp
return c | n-th-tribonacci-number | 📌📌 Simple || 94% faster || Easy-to-Understand 🐍 | abhi9Rai | 1 | 145 | n th tribonacci number | 1,137 | 0.633 | Easy | 17,683 |
https://leetcode.com/problems/n-th-tribonacci-number/discuss/1483007/Simple-oror-94-faster-oror-Easy-to-Understand | class Solution:
def tribonacci(self, n: int) -> int:
dp=dict()
dp[0]=0
dp[1]=1
dp[2]=1
def recur(n):
if n in dp:
return dp[n]
dp[n] = recur(n-1)+recur(n-2)+recur(n-3)
return dp[n]
return recur(n) | n-th-tribonacci-number | 📌📌 Simple || 94% faster || Easy-to-Understand 🐍 | abhi9Rai | 1 | 145 | n th tribonacci number | 1,137 | 0.633 | Easy | 17,684 |
https://leetcode.com/problems/n-th-tribonacci-number/discuss/512508/Python3-top-downbottom-up-DP-and-formula | class Solution:
def tribonacci(self, n: int, memo = dict()) -> int:
if n in memo: return memo[n]
if n < 2: memo[n] = n
elif n == 2: memo[n] = 1
else: memo[n] = self.tribonacci(n-1, memo) + self.tribonacci(n-2, memo) + self.tribonacci(n-3, memo)
return memo[n] | n-th-tribonacci-number | [Python3] top-down/bottom-up DP & formula | ye15 | 1 | 62 | n th tribonacci number | 1,137 | 0.633 | Easy | 17,685 |
https://leetcode.com/problems/n-th-tribonacci-number/discuss/512508/Python3-top-downbottom-up-DP-and-formula | class Solution:
def tribonacci(self, n: int) -> int:
t0, t1, t2 = 0, 1, 1
for i in range(n):
t0, t1, t2 = t1, t2, t0+t1+t2
return t0 | n-th-tribonacci-number | [Python3] top-down/bottom-up DP & formula | ye15 | 1 | 62 | n th tribonacci number | 1,137 | 0.633 | Easy | 17,686 |
https://leetcode.com/problems/n-th-tribonacci-number/discuss/512508/Python3-top-downbottom-up-DP-and-formula | class Solution:
def tribonacci(self, n: int, memo = dict()) -> int:
a0 = (19 + 3*33**0.5)**(1/3)
a1 = (19 - 3*33**0.5)**(1/3)
b = (586 + 102*33**0.5)**(1/3)
return round(3*b*((a0+a1+1)/3)**n/(b**2-2*b+4)) | n-th-tribonacci-number | [Python3] top-down/bottom-up DP & formula | ye15 | 1 | 62 | n th tribonacci number | 1,137 | 0.633 | Easy | 17,687 |
https://leetcode.com/problems/n-th-tribonacci-number/discuss/2846219/python-solution | class Solution:
def tribonacci(self, n: int) -> int:
if n ==0:
return 0
if n==1 or n==2 :
return 1
arr = [None]*(n+1)
arr[0] = 0
arr[1]=arr[2]=1
for i in range(3,n+1):
arr[i] = arr[i-2] + arr[i-1]+arr[i-3]
return arr[n] | n-th-tribonacci-number | python solution | Cosmodude | 0 | 2 | n th tribonacci number | 1,137 | 0.633 | Easy | 17,688 |
https://leetcode.com/problems/n-th-tribonacci-number/discuss/2841668/Easy-Solution-using-DP-Time-%3A-O(n)-Space-%3A-O(1) | class Solution:
def tribonacci(self, n: int) -> int:
if n <= 2:
if n !=2 :
return n
return 1
prev1, prev2, prev3 = 1, 1, 0
for _ in range(3, n+1):
curr = prev1 + prev2 + prev3
prev3 = prev2
prev2 = prev1
prev1 = curr
return curr | n-th-tribonacci-number | Easy Solution using DP [Time : O(n) Space : O(1)] | godabauday | 0 | 3 | n th tribonacci number | 1,137 | 0.633 | Easy | 17,689 |
https://leetcode.com/problems/n-th-tribonacci-number/discuss/2802074/Python3-or-1137.-N-th-Tribonacci-Number | class Solution:
memo = {}
def tribonacci(self, n: int) -> int:
if(n == 0):
return 0
elif(n == 1 or n==2):
return 1
elif(n in self.memo):
return self.memo[n]
self.memo[n] = self.tribonacci(n-3) + self.tribonacci(n-2) + self.tribonacci(n-1)
return self.memo[n] | n-th-tribonacci-number | Python3 | 1137. N-th Tribonacci Number | AndrewMitchell25 | 0 | 2 | n th tribonacci number | 1,137 | 0.633 | Easy | 17,690 |
https://leetcode.com/problems/n-th-tribonacci-number/discuss/2780523/Simple-dynamic-programming | class Solution:
def tribonacci(self, n: int) -> int:
if n == 0:
return 0
elif n == 1:
return 1
elif n == 2:
return 1
t_0 = 0
t_1 = 1
t_2 = 1
for _ in range(3, n + 1):
t_0, t_1, t_2 = t_1, t_2, t_0 + t_1 + t_2
return t_2 | n-th-tribonacci-number | Simple dynamic programming | macGregor | 0 | 2 | n th tribonacci number | 1,137 | 0.633 | Easy | 17,691 |
https://leetcode.com/problems/n-th-tribonacci-number/discuss/2764174/Python-DP-beats-96 | class Solution:
def tribonacci(self, n: int) -> int:
dp = [0,1,1]
for i in range(2,n+2):
dp.append(dp[i-2]+dp[i-1]+dp[i])
return dp[n] | n-th-tribonacci-number | Python DP beats 96% | Vivek_Pandith | 0 | 3 | n th tribonacci number | 1,137 | 0.633 | Easy | 17,692 |
https://leetcode.com/problems/n-th-tribonacci-number/discuss/2727127/Memoization-using-%22queue%22-type-list | class Solution:
def tribonacci(self, n: int) -> int:
mem = [0,1,1]
if n < 3:
return mem[n]
n -= 3
while n >= 0:
mem.append(mem.pop(0) + mem[0] + mem[1])
n -= 1
return mem[2] | n-th-tribonacci-number | Memoization using "queue" type list | Gideontz | 0 | 1 | n th tribonacci number | 1,137 | 0.633 | Easy | 17,693 |
https://leetcode.com/problems/n-th-tribonacci-number/discuss/2704257/Python-!-DP-!-Simple-Solution | class Solution:
def tribonacci(self, n: int) -> int:
if not n: return 0
dp = [0,1,1]
for _ in range(2,n):
dp.append(sum(dp))
dp.pop(0)
return dp[-1] | n-th-tribonacci-number | Python ! DP ! Simple Solution | w7Pratham | 0 | 3 | n th tribonacci number | 1,137 | 0.633 | Easy | 17,694 |
https://leetcode.com/problems/n-th-tribonacci-number/discuss/2664909/Easy-Python-solution | class Solution:
def tribonacci(self, n: int) -> int:
if n < 2:
return n
elif n > 1 and n < 4:
return n-1
else:
ans = [0,1,1]
for i in range(3, n+1):
ans.append(ans[i-1] + ans[i-2] + ans[i-3])
return ans[-1] | n-th-tribonacci-number | Easy Python solution | code_snow | 0 | 12 | n th tribonacci number | 1,137 | 0.633 | Easy | 17,695 |
https://leetcode.com/problems/n-th-tribonacci-number/discuss/2655965/here-is-my-solution-greatergreater%3A) | class Solution:
l=[-1]*38
def tribonacci(self, n: int) -> int:
if n<=1:
return n
elif n==2:
return 1
else:
if self.l[n]!=-1:
return self.l[n]
else:
self.l[n]=self.tribonacci(n-1)+self.tribonacci(n-2)+self.tribonacci(n-3)
return self.l[n] | n-th-tribonacci-number | here is my solution->>:) | re__fresh | 0 | 1 | n th tribonacci number | 1,137 | 0.633 | Easy | 17,696 |
https://leetcode.com/problems/n-th-tribonacci-number/discuss/2650301/Tribonacci-Number-oror-easy-python-solution | class Solution:
def cac(self,n,dp):
if(dp[n]!=-1):
return dp[n]
if(n<=1):
dp[n]=n
return dp[n]
if(n==2):
dp[n]=1
return dp[n]
l=self.cac(n-1,dp)
if(n>1):
m=self.cac(n-2,dp)
if(n>2):
r=self.cac(n-3,dp)
dp[n]=l+m+r
return dp[n]
def tribonacci(self, n: int) -> int:
dp=[-1]*(n+1)
k=self.cac(n,dp)
return k | n-th-tribonacci-number | Tribonacci Number || easy python solution | Kiran_Rokkam | 0 | 1 | n th tribonacci number | 1,137 | 0.633 | Easy | 17,697 |
https://leetcode.com/problems/n-th-tribonacci-number/discuss/2645962/SIMPLE-SOLUTION-USING-DP-IN-PYTHON | class Solution:
def tribonacci(self, n: int) -> int:
if n==0 or n==1:
return n
elif n==2:
return 1
else:
t=[0]*(n+1)
t[1]=1
t[2]=1
for i in range(3,n+1):
t[i]=t[i-1]+t[i-2]+t[i-3]
return t[n] | n-th-tribonacci-number | SIMPLE SOLUTION USING DP IN PYTHON | aharshit | 0 | 1 | n th tribonacci number | 1,137 | 0.633 | Easy | 17,698 |
https://leetcode.com/problems/n-th-tribonacci-number/discuss/2586403/Python-Solution-or-Three-Element-List-DP-or-Simple-Logic | class Solution:
def __init__(self):
self.store = {}
def tribonacci(self, n: int) -> int:
def solve(n):
if n in self.store:
return self.store[n]
dp = [0, 1, 1]
for i in range(3, n + 1):
dp[i % 3] = sum(dp)
self.store[n] = dp[n%3]
return dp[n%3]
return solve(n) | n-th-tribonacci-number | Python Solution | Three Element List DP | Simple Logic | Gautam_ProMax | 0 | 16 | n th tribonacci number | 1,137 | 0.633 | Easy | 17,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.