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/find-all-people-with-secret/discuss/1599870/Python3-BFS-or-DFS-by-group | class Solution:
def findAllPeople(self, n: int, meetings: List[List[int]], firstPerson: int) -> List[int]:
can = {0, firstPerson}
for _, grp in groupby(sorted(meetings, key=lambda x: x[2]), key=lambda x: x[2]):
queue = set()
graph = defaultdict(list)
for x, y, _ in grp:
graph[x].append(y)
graph[y].append(x)
if x in can: queue.add(x)
if y in can: queue.add(y)
queue = deque(queue)
while queue:
x = queue.popleft()
for y in graph[x]:
if y not in can:
can.add(y)
queue.append(y)
return can | find-all-people-with-secret | [Python3] BFS or DFS by group | ye15 | 29 | 3,100 | find all people with secret | 2,092 | 0.342 | Hard | 28,900 |
https://leetcode.com/problems/find-all-people-with-secret/discuss/1599870/Python3-BFS-or-DFS-by-group | class Solution:
def findAllPeople(self, n: int, meetings: List[List[int]], firstPerson: int) -> List[int]:
can = {0, firstPerson}
for _, grp in groupby(sorted(meetings, key=lambda x: x[2]), key=lambda x: x[2]):
stack = set()
graph = defaultdict(list)
for x, y, _ in grp:
graph[x].append(y)
graph[y].append(x)
if x in can: stack.add(x)
if y in can: stack.add(y)
stack = list(stack)
while stack:
x = stack.pop()
for y in graph[x]:
if y not in can:
can.add(y)
stack.append(y)
return can | find-all-people-with-secret | [Python3] BFS or DFS by group | ye15 | 29 | 3,100 | find all people with secret | 2,092 | 0.342 | Hard | 28,901 |
https://leetcode.com/problems/find-all-people-with-secret/discuss/1600419/Really-the-Simplest-answer-I-came-through-oror-BFS-or-DFS | class Solution:
def findAllPeople(self, n: int, meetings: List[List[int]], firstPerson: int) -> List[int]:
meetings.sort(key=lambda x:x[2])
groups = itertools.groupby(meetings,key = lambda x:x[2])
sh = {0,firstPerson}
for key,grp in groups:
seen = set()
graph = defaultdict(list)
for a,b,t in grp:
graph[a].append(b)
graph[b].append(a)
if a in sh:
seen.add(a)
if b in sh:
seen.add(b)
queue = deque(seen)
while queue:
node = queue.popleft()
for neig in graph[node]:
if neig not in sh:
sh.add(neig)
queue.append(neig)
return list(sh) | find-all-people-with-secret | ππ Really the Simplest answer I came through || BFS or DFS π | abhi9Rai | 12 | 576 | find all people with secret | 2,092 | 0.342 | Hard | 28,902 |
https://leetcode.com/problems/find-all-people-with-secret/discuss/1600419/Really-the-Simplest-answer-I-came-through-oror-BFS-or-DFS | class Solution:
def findAllPeople(self, n: int, meetings: List[List[int]], firstPerson: int) -> List[int]:
meetings.sort(key=lambda x:x[2])
groups = itertools.groupby(meetings,key = lambda x:x[2])
sh = {0,firstPerson}
for key,grp in groups:
seen = set()
graph = defaultdict(list)
for a,b,t in grp:
graph[a].append(b)
graph[b].append(a)
if a in sh:
seen.add(a)
if b in sh:
seen.add(b)
st = list(seen)[::]
while st:
node = st.pop()
for neig in graph[node]:
if neig not in sh:
sh.add(neig)
st.append(neig)
return list(sh) | find-all-people-with-secret | ππ Really the Simplest answer I came through || BFS or DFS π | abhi9Rai | 12 | 576 | find all people with secret | 2,092 | 0.342 | Hard | 28,903 |
https://leetcode.com/problems/find-all-people-with-secret/discuss/1599997/Python-BFS | class Solution:
def findAllPeople(self, n: int, meetings: List[List[int]], firstPerson: int) -> List[int]:
g = defaultdict(dict)
for p1, p2, t in meetings:
g[t][p1] = g[t].get(p1, [])
g[t][p1].append(p2)
g[t][p2] = g[t].get(p2, [])
g[t][p2].append(p1)
known = {0, firstPerson}
for t in sorted(g.keys()):
seen = set()
for p in g[t]:
if p in known and p not in seen:
q = deque([p])
seen.add(p)
while q:
cur = q.popleft()
for nxt in g[t][cur]:
if nxt not in seen:
q.append(nxt)
seen.add(nxt)
known.add(nxt)
return known | find-all-people-with-secret | Python BFS | BetterLeetCoder | 6 | 486 | find all people with secret | 2,092 | 0.342 | Hard | 28,904 |
https://leetcode.com/problems/find-all-people-with-secret/discuss/1605880/Python-solution-based-on-connected-components | class Solution(object):
def findAllPeople(self, n, meetings, firstPerson):
"""
:type n: int
:type meetings: List[List[int]]
:type firstPerson: int
:rtype: List[int]
"""
times = dict()
known = set([firstPerson,0])
for x,y,time in meetings:
ad = times.setdefault(time, dict())
ad.setdefault(x, []).append(y)
ad.setdefault(y, []).append(x)
def DFS(node, graph, visited, comp):
visited[node] = True
comp.add(node)
for child in graph[node]:
if not visited[child]:
comp.add(child)
DFS(child, graph, visited, comp)
for time in sorted(times.keys()):
graph = times[time]
visited = dict(zip(graph.keys(), [False]*len(graph.keys())))
it = iter(graph.keys())
components = []
for node in it:
if visited[node]:
continue
c = set()
DFS(node, graph, visited, c)
components.append(c)
for c in components:
if len(known.intersection(c)) > 0:
known.update(c)
return known
``` | find-all-people-with-secret | Python solution based on connected components | gajrajgchouhan | 1 | 62 | find all people with secret | 2,092 | 0.342 | Hard | 28,905 |
https://leetcode.com/problems/find-all-people-with-secret/discuss/2530437/Python-Simple-DFS-Solution-w-Explanation-or-O(V%2BE)-Time-O(V%2BE)-Space-or-No-DSU | class Solution:
def findAllPeople(self, n: int, meetings: List[List[int]], firstPerson: int) -> List[int]:
# Build the graph & store time of the meeting as weights of the edges
adj = defaultdict(list)
for x, y, time in meetings:
adj[x].append((y, time))
adj[y].append((x, time))
# visited[i] = Time by which i-th person knows the secret
visited = [inf for i in range(n)]
# u-th person knows the secret by time t
def dfs(u, t):
visited[u] = t
# Call DFS on connected nodes if an update is possible & meeting is after u knows
for v, w in adj[u]:
if visited[v] > w and w >= t:
dfs(v, w)
# Start DFS from firstPerson and 0-th person
dfs(0, 0)
dfs(firstPerson, 0)
# A person knows the secret if it gets to know the secret before inf
return [i for i in range(n) if visited[i] != inf] | find-all-people-with-secret | [Python] Simple DFS Solution w/ Explanation | O(V+E) Time, O(V+E) Space | No DSU | namanr17 | 0 | 32 | find all people with secret | 2,092 | 0.342 | Hard | 28,906 |
https://leetcode.com/problems/find-all-people-with-secret/discuss/2524038/python3-bfs-with-pq-solution-for-reference | class Solution:
def findAllPeople(self, n: int, meetings, firstPerson: int):
g = defaultdict(list)
for s,e,m in meetings:
g[s].append((e, m))
g[e].append((s, m))
st = [(0,0), (0,firstPerson)]
ans = set([])
while st:
timeline, person = heapq.heappop(st)
ans.add(person)
for p, time in g[person]:
if time >= timeline and p not in ans:
heapq.heappush(st, (time, p))
return ans | find-all-people-with-secret | [python3] bfs with pq, solution for reference | vadhri_venkat | 0 | 11 | find all people with secret | 2,092 | 0.342 | Hard | 28,907 |
https://leetcode.com/problems/find-all-people-with-secret/discuss/1629797/python3-using-groupby-and-deque-to-solve-it | class Solution:
def findAllPeople(self, n: int, meetings: List[List[int]], firstPerson: int) -> List[int]:
from itertools import groupby
from collections import deque
ans = {0, firstPerson}
frames = {}
for k, g in groupby(sorted(meetings, key=lambda x: x[2]), lambda x: x[2]):
frames[k]=[[x[0], x[1]] for x in list(g)]
for k, v in frames.items():
r = deque(v)
l = len(r)
while r and l>0:
p = r.pop()
if p[0] not in ans and p[1] not in ans:
r.appendleft(p)
l-=1
else:
ans.add(p[0])
ans.add(p[1])
l = len(r)
return ans | find-all-people-with-secret | [python3] using groupby and deque to solve it | etu7912a482 | 0 | 32 | find all people with secret | 2,092 | 0.342 | Hard | 28,908 |
https://leetcode.com/problems/find-all-people-with-secret/discuss/1600725/python-simple-to-understand | class Solution:
def findAllPeople(self, n: int, meetings: List[List[int]], fP: int) -> List[int]:
# these two person already know the answer initially
seen = {0,fP}
# set of all the times for the meeting
time = set()
# collections of all the meeting at given time in form of list
d = collections.defaultdict(list)
for i,j,t in meetings:
d[t].append((i,j))
time.add(t)
time = sorted(list(time))
# try to understand it by yourself :P
# why is use XOR
# why did i use two loops
for i in time:
m = len(d[i])
for j in range(m):
if (d[i][j][0] in seen)^(d[i][j][1] in seen):
seen.update(set(d[i][j]))
for j in range(m-1,-1,-1):
if (d[i][j][0] in seen)^(d[i][j][1] in seen):
seen.update(set(d[i][j]))
return seen | find-all-people-with-secret | python simple to understand | Anshuman2043 | 0 | 46 | find all people with secret | 2,092 | 0.342 | Hard | 28,909 |
https://leetcode.com/problems/find-all-people-with-secret/discuss/1600061/Python3-or-Sort-by-Time-and-BFS-or-Explanation-Included | class Solution:
def findAllPeople(self, n: int, meetings: List[List[int]], firstPerson: int) -> List[int]:
secretHolders = set()
secretHolders.add(0)
secretHolders.add(firstPerson)
tupleMeetings = {}
for meeting in meetings:
time = meeting[2]
if(time in tupleMeetings):
tupleMeetings[time].append((meeting[0], meeting[1]))
else:
tupleMeetings[time] = [(meeting[0], meeting[1])]
#print(tupleMeetings)
for key in sorted (tupleMeetings):
edgeList = tupleMeetings[key]
adjacencyList = {}
for edge in edgeList:
if(edge[0] not in adjacencyList):
adjacencyList[edge[0]] = set()
adjacencyList[edge[0]].add(edge[1])
if(edge[1] not in adjacencyList):
adjacencyList[edge[1]] = set()
adjacencyList[edge[1]].add(edge[0])
frontier = set()
for edgeNode in adjacencyList:
if(edgeNode in secretHolders):
frontier.add(edgeNode)
while(len(frontier) > 0):
newFrontier = set()
for item in frontier:
if(item in adjacencyList):
for neighbor in adjacencyList[item]:
if(neighbor not in secretHolders):
secretHolders.add(neighbor)
newFrontier.add(neighbor)
frontier = newFrontier
return list(secretHolders) | find-all-people-with-secret | Python3 | Sort by Time and BFS | Explanation Included | RoshanNaik | 0 | 72 | find all people with secret | 2,092 | 0.342 | Hard | 28,910 |
https://leetcode.com/problems/finding-3-digit-even-numbers/discuss/1611987/Python3-brute-force | class Solution:
def findEvenNumbers(self, digits: List[int]) -> List[int]:
ans = set()
for x, y, z in permutations(digits, 3):
if x != 0 and z & 1 == 0:
ans.add(100*x + 10*y + z)
return sorted(ans) | finding-3-digit-even-numbers | [Python3] brute-force | ye15 | 29 | 1,900 | finding 3 digit even numbers | 2,094 | 0.574 | Easy | 28,911 |
https://leetcode.com/problems/finding-3-digit-even-numbers/discuss/1611987/Python3-brute-force | class Solution:
def findEvenNumbers(self, digits: List[int]) -> List[int]:
ans = []
freq = Counter(digits)
for x in range(100, 1000, 2):
if not Counter(int(d) for d in str(x)) - freq: ans.append(x)
return ans | finding-3-digit-even-numbers | [Python3] brute-force | ye15 | 29 | 1,900 | finding 3 digit even numbers | 2,094 | 0.574 | Easy | 28,912 |
https://leetcode.com/problems/finding-3-digit-even-numbers/discuss/1615242/Python-a-short-Counter-based-solution | class Solution:
def findEvenNumbers(self, digits: List[int]) -> List[int]:
digits = Counter(digits)
result = []
for d1 in range(1, 10):
for d2 in range(10):
for d3 in range(0, 10, 2):
if not Counter([d1, d2, d3]) - digits:
result.append(100 * d1 + 10 * d2 + d3)
return result | finding-3-digit-even-numbers | Python, a short Counter-based solution | blue_sky5 | 2 | 125 | finding 3 digit even numbers | 2,094 | 0.574 | Easy | 28,913 |
https://leetcode.com/problems/finding-3-digit-even-numbers/discuss/2156932/Python-one-line-solution | class Solution:
def findEvenNumbers(self, digits: List[int]) -> List[int]:
return sorted({i*100 + j*10 + k for i,j,k in permutations(digits,3) if i!=0 and k%2==0}) | finding-3-digit-even-numbers | Python one line solution | writemeom | 1 | 154 | finding 3 digit even numbers | 2,094 | 0.574 | Easy | 28,914 |
https://leetcode.com/problems/finding-3-digit-even-numbers/discuss/1857712/1-Line-Python-Solution-oror-40-Faster-oror-Memory-less-than-70 | class Solution:
def findEvenNumbers(self, digits: List[int]) -> List[int]:
return [''.join([str(i) for i in x]) for x in sorted(set(permutations(digits,3))) if x[2]%2==0 and x[0]!=0] | finding-3-digit-even-numbers | 1-Line Python Solution || 40% Faster || Memory less than 70% | Taha-C | 1 | 150 | finding 3 digit even numbers | 2,094 | 0.574 | Easy | 28,915 |
https://leetcode.com/problems/finding-3-digit-even-numbers/discuss/2474364/Clean-and-well-structured-Python3-implementation-(Top-96.9) | class Solution:
def findEvenNumbers(self, digits: List[int]) -> List[int]:
hmap, res = defaultdict(int), []
for num in digits:
hmap[num] += 1 #counting frequency of digits of digits array
for num in range(100, 999, 2): #step 2 because we need even numbers
checker = defaultdict(int)
for digit in str(num):
checker[int(digit)] += 1 #counting frequency of digits of num
#check if every digit in num is in digits array and its frequency is less than or equal to its frequency in digits array
if all(map(lambda x: x in hmap and checker[x] <= hmap[x], checker)):
res.append(num)
return res | finding-3-digit-even-numbers | βοΈ Clean and well structured Python3 implementation (Top 96.9%) | Kagoot | 0 | 46 | finding 3 digit even numbers | 2,094 | 0.574 | Easy | 28,916 |
https://leetcode.com/problems/finding-3-digit-even-numbers/discuss/2240506/Python-simple-solution | class Solution:
def findEvenNumbers(self, digits: List[int]) -> List[int]:
nums = {str(x) for x in range(100,1000,2)}
ans = []
for i in nums:
for d in i:
if i.count(d) > digits.count(int(d)):
break
else:
ans.append(i)
return sorted(ans) | finding-3-digit-even-numbers | Python simple solution | StikS32 | 0 | 145 | finding 3 digit even numbers | 2,094 | 0.574 | Easy | 28,917 |
https://leetcode.com/problems/finding-3-digit-even-numbers/discuss/2124344/Python-3-Loops-1-to-10-0-to-10 | class Solution:
def findEvenNumbers(self, digits: List[int]) -> List[int]:
c, res = Counter(digits), set()
for i in range(1, 10):
c[i] -= 1
for j in range(0, 10):
c[j] -= 1
for k in range(0, 10):
c[k] -= 1
number = i * 100 + j * 10 + k
if number % 2 != 0:
c[k] += 1
continue
if c[i] >= 0 and c[j] >= 0 and c[k] >= 0:
res.add(number)
c[k] += 1
c[j] += 1
c[i] += 1
return sorted(res) | finding-3-digit-even-numbers | Python 3 Loops, 1 to 10, 0 to 10 | Hejita | 0 | 108 | finding 3 digit even numbers | 2,094 | 0.574 | Easy | 28,918 |
https://leetcode.com/problems/finding-3-digit-even-numbers/discuss/2108273/Easy-Understandable-python-code | class Solution:
def findEvenNumbers(self, digits: List[int]) -> List[int]:
l = set()
s = ""
for i in itertools.permutations(digits,3): # Making all the 3-digits Even numbers permutations
if i[0]==0:
continue
elif i[-1]%2!=0:
continue
else:
l.add(i)
digits.clear() # Clearing the digits list to reduce space complexity
for i in l: # Concatenating all the permutations and appending them to digits list
for j in i:
s += str(j)
digits.append(s)
s = ""
return sorted(digits) # Returning the sorted list | finding-3-digit-even-numbers | Easy Understandable python code | M3Sachin | 0 | 96 | finding 3 digit even numbers | 2,094 | 0.574 | Easy | 28,919 |
https://leetcode.com/problems/finding-3-digit-even-numbers/discuss/2103398/Python-oneliner-using-Counter | class Solution:
def findEvenNumbers(self, digits: List[int]) -> List[int]:
c = Counter(digits)
return sorted({i for i in range(100, 1000 , 2) if c >= Counter(map(int , str(i)))}) | finding-3-digit-even-numbers | Python oneliner using Counter | Vigneswar_A | 0 | 50 | finding 3 digit even numbers | 2,094 | 0.574 | Easy | 28,920 |
https://leetcode.com/problems/finding-3-digit-even-numbers/discuss/1917970/Python-Clean-and-Simple!-Counter-and-Permutations | class Solution:
def findEvenNumbers(self, digits):
c, numbers = Counter(digits), []
for i in range(100,1000,2):
ci = Counter([int(x) for x in str(i)])
if all(k in c and c[k]>=v for k,v in ci.items()):
numbers.append(i)
return numbers | finding-3-digit-even-numbers | Python - Clean and Simple! Counter and Permutations | domthedeveloper | 0 | 177 | finding 3 digit even numbers | 2,094 | 0.574 | Easy | 28,921 |
https://leetcode.com/problems/finding-3-digit-even-numbers/discuss/1917970/Python-Clean-and-Simple!-Counter-and-Permutations | class Solution:
def findEvenNumbers(self, digits):
c, numbers = Counter(digits), []
for i in range(100,1000,2):
if c >= Counter([int(x) for x in str(i)]):
numbers.append(i)
return numbers | finding-3-digit-even-numbers | Python - Clean and Simple! Counter and Permutations | domthedeveloper | 0 | 177 | finding 3 digit even numbers | 2,094 | 0.574 | Easy | 28,922 |
https://leetcode.com/problems/finding-3-digit-even-numbers/discuss/1917970/Python-Clean-and-Simple!-Counter-and-Permutations | class Solution:
def findEvenNumbers(self, digits):
return (lambda c:[i for i in range(100,1000,2) if c >= Counter([int(x) for x in str(i)])])(Counter(digits)) | finding-3-digit-even-numbers | Python - Clean and Simple! Counter and Permutations | domthedeveloper | 0 | 177 | finding 3 digit even numbers | 2,094 | 0.574 | Easy | 28,923 |
https://leetcode.com/problems/finding-3-digit-even-numbers/discuss/1917970/Python-Clean-and-Simple!-Counter-and-Permutations | class Solution:
def findEvenNumbers(self, digits):
arr = []
for a, b, c in set(permutations(digits, 3)):
if a and not c:
arr.append(100*a+10*b+c)
return sorted(arr) | finding-3-digit-even-numbers | Python - Clean and Simple! Counter and Permutations | domthedeveloper | 0 | 177 | finding 3 digit even numbers | 2,094 | 0.574 | Easy | 28,924 |
https://leetcode.com/problems/finding-3-digit-even-numbers/discuss/1917970/Python-Clean-and-Simple!-Counter-and-Permutations | class Solution:
def findEvenNumbers(self, digits):
return sorted(a*100+b*10+c for a, b, c in set(permutations(digits, 3)) if a and not c&1) | finding-3-digit-even-numbers | Python - Clean and Simple! Counter and Permutations | domthedeveloper | 0 | 177 | finding 3 digit even numbers | 2,094 | 0.574 | Easy | 28,925 |
https://leetcode.com/problems/finding-3-digit-even-numbers/discuss/1646906/Python-using-Counter-and-permutations | class Solution:
def findEvenNumbers(self, digits: List[int]) -> List[int]:
count = Counter(digits)
for v, n in count.items():
count[v] = min(n, 3)
l = set()
for t in permutations(count.elements(), 3):
v = int(''.join(map(str, t)))
if v % 2 == 0 and v >= 100:
l.add(v)
return sorted(l) | finding-3-digit-even-numbers | Python, using Counter and permutations | emwalker | 0 | 143 | finding 3 digit even numbers | 2,094 | 0.574 | Easy | 28,926 |
https://leetcode.com/problems/finding-3-digit-even-numbers/discuss/1618254/Counters-and-list-filtering-89-speed | class Solution:
nums = {n: Counter(map(int, str(n))) for n in range(100, 999, 2)}
def findEvenNumbers(self, digits: List[int]) -> List[int]:
cnt_digits = Counter(digits)
return [n for n, cnt in Solution.nums.items()
if all(count <= cnt_digits[d] for d, count in cnt.items())] | finding-3-digit-even-numbers | Counters and list filtering, 89% speed | EvgenySH | 0 | 157 | finding 3 digit even numbers | 2,094 | 0.574 | Easy | 28,927 |
https://leetcode.com/problems/finding-3-digit-even-numbers/discuss/1612000/Python3-itertools | class Solution:
def findEvenNumbers(self, digits: List[int]) -> List[int]:
output = set()
for n in itertools.permutations(digits, 3):
if n[0] != 0 and n[2] % 2 == 0:
output.add(n[0] * 100 + n[1] * 10 + n[2])
output = list(output)
output.sort()
return output | finding-3-digit-even-numbers | Python3 itertools | michaelb072 | 0 | 71 | finding 3 digit even numbers | 2,094 | 0.574 | Easy | 28,928 |
https://leetcode.com/problems/finding-3-digit-even-numbers/discuss/1611990/python-brute-force-solution | class Solution:
def findEvenNumbers(self, digits: List[int]) -> List[int]:
n = len(digits)
res = []
for i in range(n):
if digits[i] != 0:
for j in range(n):
if j != i:
for k in range(n):
if digits[k] % 2 == 0 and k not in (i, j):
res.append(digits[i]*100+digits[j]*10+digits[k])
res = list(set(res))
res.sort()
return res | finding-3-digit-even-numbers | python brute force solution | abkc1221 | 0 | 112 | finding 3 digit even numbers | 2,094 | 0.574 | Easy | 28,929 |
https://leetcode.com/problems/delete-the-middle-node-of-a-linked-list/discuss/2700533/Fastest-python-solution-TC%3A-O(N)SC%3A-O(1) | class Solution:
def deleteMiddle(self, head: Optional[ListNode]) -> Optional[ListNode]:
slow,fast,prev=head,head,None
while fast and fast.next:
prev=slow
slow=slow.next
fast=fast.next.next
if prev==None:
return None
prev.next=slow.next
return head | delete-the-middle-node-of-a-linked-list | Fastest python solution TC: O(N),SC: O(1) | shubham_1307 | 12 | 1,200 | delete the middle node of a linked list | 2,095 | 0.605 | Medium | 28,930 |
https://leetcode.com/problems/delete-the-middle-node-of-a-linked-list/discuss/1617620/Python-oror-Easy-Solution | class Solution:
def deleteMiddle(self, head: Optional[ListNode]) -> Optional[ListNode]:
if head.next == None:
return
slow, fast = head, head
prev = None
while fast and fast.next:
prev = slow
slow = slow.next
fast = fast.next.next
prev.next = slow.next
return head | delete-the-middle-node-of-a-linked-list | Python || Easy Solution | naveenrathore | 3 | 130 | delete the middle node of a linked list | 2,095 | 0.605 | Medium | 28,931 |
https://leetcode.com/problems/delete-the-middle-node-of-a-linked-list/discuss/2234244/Python3-solution-using-2-pointer-slow-and-fast | class Solution:
def deleteMiddle(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head or not head.next:
return
fast = head.next
slow = head
while slow and fast and fast.next:
if fast.next.next is None:
break
else:
fast= fast.next.next
slow = slow.next
slow.next = slow.next.next
return head | delete-the-middle-node-of-a-linked-list | Python3 solution using 2 pointer slow and fast | ShaangriLa | 1 | 26 | delete the middle node of a linked list | 2,095 | 0.605 | Medium | 28,932 |
https://leetcode.com/problems/delete-the-middle-node-of-a-linked-list/discuss/1980213/python-3-oror-two-pointers-oror-O(n)O(1) | class Solution:
def deleteMiddle(self, head: Optional[ListNode]) -> Optional[ListNode]:
dummy = prevSlow = ListNode(0, head)
slow = fast = head
while fast and fast.next:
prevSlow = slow
slow = slow.next
fast = fast.next.next
prevSlow.next = slow.next
return dummy.next | delete-the-middle-node-of-a-linked-list | python 3 || two pointers || O(n)/O(1) | dereky4 | 1 | 114 | delete the middle node of a linked list | 2,095 | 0.605 | Medium | 28,933 |
https://leetcode.com/problems/delete-the-middle-node-of-a-linked-list/discuss/1807644/Python-slow-and-fast-pointer-solution | class Solution:
def deleteMiddle(self, head: Optional[ListNode]) -> Optional[ListNode]:
if head.next is None:
head=head.next
return head
cur = head
prev = None
double_cur = head
while double_cur and double_cur.next:
prev = cur
cur = cur.next
double_cur = double_cur.next.next
prev.next = cur.next
return head | delete-the-middle-node-of-a-linked-list | Python slow and fast pointer solution | adiljay05 | 1 | 58 | delete the middle node of a linked list | 2,095 | 0.605 | Medium | 28,934 |
https://leetcode.com/problems/delete-the-middle-node-of-a-linked-list/discuss/1612192/Python3-2-pointers | class Solution:
def deleteMiddle(self, head: Optional[ListNode]) -> Optional[ListNode]:
prev = None
fast = slow = head
while fast and fast.next:
fast = fast.next.next
prev = slow
slow = slow.next
if not prev: return None
prev.next = prev.next.next
return head | delete-the-middle-node-of-a-linked-list | [Python3] 2 pointers | ye15 | 1 | 47 | delete the middle node of a linked list | 2,095 | 0.605 | Medium | 28,935 |
https://leetcode.com/problems/delete-the-middle-node-of-a-linked-list/discuss/1612192/Python3-2-pointers | class Solution:
def deleteMiddle(self, head: Optional[ListNode]) -> Optional[ListNode]:
dummy = fast = slow = ListNode(next = head)
while fast.next and fast.next.next:
fast = fast.next.next
slow = slow.next
slow.next = slow.next.next
return dummy.next | delete-the-middle-node-of-a-linked-list | [Python3] 2 pointers | ye15 | 1 | 47 | delete the middle node of a linked list | 2,095 | 0.605 | Medium | 28,936 |
https://leetcode.com/problems/delete-the-middle-node-of-a-linked-list/discuss/1612009/python-Floyd's-Algo | class Solution:
def deleteMiddle(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head.next:
return
slow = fast = head
prev = None
while fast and fast.next:
prev = slow
slow = slow.next
fast = fast.next.next
prev.next = slow.next
slow.next = None
return head | delete-the-middle-node-of-a-linked-list | python Floyd's Algo | abkc1221 | 1 | 85 | delete the middle node of a linked list | 2,095 | 0.605 | Medium | 28,937 |
https://leetcode.com/problems/delete-the-middle-node-of-a-linked-list/discuss/2847208/Easiest-Python-Solution-2095.-Delete-the-Middle-Node-of-a-Linked-List | class Solution:
def deleteMiddle(self, head: Optional[ListNode]) -> Optional[ListNode]:
current = head
nums = []
while current:
nums.append(current.val)
current = current.next
mid = len(nums)//2
del nums[int(mid)]
dummy = current = ListNode(0)
for a in nums:
current.next = ListNode(a)
current = current.next
return dummy.next | delete-the-middle-node-of-a-linked-list | β
Easiest Python Solution - 2095. Delete the Middle Node of a Linked List | Brian_Daniel_Thomas | 0 | 1 | delete the middle node of a linked list | 2,095 | 0.605 | Medium | 28,938 |
https://leetcode.com/problems/delete-the-middle-node-of-a-linked-list/discuss/2781907/Delete-the-Middle-Node-of-a-Linked-List-Python-easy-solution | class Solution:
def deleteMiddle(self, head: Optional[ListNode]) -> Optional[ListNode]:
n=0
node = head
while node:
n+=1
node = node.next
mid = n//2
if mid==0:
head = None
return head
count=0
start=head
while count<mid-1:
start = start.next
count+=1
start.next = start.next.next
return head | delete-the-middle-node-of-a-linked-list | Delete the Middle Node of a Linked List - Python easy solution | Apucs | 0 | 4 | delete the middle node of a linked list | 2,095 | 0.605 | Medium | 28,939 |
https://leetcode.com/problems/delete-the-middle-node-of-a-linked-list/discuss/2710187/python-easy-solution-oror-simple-traversal | class Solution:
def deleteMiddle(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head.next:return None
cnt=0
cur=head
while cur and cur.next: #program to find length
cnt+=1
cur=cur.next
length=(cnt+1)
middle=length//2 #middle node
i=0
tail=head
while i<middle-1:
tail=tail.next
i+=1
tail.next=tail.next.next #deleting middle node
return head | delete-the-middle-node-of-a-linked-list | python easy solution || simple traversal | tush18 | 0 | 2 | delete the middle node of a linked list | 2,095 | 0.605 | Medium | 28,940 |
https://leetcode.com/problems/delete-the-middle-node-of-a-linked-list/discuss/2704086/Python3!-1-Pass.-As-short-as-it-gets. | class Solution:
def deleteMiddle(self, head: Optional[ListNode]) -> Optional[ListNode]:
def recursive(node:ListNode, length:int = 0) -> int:
if node is None:
return length
total = recursive(node.next, length+1)
if length + 1 == total // 2:
node.next = node.next.next
return total
if head is None or head.next is None:
return None
recursive(head)
return head | delete-the-middle-node-of-a-linked-list | πPython3! 1 Pass. As short as it gets. | aminjun | 0 | 4 | delete the middle node of a linked list | 2,095 | 0.605 | Medium | 28,941 |
https://leetcode.com/problems/delete-the-middle-node-of-a-linked-list/discuss/2702974/Python3-or-Faster-than-99-or-Two-Pointers | class Solution:
def deleteMiddle(self, head: Optional[ListNode]) -> Optional[ListNode]:
if head.next == None:
return None
elif head.next.next == None:
head.next = None
return head
else:
slow = head
fast = head.next.next
while(fast != None):
fast = fast.next
if fast == None:
slow.next = slow.next.next
return head
fast = fast.next
slow = slow.next
slow.next = slow.next.next
return head | delete-the-middle-node-of-a-linked-list | Python3 | Faster than 99% | Two Pointers | TheSnappl | 0 | 10 | delete the middle node of a linked list | 2,095 | 0.605 | Medium | 28,942 |
https://leetcode.com/problems/delete-the-middle-node-of-a-linked-list/discuss/2702425/PYTHON-Simple-python-solution | class Solution:
def deleteMiddle(self, head: Optional[ListNode]) -> Optional[ListNode]:
if head.next == None:
head = None
else:
tmp = head
length = 0
while tmp:
length += 1
tmp = tmp.next
tmp = head
for i in range(length // 2):
last = tmp
tmp = tmp.next
last.next = tmp.next
return head | delete-the-middle-node-of-a-linked-list | [PYTHON] Simple python solution | valera_grishko | 0 | 4 | delete the middle node of a linked list | 2,095 | 0.605 | Medium | 28,943 |
https://leetcode.com/problems/delete-the-middle-node-of-a-linked-list/discuss/2702378/Python-Simple-Python-Solution-Using-Iterative-Approach | class Solution:
def deleteMiddle(self, head: Optional[ListNode]) -> Optional[ListNode]:
if head.next == None:
return None
node = head
length = 0
while node != None:
length = length + 1
node = node.next
mid_point = length // 2
new_node = head
while mid_point > 1:
new_node = new_node.next
mid_point = mid_point - 1
new_node.next = new_node.next.next
return head | delete-the-middle-node-of-a-linked-list | [ Python ] β
β
Simple Python Solution Using Iterative Approach π₯³βπ | ASHOK_KUMAR_MEGHVANSHI | 0 | 15 | delete the middle node of a linked list | 2,095 | 0.605 | Medium | 28,944 |
https://leetcode.com/problems/delete-the-middle-node-of-a-linked-list/discuss/2701991/Python-Accepted | class Solution:
def deleteMiddle(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head.next: return None
slow, fast = head, head.next.next
while fast and fast.next:
slow = slow.next
fast = fast.next.next
slow.next = slow.next.next
return head | delete-the-middle-node-of-a-linked-list | Python Accepted β
| Khacker | 0 | 4 | delete the middle node of a linked list | 2,095 | 0.605 | Medium | 28,945 |
https://leetcode.com/problems/delete-the-middle-node-of-a-linked-list/discuss/2701867/Python-(Faster-than-98)-with-a-brief-explanationor-Two-pointers | class Solution:
def deleteMiddle(self, head: Optional[ListNode]) -> Optional[ListNode]:
dummy = ListNode(0, head)
slow = dummy
fast = dummy.next
while fast and fast.next:
slow = slow.next
fast = fast.next.next
slow.next = slow.next.next
return dummy.next | delete-the-middle-node-of-a-linked-list | Python (Faster than 98%) with a brief explanation| Two-pointers | KevinJM17 | 0 | 2 | delete the middle node of a linked list | 2,095 | 0.605 | Medium | 28,946 |
https://leetcode.com/problems/delete-the-middle-node-of-a-linked-list/discuss/2701352/tortoise-and-hare-beating-89-in-time-and-79-in-memory | class Solution:
def deleteMiddle(self, head: Optional[ListNode]) -> Optional[ListNode]:
# tortoise and hare
if not head.next:
return None
hare = head
tortoise = head
# the previous node for tortoise
tortoise_ = head
while hare and hare.next:
tortoise_ = tortoise
tortoise = tortoise.next
hare = hare.next.next
tortoise_.next = tortoise.next
return head | delete-the-middle-node-of-a-linked-list | tortoise and hare, beating 89% in time and 79% in memory | leonine9 | 0 | 1 | delete the middle node of a linked list | 2,095 | 0.605 | Medium | 28,947 |
https://leetcode.com/problems/delete-the-middle-node-of-a-linked-list/discuss/2701176/Simple-1-pass-Python3-Solution | class Solution:
def deleteMiddle(self, head: Optional[ListNode]) -> Optional[ListNode]:
if head.next is None:
return None
prev = temp1x = temp2x = head
while True:
temp1x = temp1x.next
temp2x = temp2x.next.next
if not temp2x or not temp2x.next:
break
prev = temp1x
prev.next = temp1x.next
return head | delete-the-middle-node-of-a-linked-list | Simple π₯1-passπ₯ Python3 Solution | mediocre-coder | 0 | 2 | delete the middle node of a linked list | 2,095 | 0.605 | Medium | 28,948 |
https://leetcode.com/problems/delete-the-middle-node-of-a-linked-list/discuss/2701168/Python-2-Pointers-or-O(n)-or-Simple-Intuitive | class Solution:
def deleteMiddle(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head.next:
return None
slow, fast = head, head.next.next
while fast and fast.next:
slow = slow.next
fast = fast.next.next
slow.next = slow.next.next
return head | delete-the-middle-node-of-a-linked-list | Python 2 Pointers | O(n) | Simple Intuitive | Nibba2018 | 0 | 4 | delete the middle node of a linked list | 2,095 | 0.605 | Medium | 28,949 |
https://leetcode.com/problems/delete-the-middle-node-of-a-linked-list/discuss/2701062/Python-3-oror-Simple-Solution-oror-Easy-Understanding-oror-O(N)-complexity | class Solution:
def deleteMiddle(self, head: Optional[ListNode]) -> Optional[ListNode]:
if head == None:
return head
if head.next == None:
return head.next
node = head
n = 0
while(node != None):
n+=1
node = node.next
mid = n//2
print(mid)
n = 0
node = head
while(node != None):
if(n == mid-1):
node.next = node.next.next
break
n += 1
node = node.next
return head | delete-the-middle-node-of-a-linked-list | Python 3 || Simple Solution || Easy Understanding || O(N) complexity | ahamedmusadiq_-12 | 0 | 3 | delete the middle node of a linked list | 2,095 | 0.605 | Medium | 28,950 |
https://leetcode.com/problems/step-by-step-directions-from-a-binary-tree-node-to-another/discuss/1612179/Python3-lca | class Solution:
def getDirections(self, root: Optional[TreeNode], startValue: int, destValue: int) -> str:
def lca(node):
"""Return lowest common ancestor of start and dest nodes."""
if not node or node.val in (startValue , destValue): return node
left, right = lca(node.left), lca(node.right)
return node if left and right else left or right
root = lca(root) # only this sub-tree matters
ps = pd = ""
stack = [(root, "")]
while stack:
node, path = stack.pop()
if node.val == startValue: ps = path
if node.val == destValue: pd = path
if node.left: stack.append((node.left, path + "L"))
if node.right: stack.append((node.right, path + "R"))
return "U"*len(ps) + pd | step-by-step-directions-from-a-binary-tree-node-to-another | [Python3] lca | ye15 | 108 | 8,100 | step by step directions from a binary tree node to another | 2,096 | 0.488 | Medium | 28,951 |
https://leetcode.com/problems/step-by-step-directions-from-a-binary-tree-node-to-another/discuss/1728875/2-Python-solutions%3A-Graph-based-LCA | class Solution:
def getDirections(self, root: Optional[TreeNode], startValue: int, destValue: int) -> str:
graph=defaultdict(list)
stack=[(root)]
#Step1: Build Graph
while stack:
node=stack.pop()
if node.left:
graph[node.val].append((node.left.val,"L"))
graph[node.left.val].append((node.val,"U"))
stack.append(node.left)
if node.right:
graph[node.val].append((node.right.val,"R"))
graph[node.right.val].append((node.val,"U"))
stack.append(node.right)
#Step 2: Normal BFS
q=deque([(startValue,"")])
seen=set()
seen.add(startValue)
while q:
node,path=q.popleft()
if node==destValue:
return path
for neigh in graph[node]:
v,d=neigh
if v not in seen:
q.append((v,path+d))
seen.add(v)
return -1 | step-by-step-directions-from-a-binary-tree-node-to-another | 2 Python π solutions: Graph-based, LCA | InjySarhan | 15 | 1,300 | step by step directions from a binary tree node to another | 2,096 | 0.488 | Medium | 28,952 |
https://leetcode.com/problems/step-by-step-directions-from-a-binary-tree-node-to-another/discuss/1728875/2-Python-solutions%3A-Graph-based-LCA | class Solution:
def getDirections(self, root: Optional[TreeNode], startValue: int, destValue: int) -> str:
def getLCA(root,p,q):
if not root: return None
if root.val==p or root.val==q:
return root
L=getLCA(root.left,p,q)
R=getLCA(root.right,p,q)
if L and R:
return root
return L or R
def getPath(node1,node2,path): #---> Problem here
if not node1: return
if node1.val==node2: return path
return getPath(node1.left,node2,path+["L"]) or getPath(node1.right,node2,path+["R"])
LCA=getLCA(root,startValue,destValue)
path1=getPath(LCA,startValue,[])
path2=getPath(LCA,destValue,[])
path=["U"]*len(path1) + path2 if path1 else path2
return "".join(path) | step-by-step-directions-from-a-binary-tree-node-to-another | 2 Python π solutions: Graph-based, LCA | InjySarhan | 15 | 1,300 | step by step directions from a binary tree node to another | 2,096 | 0.488 | Medium | 28,953 |
https://leetcode.com/problems/step-by-step-directions-from-a-binary-tree-node-to-another/discuss/1728875/2-Python-solutions%3A-Graph-based-LCA | class Solution:
def getDirections(self, root: Optional[TreeNode], startValue: int, destValue: int) -> str:
#soltion 2 LCA
def getLCA(root,p,q):
if not root: return None
if root.val==p or root.val==q:
return root
L=getLCA(root.left,p,q)
R=getLCA(root.right,p,q)
if L and R:
return root
return L or R
LCA=getLCA(root,startValue,destValue)
ps,pd="",""
stack = [(LCA, "")]
while stack:
node, path = stack.pop()
if node.val == startValue: ps = path
if node.val == destValue: pd = path
if node.left: stack.append((node.left, path + "L"))
if node.right: stack.append((node.right, path + "R"))
return "U"*len(ps) + pd | step-by-step-directions-from-a-binary-tree-node-to-another | 2 Python π solutions: Graph-based, LCA | InjySarhan | 15 | 1,300 | step by step directions from a binary tree node to another | 2,096 | 0.488 | Medium | 28,954 |
https://leetcode.com/problems/step-by-step-directions-from-a-binary-tree-node-to-another/discuss/2224238/Simple-iterative-solution-pre-order-with-explanation-and-comments | class Solution:
def find_path(self, node, src_val, dest_val):
# To handle pre-order iterative
stack = []
stack.append((node, ""))
# Tracking the path to both start and destination
src_path = dest_path = ""
while stack:
node, path = stack.pop()
if node.val == src_val:
src_path = path
if node.val == dest_val:
dest_path = path
# Tracking the both paths at the same time
if node.right:
stack.append((node.right, path+"R"))
if node.left:
stack.append((node.left, path+"L"))
return src_path, dest_path
def getDirections(self, root: Optional[TreeNode], startValue: int, destValue: int) -> str:
path_s, path_d = self.find_path(root, startValue, destValue)
i = j = 0
while i < len(path_s) and j < len(path_d):
if path_s[i] != path_d[j]:
break
i += 1
j += 1
return 'U' * len(path_s[i:]) + path_d[j:] | step-by-step-directions-from-a-binary-tree-node-to-another | Simple iterative solution pre-order with explanation and comments | massaker | 2 | 128 | step by step directions from a binary tree node to another | 2,096 | 0.488 | Medium | 28,955 |
https://leetcode.com/problems/step-by-step-directions-from-a-binary-tree-node-to-another/discuss/2065266/Python-two-DFS-traversals | class Solution:
def getDirections(self, root: Optional[TreeNode], startValue: int, destValue: int) -> str:
def buildAdjacencyList(node):
if not node:
return
if node.left:
adj[node.val].append((node.left.val, 'L'))
adj[node.left.val].append((node.val, 'U'))
buildAdjacencyList(node.left)
if node.right:
adj[node.val].append((node.right.val, 'R'))
adj[node.right.val].append((node.val, 'U'))
buildAdjacencyList(node.right)
def findNode(value, prior, path):
if value == destValue:
return True
for next_value, char in adj[value]:
if next_value != prior:
if findNode(next_value, value, path):
path.append(char)
return True
return False
adj = defaultdict(list)
buildAdjacencyList(root)
path = []
findNode(startValue, -1, path)
return "".join(reversed(path)) | step-by-step-directions-from-a-binary-tree-node-to-another | Python, two DFS traversals | blue_sky5 | 2 | 237 | step by step directions from a binary tree node to another | 2,096 | 0.488 | Medium | 28,956 |
https://leetcode.com/problems/step-by-step-directions-from-a-binary-tree-node-to-another/discuss/1964602/BFS-Python-straightforward-solution | class Solution:
def getDirections(self, root: Optional[TreeNode], startValue: int, destValue: int) -> str:
dq = deque([[root, ""]])
sourceDirections = ""
destDirections = ""
while len(dq) > 0:
curr = dq.popleft()
if curr[0] is None:
continue
if curr[0].val == startValue:
sourceDirections = curr[1]
if curr[0].val == destValue:
destDirections = curr[1]
dq.append([curr[0].left, curr[1]+"L"])
dq.append([curr[0].right, curr[1]+"R"])
index = 0
for i in range(min(len(sourceDirections), len(destDirections))):
if sourceDirections[i] == destDirections[i]:
index += 1
else:
break
return (len(sourceDirections) - index) * "U" + destDirections[index:] | step-by-step-directions-from-a-binary-tree-node-to-another | BFS Python straightforward solution | user6397p | 2 | 213 | step by step directions from a binary tree node to another | 2,096 | 0.488 | Medium | 28,957 |
https://leetcode.com/problems/step-by-step-directions-from-a-binary-tree-node-to-another/discuss/2103945/python3-solution%3A-90-faster-solution | class Solution:
def getDirections(self, root: Optional[TreeNode], startValue: int, destValue: int) -> str:
final_paths = [[], []]
def path_to_node(root, cur_path, direction):
nonlocal final_paths, startValue, destValue
if not root:
return
cur_path.append(direction)
if root.val == startValue:
final_paths[0] = cur_path.copy()
if root.val == destValue:
final_paths[1] = cur_path.copy()
path_to_node(root.left, cur_path, 'L')
path_to_node(root.right, cur_path, 'R')
cur_path.pop(-1)
path_to_node(root, [], 'S')
start_path = final_paths[0]
dest_path = final_paths[1]
while len(start_path) > 0 and len(dest_path) > 0:
if start_path[0] != dest_path[0]:
break
start_path.pop(0)
dest_path.pop(0)
return 'U'*len(start_path) + ''.join(dest_path) | step-by-step-directions-from-a-binary-tree-node-to-another | python3 solution: 90% faster solution | subrahmanyajoshi123 | 1 | 201 | step by step directions from a binary tree node to another | 2,096 | 0.488 | Medium | 28,958 |
https://leetcode.com/problems/step-by-step-directions-from-a-binary-tree-node-to-another/discuss/1996946/Clean-simple-Python-LCA-with-parents-hashmap | class Solution:
def getDirections(self, root: Optional[TreeNode], startValue: int, destValue: int) -> str:
# Build a parent map with which we can move upward in the tree.
# For this specific problem, we also mark whether it's a left or right child of the parent.
parents = dict()
parents[root.val] = (0, 'X')
def buildParents(node):
if node.left:
parents[node.left.val] = (node.val, 'L')
buildParents(node.left)
if node.right:
parents[node.right.val] = (node.val, 'R')
buildParents(node.right)
buildParents(root)
# Get the path from root to the target value
def getPathParents(val):
ans = []
parent = parents[val]
print(parent, parent[0])
while parent[0] != 0:
ans.append(parent[1])
parent = parents[parent[0]]
return list(reversed(ans))
startPath = getPathParents(startValue)
destPath = getPathParents(destValue)
# move to common lowest ancestor (LCA)
p = 0
while p < len(startPath) and p < len(destPath) and startPath[p] == destPath[p]:
p += 1
# create output format
return "".join(['U'] * len(startPath[p:]) + destPath[p:])
# This getPath method was my first try, but it is too memory expensive and
# won't be accepted by LeetCode, although it works algorithmically.
#def getPath(root, val, path=['X']):
# if val == root.val:
# return path
# elif not root.left and not root.right:
# return []
# else:
# ans = []
# if root.left:
# ans = ans + getPath(root.left, val, path + ['L'])
# if root.right and not ans:
# ans = ans + getPath(root.right, val, path + ['R'])
# return ans
#startPath = getPath(root, startValue)
#destPath = getPath(root, destValue) | step-by-step-directions-from-a-binary-tree-node-to-another | Clean, simple Python, LCA with parents hashmap | boris17 | 1 | 105 | step by step directions from a binary tree node to another | 2,096 | 0.488 | Medium | 28,959 |
https://leetcode.com/problems/step-by-step-directions-from-a-binary-tree-node-to-another/discuss/1879154/python-easy-dfs-solution-(no-LCA) | class Solution:
def getDirections(self, root: Optional[TreeNode], startValue: int, destValue: int) -> str:
direction = defaultdict(dict)
stack = [root]
while stack:
node = stack.pop()
if node.left:
stack.append(node.left)
direction[node.val][node.left.val] = 'L'
direction[node.left.val][node.val] = 'U'
if node.right:
stack.append(node.right)
direction[node.val][node.right.val] = 'R'
direction[node.right.val][node.val] = 'U'
s = [(startValue, '')]
visited = {startValue}
while s:
num, path = s.pop()
if num == destValue:
return path
for child in direction[num]:
if child not in visited:
visited.add(child)
s.append((child, path + direction[num][child])) | step-by-step-directions-from-a-binary-tree-node-to-another | python easy dfs solution (no LCA) | byuns9334 | 1 | 251 | step by step directions from a binary tree node to another | 2,096 | 0.488 | Medium | 28,960 |
https://leetcode.com/problems/step-by-step-directions-from-a-binary-tree-node-to-another/discuss/2562873/Python-O(n)-LCA-without-copying-path-each-time | class Solution:
def getDirections(self, root: Optional[TreeNode], s: int, t: int) -> str:
sPath, tPath, stack, path = None, None, [], []
def dfs(n):
nonlocal sPath
nonlocal tPath
if n is None or (sPath is not None and tPath is not None):
return
if n.val == s:
sPath = list(path)
if n.val == t:
tPath = list(path)
path.append('L')
dfs(n.left)
path.pop()
path.append('R')
dfs(n.right)
path.pop()
dfs(root)
i = 0
while i < min(len(sPath), len(tPath)):
if sPath[i] != tPath[i]:
break
i += 1
return ''.join((['U'] * (len(sPath) - i))) + ''.join(tPath[i:]) | step-by-step-directions-from-a-binary-tree-node-to-another | [Python] O(n) LCA without copying path each time | ambient8 | 0 | 80 | step by step directions from a binary tree node to another | 2,096 | 0.488 | Medium | 28,961 |
https://leetcode.com/problems/step-by-step-directions-from-a-binary-tree-node-to-another/discuss/2311045/Python-BackTrack | class Solution:
def getDirections(self, root: Optional[TreeNode], startValue: int, destValue: int) -> str:
def findRootToNode(node, curStr, dest, res):
if node.val == dest:
res[0] = ''.join(curStr)
return
if node.left:
curStr.append('L')
findRootToNode(node.left, curStr, dest, res)
curStr.pop()
if node.right:
curStr.append('R')
findRootToNode(node.right, curStr, dest, res)
curStr.pop()
lst1, lst2 = [''], ['']
findRootToNode(root, [], startValue, lst1)
findRootToNode(root, [], destValue, lst2)
startStr, destStr = lst1[0], lst2[0]
i = 0
m, n = len(startStr), len(destStr)
while i < min(m, n) and startStr[i] == destStr[i]:
i += 1
startStr = startStr[i:]
destStr = destStr[i:]
res = 'U' * len(startStr)
res += destStr
return res | step-by-step-directions-from-a-binary-tree-node-to-another | Python, BackTrack | Kewl777 | 0 | 65 | step by step directions from a binary tree node to another | 2,096 | 0.488 | Medium | 28,962 |
https://leetcode.com/problems/step-by-step-directions-from-a-binary-tree-node-to-another/discuss/2060164/Python3-BacktrackLCA-path-construction | class Solution:
def getDirections(self, root: Optional[TreeNode], start_value: int, dest_value: int) -> str:
def dirs_from_root(root: TreeNode, t: int, dirs) -> list[str]:
if root is None:
return False
elif root.val == t:
return True
dirs.append('L')
if dirs_from_root(root.left, t, dirs):
return True
dirs[-1] = 'R'
if dirs_from_root(root.right, t, dirs):
return True
dirs.pop()
return False
p1, p2 = [], []
dirs_from_root(root, start_value, p1)
dirs_from_root(root, dest_value, p2)
divergent_start = next((i for i, (d1, d2) in enumerate(zip(p1, p2)) if d1 != d2), min(len(p1), len(p2)))
return "U" * len(p1[divergent_start:]) + "".join(p2[divergent_start:]) | step-by-step-directions-from-a-binary-tree-node-to-another | [Python3] Backtrack/LCA path construction | taborlin | 0 | 118 | step by step directions from a binary tree node to another | 2,096 | 0.488 | Medium | 28,963 |
https://leetcode.com/problems/step-by-step-directions-from-a-binary-tree-node-to-another/discuss/2005656/Python-DFS-easy-solution | class Solution:
def getDirections(self, root: Optional[TreeNode], startValue: int, destValue: int) -> str:
p_s, p_d = [], []
p_s = self.find(root, startValue, p_s)
p_d = self.find(root, destValue, p_d)
overlap_index = -1
# find common ancestor
for i in range(len(p_s)):
c = p_s[i]
if i<len(p_d) and p_d[i] == c:
overlap_index = i
else:
break
if overlap_index != -1:
p_s, p_d = p_s[overlap_index+1:], p_d[overlap_index+1:]
right = ''
for ele in p_d:
right += 'L' if ele == 0 else 'R'
return 'U'*len(p_s) + right
def find(self, curr, des, path):
if curr == None:
return None
if curr.val == des:
return path
# represent right as 1, left as 0 to save memory
path.append(1)
res = self.find(curr.right, des, path)
if res: return res
path[-1] = 0
res = self.find(curr.left, des, path)
if res: return res
path.pop() | step-by-step-directions-from-a-binary-tree-node-to-another | Python DFS easy solution | EthanLi0203 | 0 | 210 | step by step directions from a binary tree node to another | 2,096 | 0.488 | Medium | 28,964 |
https://leetcode.com/problems/step-by-step-directions-from-a-binary-tree-node-to-another/discuss/1709138/Without-LCA-ignore-common-part-of-paths | class Solution:
def getDirections(self, root: Optional[TreeNode], startValue: int, destValue: int) -> str:
stack, start, end = [(root, "")], "", ""
while stack:
node, path = stack.pop()
stack = stack + [(node.left, path + "L")] if node.left else stack
stack = stack + [(node.right, path + "R")] if node.right else stack
start = path if node.val == startValue else start
end = path if node.val == destValue else end
if start and end:
break
i = 0 # To ignore common path
while i < min(len(start), len(end)) and start[i] == end[i]:
i += 1
return "U" * (len(start) - i) + end[i:] | step-by-step-directions-from-a-binary-tree-node-to-another | Without LCA; ignore common part of paths | abhie | 0 | 95 | step by step directions from a binary tree node to another | 2,096 | 0.488 | Medium | 28,965 |
https://leetcode.com/problems/step-by-step-directions-from-a-binary-tree-node-to-another/discuss/1616418/Find-both-with-while-loop | class Solution:
def getDirections(self, root: Optional[TreeNode], startValue: int, destValue: int) -> str:
row = [("", root)]
start_path, dest_path = "", ""
start_found = dest_found = False
while row:
new_row = []
for path, node in row:
if node.val == startValue:
start_path = path
start_found = True
elif node.val == destValue:
dest_path = path
dest_found = True
if start_found and dest_found:
break
if node.left:
new_row.append((f"{path}L", node.left))
if node.right:
new_row.append((f"{path}R", node.right))
if start_found and dest_found:
break
row = new_row
len_start_path, len_dest_path = len(start_path), len(dest_path)
i = 0
while (len_start_path > i < len_dest_path and
start_path[i] == dest_path[i]):
i += 1
return f"{'U' * (len_start_path - i)}{dest_path[i:]}" | step-by-step-directions-from-a-binary-tree-node-to-another | Find both with while loop | EvgenySH | 0 | 70 | step by step directions from a binary tree node to another | 2,096 | 0.488 | Medium | 28,966 |
https://leetcode.com/problems/step-by-step-directions-from-a-binary-tree-node-to-another/discuss/1613267/Python-3-BFS-%2B-Djikstra's-algoirthm | class Solution:
def getDirections(self, root: Optional[TreeNode], s: int, d: int) -> str:
par = {}
left, right = {}, {}
def dfs(cur, parent, d):
if not cur:
return
if parent:
par[cur.val] = parent.val
if d == 'l':
left[parent.val] = cur.val
elif d == 'r':
right[parent.val] = cur.val
dfs(cur.left, cur, 'l')
dfs(cur.right, cur, 'r')
dfs(root, None, '')
q = deque([(0, s, "")])
vis = defaultdict(lambda: float('inf'), {s: 0})
while q:
steps, cur, path = q.popleft()
if cur == d:
return path
if cur in par and vis[par[cur]] > steps + 1:
vis[par[cur]] = steps + 1
q.append((steps + 1, par[cur], path + 'U'))
if cur in left and vis[left[cur]] > steps + 1:
vis[left[cur]] = steps + 1
q.append((steps + 1, left[cur], path + 'L'))
if cur in right and vis[right[cur]] > steps + 1:
vis[right[cur]] = steps + 1
q.append((steps + 1, right[cur], path + 'R')) | step-by-step-directions-from-a-binary-tree-node-to-another | [Python 3] BFS + Djikstra's algoirthm | chestnut890123 | 0 | 91 | step by step directions from a binary tree node to another | 2,096 | 0.488 | Medium | 28,967 |
https://leetcode.com/problems/step-by-step-directions-from-a-binary-tree-node-to-another/discuss/1612693/Simple-Python-solution.(with-comments) | class Solution:
def getDirections(self, root: Optional[TreeNode], startValue: int, destValue: int) -> str:
def path(root,val,lst,ast):
if root:
lst.append(ast)
if root.val==val:
return True
if path(root.left,val,lst,"L") or path(root.right,val,lst,"R"):
return True
lst.pop()
return False
lst=[]
path(root,startValue,lst," ") #find the path from root to startValue and store it in a list
lst1=lst
lst=[]
path(root,destValue,lst," ")#find the path from root to destValue and store it in a list
lst2=lst
c=0
for i in range(min(len(lst1),len(lst2))):#find the index till where there are common elements (i.e these are unnecessary values that are not part of the actual path )
if lst1[i]==lst2[i]:
c+=1
else:
break
lst1=lst1[c:]
lst1=lst1[::-1]# slice the list with reference to the index value
lst2=lst2[c:]
for i in range(len(lst1)):# turn all the startValue path to U
lst1[i]="U"
ans="".join(lst1)+"".join(lst2)
return ans
``` | step-by-step-directions-from-a-binary-tree-node-to-another | Simple Python solution.(with comments) | NagatoBeast | 0 | 59 | step by step directions from a binary tree node to another | 2,096 | 0.488 | Medium | 28,968 |
https://leetcode.com/problems/step-by-step-directions-from-a-binary-tree-node-to-another/discuss/1612246/easy-to-understand%3A-bfs-twice | class Solution:
def getDirections(self, root: Optional[TreeNode], startValue: int, destValue: int) -> str:
graph = defaultdict(set) # from.val -> (dest_node, 'L')
que = deque([root])
while que:
size = len(que)
for _ in range(size):
node = que.popleft()
if node.left:
que.append(node.left)
graph[node.val].add((node.left, 'L'))
graph[node.left.val].add((node, 'U'))
if node.right:
que.append(node.right)
graph[node.val].add((node.right, 'R'))
graph[node.right.val].add((node, 'U'))
que = deque([(startValue, '')])
visited = set([startValue])
while que:
cnt, path = que.popleft()
if cnt == destValue:
return path
for nei, label in graph[cnt]:
if nei.val in visited:
continue
que.append([nei.val, path + label])
visited.add(nei.val) | step-by-step-directions-from-a-binary-tree-node-to-another | easy to understand: bfs twice | mtx2d | 0 | 61 | step by step directions from a binary tree node to another | 2,096 | 0.488 | Medium | 28,969 |
https://leetcode.com/problems/valid-arrangement-of-pairs/discuss/1612010/Python3-Hierholzer's-algo | class Solution:
def validArrangement(self, pairs: List[List[int]]) -> List[List[int]]:
graph = defaultdict(list)
degree = defaultdict(int) # net out degree
for x, y in pairs:
graph[x].append(y)
degree[x] += 1
degree[y] -= 1
for k in degree:
if degree[k] == 1:
x = k
break
ans = []
def fn(x):
"""Return Eulerian path via dfs."""
while graph[x]: fn(graph[x].pop())
ans.append(x)
fn(x)
ans.reverse()
return [[ans[i], ans[i+1]] for i in range(len(ans)-1)] | valid-arrangement-of-pairs | [Python3] Hierholzer's algo | ye15 | 32 | 1,400 | valid arrangement of pairs | 2,097 | 0.41 | Hard | 28,970 |
https://leetcode.com/problems/valid-arrangement-of-pairs/discuss/1612010/Python3-Hierholzer's-algo | class Solution:
def validArrangement(self, pairs: List[List[int]]) -> List[List[int]]:
graph = defaultdict(list)
degree = defaultdict(int) # net out degree
for x, y in pairs:
graph[x].append(y)
degree[x] += 1
degree[y] -= 1
for k in degree:
if degree[k] == 1:
x = k
break
ans = []
stack = [x]
while stack:
while graph[stack[-1]]:
stack.append(graph[stack[-1]].pop())
ans.append(stack.pop())
ans.reverse()
return [[ans[i], ans[i+1]] for i in range(len(ans)-1)] | valid-arrangement-of-pairs | [Python3] Hierholzer's algo | ye15 | 32 | 1,400 | valid arrangement of pairs | 2,097 | 0.41 | Hard | 28,971 |
https://leetcode.com/problems/valid-arrangement-of-pairs/discuss/1616288/Python-O(V%2BE)-by-Euler-path-w-Visualization | class Solution:
def validArrangement(self, pairs: List[List[int]]) -> List[List[int]]:
# in degree table for each node
in_degree = defaultdict(int)
# out degree table for each node
out_degree = defaultdict(int)
# adjacency matrix for each node
adj_matrix = defaultdict(list)
# update table with input edge pairs
for src, dst in pairs:
in_degree[dst] += 1
out_degree[src] += 1
adj_matrix[src].append(dst)
## Case_#1:
# There is eular circuit in graph, any arbitrary node can be start point, here we use source node of first edge just for convenience
start_node_idx = pairs[0][0]
## Case_#2
# There is no eular circuit. But there is eular path, find the start node by indegree and outdegree relation
for node in adj_matrix:
# find the node whose outdegree is one more than indegree
if out_degree[node] - in_degree[node] == 1:
start_node_idx = node
break
# ------------------------------------------------
def eular_path( adjMatrix, path, cur_node):
# Keep traverse to next node in DFS until all edges of current node are visited
while adjMatrix[cur_node]:
# pop one edge and get next visit node
next_visit_node = adjMatrix[cur_node].pop()
eular_path( adjMatrix, path, next_visit_node )
# post-order style
# current explorer is finished, record current edge pair
path.append([cur_node, next_visit_node])
# ------------------------------------------------
record = []
eular_path(adj_matrix, record, start_node_idx)
# reversed of post-order record is the answer of eular path
return reversed(record) | valid-arrangement-of-pairs | Python O(V+E) by Euler path [w/ Visualization] | brianchiang_tw | 1 | 116 | valid arrangement of pairs | 2,097 | 0.41 | Hard | 28,972 |
https://leetcode.com/problems/find-subsequence-of-length-k-with-the-largest-sum/discuss/1705383/Python-Simple-Solution-or-100-Time | class Solution:
def maxSubsequence(self, nums: List[int], k: int) -> List[int]:
tuple_heap = [] # Stores (value, index) as min heap
for i, val in enumerate(nums):
if len(tuple_heap) == k:
heappushpop(tuple_heap, (val, i)) # To prevent size of heap growing larger than k
else:
heappush(tuple_heap, (val, i))
# heap now contains only the k largest elements with their indices as well.
tuple_heap.sort(key=lambda x: x[1]) # To get the original order of values. That is why we sort it by index(x[1]) & not value(x[0])
ans = []
for i in tuple_heap:
ans.append(i[0])
return ans | find-subsequence-of-length-k-with-the-largest-sum | Python Simple Solution | 100% Time | anCoderr | 10 | 806 | find subsequence of length k with the largest sum | 2,099 | 0.425 | Easy | 28,973 |
https://leetcode.com/problems/find-subsequence-of-length-k-with-the-largest-sum/discuss/1635474/Python-optimized-solution-with-heap | class Solution:
def maxSubsequence(self, nums: List[int], k: int) -> List[int]:
import heapq
h = []
n = len(nums)
for i in range(n):
heapq.heappush(h, (-nums[i], i))
res = []
for _ in range(k):
v, idx = heapq.heappop(h)
res.append(idx)
res.sort()
return [nums[idx] for idx in res] | find-subsequence-of-length-k-with-the-largest-sum | Python optimized solution with heap | byuns9334 | 2 | 263 | find subsequence of length k with the largest sum | 2,099 | 0.425 | Easy | 28,974 |
https://leetcode.com/problems/find-subsequence-of-length-k-with-the-largest-sum/discuss/1626859/Easy-python3-solution | class Solution:
def maxSubsequence(self, nums: List[int], k: int) -> List[int]:
valindex=sorted([(num,i) for i,num in enumerate(nums)],reverse=True)
return [num for num,i in sorted(valindex[:k],key=lambda x:x[1])] | find-subsequence-of-length-k-with-the-largest-sum | Easy python3 solution | Karna61814 | 2 | 157 | find subsequence of length k with the largest sum | 2,099 | 0.425 | Easy | 28,975 |
https://leetcode.com/problems/find-subsequence-of-length-k-with-the-largest-sum/discuss/2779624/python-heap | class Solution:
def maxSubsequence(self, nums: List[int], k: int) -> List[int]:
min_heap = []
for i, n in enumerate(nums):
heappush(min_heap, (n, i))
if len(min_heap) > k:
heappop(min_heap)
min_heap.sort(key = lambda x: x[1])
return [i[0] for i in min_heap] | find-subsequence-of-length-k-with-the-largest-sum | python heap | JasonDecode | 1 | 22 | find subsequence of length k with the largest sum | 2,099 | 0.425 | Easy | 28,976 |
https://leetcode.com/problems/find-subsequence-of-length-k-with-the-largest-sum/discuss/2390383/Python-all-solutions-using-sort-and-heap-or-sort-or-heap-or-one-liner | class Solution:
def maxSubsequence(self, nums: List[int], k: int) -> List[int]:
arr = [(nums[i], i) for i in range(len(nums))]
arr.sort(reverse=True)
arr = arr[:k]
arr.sort(key=lambda k: k[1])
return [val[0] for val in arr] | find-subsequence-of-length-k-with-the-largest-sum | Python all solutions using sort and heap | sort | heap | one-liner | wilspi | 1 | 155 | find subsequence of length k with the largest sum | 2,099 | 0.425 | Easy | 28,977 |
https://leetcode.com/problems/find-subsequence-of-length-k-with-the-largest-sum/discuss/2390383/Python-all-solutions-using-sort-and-heap-or-sort-or-heap-or-one-liner | class Solution:
def maxSubsequence(self, nums: List[int], k: int) -> List[int]:
return [
nums[x]
for x in sorted(
sorted(range(len(nums)), key=lambda k: nums[k], reverse=True)[:k]
)
] | find-subsequence-of-length-k-with-the-largest-sum | Python all solutions using sort and heap | sort | heap | one-liner | wilspi | 1 | 155 | find subsequence of length k with the largest sum | 2,099 | 0.425 | Easy | 28,978 |
https://leetcode.com/problems/find-subsequence-of-length-k-with-the-largest-sum/discuss/2390383/Python-all-solutions-using-sort-and-heap-or-sort-or-heap-or-one-liner | class Solution:
def maxSubsequence(self, nums: List[int], k: int) -> List[int]:
arr = [(-nums[i], i) for i in range(len(nums))]
heapq.heapify(arr)
ans = []
while k > 0:
ans.append(heapq.heappop(arr))
k -= 1
ans.sort(key=lambda k: k[1])
return [-val[0] for val in ans] | find-subsequence-of-length-k-with-the-largest-sum | Python all solutions using sort and heap | sort | heap | one-liner | wilspi | 1 | 155 | find subsequence of length k with the largest sum | 2,099 | 0.425 | Easy | 28,979 |
https://leetcode.com/problems/find-subsequence-of-length-k-with-the-largest-sum/discuss/1732750/Python-3-using-Heap | class Solution:
def maxSubsequence(self, nums: List[int], k: int) -> List[int]:
nums = [[-nums[i],i] for i in range(len(nums))]
heapq.heapify(nums)
ans,fin = [],[]
for i in range(k):
ans.append(heapq.heappop(nums)[::-1])
heapq.heapify(ans)
for i in range(len(ans)):
fin.append(-1*heapq.heappop(ans)[1])
return fin | find-subsequence-of-length-k-with-the-largest-sum | Python 3 using Heap | akshaiy_14 | 1 | 161 | find subsequence of length k with the largest sum | 2,099 | 0.425 | Easy | 28,980 |
https://leetcode.com/problems/find-subsequence-of-length-k-with-the-largest-sum/discuss/1624081/Intuitive-approach-by-two-sorting. | class Solution:
def maxSubsequence(self, nums: List[int], k: int) -> List[int]:
# transform nums into nums_with_index and sort it according to value.
# decreasingly
# . e.g.:
# (3, 1, 2) -> ((0, 3), (1, 1), (2, 2))
# -> ((0, 3), (2, 2), (1, 1))
nums_with_index = sorted(
[(i, n) for i, n in enumerate(nums)],
key=lambda t: t[1],
reverse=True
)
# Retrieve the top K element from nums_with_index and sort it with
# position index increasingly. Finally, transform it again by retrieve
# the value of position index from nums
return list(map(
lambda t: nums[t[0]],
sorted(nums_with_index[:k], key=lambda t: t[0]))) | find-subsequence-of-length-k-with-the-largest-sum | Intuitive approach by two sorting. | puremonkey2001 | 1 | 82 | find subsequence of length k with the largest sum | 2,099 | 0.425 | Easy | 28,981 |
https://leetcode.com/problems/find-subsequence-of-length-k-with-the-largest-sum/discuss/1623315/Python3-O(N)-quick-select | class Solution:
def maxSubsequence(self, nums: List[int], k: int) -> List[int]:
temp = nums[:]
shuffle(temp)
def part(lo, hi):
"""Return partition of nums[lo:hi]."""
i, j = lo+1, hi-1
while i <= j:
if temp[i] < temp[lo]: i += 1
elif temp[j] > temp[lo]: j -= 1
else:
temp[i], temp[j] = temp[j], temp[i]
i += 1
j -= 1
temp[lo], temp[j] = temp[j], temp[lo]
return j
lo, hi = 0, len(temp)
while lo <= hi:
mid = part(lo, hi)
if mid < len(temp)-k: lo += 1
elif mid == len(temp)-k: break
else: hi = mid
threshold = temp[mid]
larger = sum(x > threshold for x in nums)
equal = k - larger
ans = []
for x in nums:
if x > threshold: ans.append(x)
elif x == threshold:
if equal:
equal -= 1
ans.append(x)
return ans | find-subsequence-of-length-k-with-the-largest-sum | [Python3] O(N) quick select | ye15 | 1 | 242 | find subsequence of length k with the largest sum | 2,099 | 0.425 | Easy | 28,982 |
https://leetcode.com/problems/find-subsequence-of-length-k-with-the-largest-sum/discuss/2847367/Python3-solution | class Solution:
def maxSubsequence(self, nums: List[int], k: int) -> List[int]:
if (len(nums) == k):
return nums
for i in range(len(nums) - k):
nums.remove(min(nums))
return nums | find-subsequence-of-length-k-with-the-largest-sum | Python3 solution | SupriyaArali | 0 | 1 | find subsequence of length k with the largest sum | 2,099 | 0.425 | Easy | 28,983 |
https://leetcode.com/problems/find-subsequence-of-length-k-with-the-largest-sum/discuss/2712078/python-99-faster-2-lines-of-code-easy | class Solution:
def maxSubsequence(self, nums: List[int], k: int) -> List[int]:
for i in range(len(nums)-k):
nums.remove(min(nums))
return nums | find-subsequence-of-length-k-with-the-largest-sum | python 99% faster 2 lines of code easy | Raghunath_Reddy | 0 | 14 | find subsequence of length k with the largest sum | 2,099 | 0.425 | Easy | 28,984 |
https://leetcode.com/problems/find-subsequence-of-length-k-with-the-largest-sum/discuss/2669224/Easy-python-solution-using-sorting | class Solution:
def maxSubsequence(self, nums: List[int], k: int) -> List[int]:
a=Counter(sorted(nums,reverse=True)[:k])
ans=[]
for i in nums:
if i in a:
ans.append(i)
a[i]-=1
if a[i]==0:
del a[i]
return ans | find-subsequence-of-length-k-with-the-largest-sum | Easy python solution using sorting | prateek4463 | 0 | 5 | find subsequence of length k with the largest sum | 2,099 | 0.425 | Easy | 28,985 |
https://leetcode.com/problems/find-subsequence-of-length-k-with-the-largest-sum/discuss/2363395/Easy-python-heap | class Solution:
def maxSubsequence(self, nums: List[int], k: int) -> List[int]:
val_idx_heap = []
for i,val in enumerate(nums):
if len(val_idx_heap)==k:
heappushpop(val_idx_heap,(val,i))
else:
heappush(val_idx_heap,(val,i))
val_idx_heap.sort(key=lambda x: x[1])
ans=[]
for i in range(k):
ans.append(val_idx_heap[i][0])
return ans | find-subsequence-of-length-k-with-the-largest-sum | Easy python heap | sunakshi132 | 0 | 68 | find subsequence of length k with the largest sum | 2,099 | 0.425 | Easy | 28,986 |
https://leetcode.com/problems/find-subsequence-of-length-k-with-the-largest-sum/discuss/2254289/A-hidden-power-of-sort()-faster-than-99.91 | class Solution:
def maxSubsequence(self, nums: List[int], k: int) -> List[int]:
val_n_index = [(i, n) for i, n in enumerate(nums)]
val_n_index.sort(reverse=True, key=lambda t: t[1])
val_n_index = val_n_index[:k]
val_n_index.sort(key=lambda t: t[0])
return [i[1] for i in val_n_index] | find-subsequence-of-length-k-with-the-largest-sum | A hidden power of sort(π΄), faster than 99.91% | amaargiru | 0 | 112 | find subsequence of length k with the largest sum | 2,099 | 0.425 | Easy | 28,987 |
https://leetcode.com/problems/find-subsequence-of-length-k-with-the-largest-sum/discuss/2223187/Python-Solution | class Solution:
def maxSubsequence(self, nums: List[int], k: int) -> List[int]:
nums2=sorted(nums,reverse=True)[:k]
li=[]
for i in nums:
if i in nums2:
li.append(i)
nums2.remove(i)
return li | find-subsequence-of-length-k-with-the-largest-sum | Python Solution | SakshiMore22 | 0 | 76 | find subsequence of length k with the largest sum | 2,099 | 0.425 | Easy | 28,988 |
https://leetcode.com/problems/find-subsequence-of-length-k-with-the-largest-sum/discuss/2134162/Memory-Usage%3A-14.1-MB-less-than-95.39-of-Python3 | class Solution:
def maxSubsequence(self, nums: List[int], k: int) -> List[int]:
res, max_k = [], sorted(nums, reverse=True)[:k]
for num in nums:
if num in max_k:
res.append(num)
max_k.remove(num)
if len(max_k) == 0:
return res | find-subsequence-of-length-k-with-the-largest-sum | Memory Usage: 14.1 MB, less than 95.39% of Python3 | writemeom | 0 | 101 | find subsequence of length k with the largest sum | 2,099 | 0.425 | Easy | 28,989 |
https://leetcode.com/problems/find-subsequence-of-length-k-with-the-largest-sum/discuss/2047183/Python-Solution | class Solution:
def maxSubsequence(self, nums: List[int], k: int) -> List[int]:
arr = sorted(nums)
for i in range(len(nums) - k):
nums.remove(arr[i])
return nums | find-subsequence-of-length-k-with-the-largest-sum | Python Solution | hgalytoby | 0 | 139 | find subsequence of length k with the largest sum | 2,099 | 0.425 | Easy | 28,990 |
https://leetcode.com/problems/find-subsequence-of-length-k-with-the-largest-sum/discuss/1988282/Python-3-line-Easy-Solution-with-Sorting-beats-98 | class Solution:
def maxSubsequence(self, nums: List[int], k: int) -> List[int]:
# sort by value in descending order, keep track of original indices
nums = sorted(enumerate(nums), key=lambda x: x[1], reverse=True)
# sort k large numbers by original indices (as it's supposed to be a sequence)
snums = sorted(nums[:k])
# get rid of the indices, and return only the numbers
return [x[1] for x in snums] | find-subsequence-of-length-k-with-the-largest-sum | Python 3-line Easy Solution with Sorting [beats 98%] | back2square1 | 0 | 79 | find subsequence of length k with the largest sum | 2,099 | 0.425 | Easy | 28,991 |
https://leetcode.com/problems/find-subsequence-of-length-k-with-the-largest-sum/discuss/1969139/Python-Easy-Soluction-or-Beats-99-submits | class Solution:
def maxSubsequence(self, nums: List[int], k: int) -> List[int]:
ans = sorted(nums)[-k:]
for n in nums :
if ans :
if n in ans :
ans.remove(n)
yield n
else :
break | find-subsequence-of-length-k-with-the-largest-sum | [ Python ] Easy Soluction | Beats 99% submits | crazypuppy | 0 | 124 | find subsequence of length k with the largest sum | 2,099 | 0.425 | Easy | 28,992 |
https://leetcode.com/problems/find-subsequence-of-length-k-with-the-largest-sum/discuss/1947107/Python-Fast-and-Efficient-Solution-Using-Sorting-%2B-heapq | class Solution:
def maxSubsequence(self, nums: List[int], k: int) -> List[int]:
if len(nums) == k:
return nums
num_idx = []
for i, e in enumerate(nums):
num_idx.append((e, i))
heapq.heapify(num_idx)
res = heapq.nlargest(k, num_idx)
res = sorted(res, key = lambda x : x[1])
return [i[0] for i in res] | find-subsequence-of-length-k-with-the-largest-sum | Python Fast & Efficient Solution Using Sorting + heapq | Hejita | 0 | 69 | find subsequence of length k with the largest sum | 2,099 | 0.425 | Easy | 28,993 |
https://leetcode.com/problems/find-subsequence-of-length-k-with-the-largest-sum/discuss/1810435/1-Line-Python-Solution-oror-82-Faster-oror-Memory-less-than-85 | class Solution:
def maxSubsequence(self, nums: List[int], k: int) -> List[int]:
return [val for idx,val in sorted(sorted(enumerate(nums), key=lambda x: -x[1])[:k], key=lambda x: x[0])] | find-subsequence-of-length-k-with-the-largest-sum | 1-Line Python Solution || 82% Faster || Memory less than 85% | Taha-C | 0 | 134 | find subsequence of length k with the largest sum | 2,099 | 0.425 | Easy | 28,994 |
https://leetcode.com/problems/find-subsequence-of-length-k-with-the-largest-sum/discuss/1721023/Python3-accepted-solution | class Solution:
def maxSubsequence(self, nums: List[int], k: int) -> List[int]:
ans = []
li = sorted(nums)[len(nums)-k:]
for i in range(len(nums)):
if(nums[i] in li and ans.count(nums[i])<li.count(nums[i])):
ans.append(nums[i])
return ans | find-subsequence-of-length-k-with-the-largest-sum | Python3 accepted solution | sreeleetcode19 | 0 | 116 | find subsequence of length k with the largest sum | 2,099 | 0.425 | Easy | 28,995 |
https://leetcode.com/problems/find-subsequence-of-length-k-with-the-largest-sum/discuss/1691009/Python-clean-noob-solution-with-99.9 | class Solution:
def maxSubsequence(self, nums: List[int], k: int) -> List[int]:
result = []
for i,j in enumerate(nums):
if len(result)==k:
heappushpop(result,(j,i))
else:
heappush(result,(j,i))
# print(result)
ans = []
result.sort(key=lambda x:x[1])
for i in result:
ans.append(i[0])
return ans | find-subsequence-of-length-k-with-the-largest-sum | Python clean noob solution with 99.9% | Brillianttyagi | 0 | 139 | find subsequence of length k with the largest sum | 2,099 | 0.425 | Easy | 28,996 |
https://leetcode.com/problems/find-subsequence-of-length-k-with-the-largest-sum/discuss/1646945/Python-2-lines-not-very-clear-%3A) | class Solution:
def maxSubsequence(self, nums: List[int], k: int) -> List[int]:
A = sorted(enumerate(nums), key=lambda t: (-t[1], t[0]))
return [v for i, v in sorted(A[:k], key=lambda t: t[0])] | find-subsequence-of-length-k-with-the-largest-sum | Python, 2 lines, not very clear :) | emwalker | 0 | 86 | find subsequence of length k with the largest sum | 2,099 | 0.425 | Easy | 28,997 |
https://leetcode.com/problems/find-subsequence-of-length-k-with-the-largest-sum/discuss/1641278/one-line-python | class Solution:
def maxSubsequence(self, nums: List[int], k: int) -> List[int]:
return next(zip(*sorted(sorted([(v, i) for i, v in enumerate(nums)], reverse=True)[:k], key=lambda x: x[1]))) | find-subsequence-of-length-k-with-the-largest-sum | one-line python | Hoke_luo | 0 | 103 | find subsequence of length k with the largest sum | 2,099 | 0.425 | Easy | 28,998 |
https://leetcode.com/problems/find-subsequence-of-length-k-with-the-largest-sum/discuss/1627346/Two-times-sorting-100-speed | class Solution:
def maxSubsequence(self, nums: List[int], k: int) -> List[int]:
return [n for n, i in sorted(sorted((n, i) for i, n in
enumerate(nums))[-k:],
key=lambda tpl: tpl[1])] | find-subsequence-of-length-k-with-the-largest-sum | Two times sorting, 100% speed | EvgenySH | 0 | 108 | find subsequence of length k with the largest sum | 2,099 | 0.425 | Easy | 28,999 |
Subsets and Splits