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:
... | 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:
... | 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()... | 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 ... | 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
... | 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)
... | 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:
... | 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... | 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 = c... | 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:
... | 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... | 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)
... | 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... | 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.fi... | 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... | 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... | 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
wh... | 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+... | 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 :
... | 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 ... | 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:
... | 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... | 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:
... | 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... | 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 a... | 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... | 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:
... | 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(... | 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:
... | 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:
mappi... | 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
retur... | 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 ... | 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)
d... | 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:
... | 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
... | 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"])
f... | 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 red... | 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 ... | 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] = T... | 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... | 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 :
... | 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:
... | 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([(... | 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 = [... | 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 = se... | 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:
... | 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 an... | 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
... | 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]))
retur... | 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:
... | 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]
... | 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):
... | 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... | 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]... | 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.a... | 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 = ... | 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 ... | 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)
ret... | 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 tribonacc... | 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... | 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... | 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)
... | 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])
... | 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... | 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
... | 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)
... | 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
... | 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.tri... | 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=... | 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(... | 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.