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/check-if-a-string-can-break-another-string/discuss/1074828/Python-clean-super-easy-to-read-code! | class Solution:
def checkIfCanBreak(self, s1: str, s2: str) -> bool:
a = [ord(i) for i in s1]
b = [ord(j) for j in s2]
a.sort()
b.sort()
a_breaks_b = True
b_breaks_a = True
for i in range(len(a)):
if a[i] < b[i]: a_breaks_b = False
if a[i] > b[i]: b_breaks_a = False
return a_breaks_b or b_breaks_a | check-if-a-string-can-break-another-string | Python clean, super easy to read code! | dev-josh | 0 | 47 | check if a string can break another string | 1,433 | 0.689 | Medium | 21,400 |
https://leetcode.com/problems/check-if-a-string-can-break-another-string/discuss/727919/Python-O(nlogn)-with-O(1)-space | class Solution:
def checkIfCanBreak(self, s1: str, s2: str) -> bool:
s1 = sorted(s1)
s2 = sorted(s2)
count1 = 0
count2 = 0
for i in range(0 , len(s1)):
if s2[i] >= s1[i]:
count1 +=1
if s1[i] >= s2[i]:
count2 += 1
if count1== len(s1) or count2 == len(s1):
return True
return False | check-if-a-string-can-break-another-string | Python O(nlogn) with O(1) space | Hiteshsaai | 0 | 60 | check if a string can break another string | 1,433 | 0.689 | Medium | 21,401 |
https://leetcode.com/problems/check-if-a-string-can-break-another-string/discuss/683558/Python-faster-than-100-count-vs-counter | class Solution:
def checkIfCanBreak(self, s1: str, s2: str) -> bool:
firstBreaks = True
secondBreaks = True
diff = 0
for ch in string.ascii_lowercase:
diff += s1.count(ch) - s2.count(ch)
if diff > 0:
firstBreaks = False
if diff < 0:
secondBreaks = False
return firstBreaks or secondBreaks | check-if-a-string-can-break-another-string | [Python] faster than 100%, count vs counter | EgorMatirov | 0 | 172 | check if a string can break another string | 1,433 | 0.689 | Medium | 21,402 |
https://leetcode.com/problems/check-if-a-string-can-break-another-string/discuss/643562/Intuitive-approach-by-sorting-and-comparison | class Solution:
def checkIfCanBreak(self, s1: str, s2: str) -> bool:
s1_list = sorted(s1)
s2_list = sorted(s2)
return all([s1_list[i] >= s2_list[i] for i in range(len(s1_list))]) or \
all([s1_list[i] <= s2_list[i] for i in range(len(s1_list))]) | check-if-a-string-can-break-another-string | Intuitive approach by sorting and comparison | puremonkey2001 | 0 | 50 | check if a string can break another string | 1,433 | 0.689 | Medium | 21,403 |
https://leetcode.com/problems/check-if-a-string-can-break-another-string/discuss/609563/Python%3A-Sort-and-Check-if-the-string-cuts. | class Solution:
def checkIfCanBreak(self, s1: str, s2: str) -> bool:
s1 = sorted(s1)
s2 = sorted(s2)
f1 = [c for i, c in enumerate(s1) if s1[i] != s2[i]]
f2 = [c for i, c in enumerate(s2) if s2[i] != s1[i]]
def check(f1, f2):
fg = True
for i, c in enumerate(f1):
if f1[i] < f2[i]:
fg = False
break
return fg
r = check(f1, f2)
s = check(f2, f1)
return r or s | check-if-a-string-can-break-another-string | Python: Sort and Check if the string cuts. | cppygod | 0 | 41 | check if a string can break another string | 1,433 | 0.689 | Medium | 21,404 |
https://leetcode.com/problems/check-if-a-string-can-break-another-string/discuss/608918/Python3-sorting | class Solution:
def checkIfCanBreak(self, s1: str, s2: str) -> bool:
s1, s2 = sorted(s1), sorted(s2)
return all(c1 <= c2 for c1, c2 in zip(s1, s2)) or all(c1 >= c2 for c1, c2 in zip(s1, s2)) | check-if-a-string-can-break-another-string | [Python3] sorting | ye15 | 0 | 35 | check if a string can break another string | 1,433 | 0.689 | Medium | 21,405 |
https://leetcode.com/problems/check-if-a-string-can-break-another-string/discuss/608602/Python3-2-Liner-Simple-Sort-%2B-Greedy-N-logN | class Solution:
def checkIfCanBreak(self, s1: str, s2: str) -> bool:
s1, s2 = sorted([char for char in s1]), sorted([char for char in s2])
return all([s1[i] >= s2[i] for i in range(len(s1))]) or all([s1[i] <= s2[i] for i in range(len(s1))]) | check-if-a-string-can-break-another-string | [Python3] 2 Liner Simple, Sort + Greedy N logN | ilkercankaya | 0 | 53 | check if a string can break another string | 1,433 | 0.689 | Medium | 21,406 |
https://leetcode.com/problems/number-of-ways-to-wear-different-hats-to-each-other/discuss/608721/Python-dp-with-bit-mask-memorization | class Solution:
def numberWays(self, hats: List[List[int]]) -> int:
n = len(hats)
h2p = collections.defaultdict(list)
for p, hs in enumerate(hats):
for h in hs:
h2p[h].append(p)
full_mask = (1 << n) - 1
mod = 10**9 + 7
@functools.lru_cache(maxsize=None)
def count(h, mask):
# everyone wears a hat
if mask == full_mask:
return 1
# ran out of hats
if h == 41:
return 0
# skip the current hat h
ans = count(h + 1, mask)
for p in h2p[h]:
# if person p already has a hat
if mask & (1 << p):
continue
# let person p wear hat h
ans += count(h + 1, mask | (1 << p))
ans %= mod
return ans
# start from the first hat and no one wearing any hat
return count(1, 0) | number-of-ways-to-wear-different-hats-to-each-other | Python dp with bit mask memorization | ChelseaChenC | 2 | 246 | number of ways to wear different hats to each other | 1,434 | 0.429 | Hard | 21,407 |
https://leetcode.com/problems/number-of-ways-to-wear-different-hats-to-each-other/discuss/1740645/Python-two-approaches-to-bottom-up-DP-that-use-bit-masks | class Solution:
def numberWays(self, hats: List[List[int]]) -> int:
# use hat masks in bottom up dp
n_hats, n_persons = 40, len(hats)
dp = [collections.defaultdict(int) for i in range(n_persons + 1)]
# dp[i] = dict hat_mask -> count using [:i] persons
curr = dp[0]
curr[0] = 1
prev = curr
for i in range(n_persons):
curr = dp[i + 1]
for key in prev:
curr[key] += prev[key]
for h in hats[i]:
bit = 1 << (h - 1)
for hat_mask in prev:
if bit & hat_mask == 0:
curr[bit | hat_mask] += prev[hat_mask]
prev = curr
# answer is sum over all masks with n_persons 1 bits
masks = []
for m in dp[n_persons]:
count, mm = 0, m
while mm:
count += 1
mm = mm & (mm - 1)
if count == n_persons:
masks.append(m)
return sum(dp[n_persons][m] for m in masks) % 1000000007 | number-of-ways-to-wear-different-hats-to-each-other | [Python] two approaches to bottom up DP that use bit masks | endurance | 1 | 102 | number of ways to wear different hats to each other | 1,434 | 0.429 | Hard | 21,408 |
https://leetcode.com/problems/number-of-ways-to-wear-different-hats-to-each-other/discuss/1740645/Python-two-approaches-to-bottom-up-DP-that-use-bit-masks | class Solution:
def numberWays(self, hats: List[List[int]]) -> int:
# use person masks in bottom up dp
n_hats, n_persons = 40, len(hats)
n_masks = 1 << n_persons
persons = [[] for _ in range(n_hats)]
for person, arr in enumerate(hats):
for hat in arr:
persons[hat - 1].append(person) # hat is one based
dp = [[0 for person_mask in range(n_masks)] for i in range(n_hats + 1)]
# dp[i][person_mask] = count using [:i] hats
curr = dp[0]
curr[0] = 1
prev = curr
for i in range(n_hats):
curr = dp[i + 1]
for person_mask in range(n_masks):
curr[person_mask] += prev[person_mask]
for person in persons[i]:
bit = 1 << person
for person_mask in range(n_masks):
if bit & person_mask == 0:
curr[bit | person_mask] += prev[person_mask]
prev = curr
return curr[(1 << n_persons) - 1] % 1000000007 | number-of-ways-to-wear-different-hats-to-each-other | [Python] two approaches to bottom up DP that use bit masks | endurance | 1 | 102 | number of ways to wear different hats to each other | 1,434 | 0.429 | Hard | 21,409 |
https://leetcode.com/problems/number-of-ways-to-wear-different-hats-to-each-other/discuss/1055840/Python3-Beats-100-DP-Bottom-Up-Solution | class Solution:
def numberWays(self, hats: List[List[int]]) -> int:
N = len(hats) # number of people
h2p = collections.defaultdict(list) # hat -> people
for person in range(N):
for hat in hats[person]:
h2p[hat].append(person)
if len(h2p) < N: # when the number of hats < the number of people
return 0
# For each hat, dp stores the status of the people has been matched by a hat.
# e.g. 0b0000000000 means no one wears a hat
# 0b0010000000 means only person No.2 wears a hat
# There are totally 2 ^ N different possible status.
MASK = [1 << p for p in range(N)]
dp = [[0] * (2 ** N) for _ in range(len(h2p) + 1)]
dp[0][0] = 1
i, MOD = 1, 1000000007
while h2p: # O(H)
_, people = h2p.popitem()
for j, n in enumerate(dp[i - 1]): #O(2^P)
if not n:
continue
dp[i][j] += n # when mask = 0
for p in people: #O(P)
if not (MASK[p] & j):
dp[i][MASK[p] + j] += n
i += 1
return dp[-1][-1] % MOD | number-of-ways-to-wear-different-hats-to-each-other | [Python3] Beats 100%, DP Bottom Up Solution | licpotis | 1 | 195 | number of ways to wear different hats to each other | 1,434 | 0.429 | Hard | 21,410 |
https://leetcode.com/problems/destination-city/discuss/1664716/98-faster-easy-python-solution-based-on-question-no.-997 | class Solution:
def destCity(self, paths: List[List[str]]) -> str:
lst=[]
arr=[]
for i in paths:
lst.append(i[0])
arr.append(i[1])
ptr=set(lst)
ptr2=set(arr)
return list(ptr2-ptr)[0] | destination-city | 98% faster easy python solution based on question no. 997 | amannarayansingh10 | 9 | 437 | destination city | 1,436 | 0.776 | Easy | 21,411 |
https://leetcode.com/problems/destination-city/discuss/1169405/Python-or-Using-Dictionary | class Solution:
def destCity(self, paths: List[List[str]]) -> str:
d = dict(paths)
for i in d.values():
if i not in d.keys():
return i | destination-city | Python | Using Dictionary | hirrangd | 8 | 314 | destination city | 1,436 | 0.776 | Easy | 21,412 |
https://leetcode.com/problems/destination-city/discuss/2573469/SIMPLE-PYTHON3-SOLUTION-using-sets | class Solution:
def destCity(self, paths: List[List[str]]) -> str:
source = set()
dest = set()
for l in paths:
source.add(l[0])
dest.add(l[1])
return list(dest - source)[0] | destination-city | ✅✔ SIMPLE PYTHON3 SOLUTION ✅✔ using sets | rajukommula | 4 | 219 | destination city | 1,436 | 0.776 | Easy | 21,413 |
https://leetcode.com/problems/destination-city/discuss/2029752/Python-3-Lines-Set-Based | class Solution:
def destCity(self, paths: List[List[str]]) -> str:
srcs = {src for src, _ in paths}
dests = {dest for _, dest in paths}
return (dests - srcs).pop() | destination-city | Python 3 Lines, Set-Based | indolentllama | 2 | 106 | destination city | 1,436 | 0.776 | Easy | 21,414 |
https://leetcode.com/problems/destination-city/discuss/1057730/simple-python-solution-faster-than-93.14-and-less-than-77.87 | class Solution:
def destCity(self, paths: List[List[str]]) -> str:
city_from, city_to = [], []
for i in range(len(paths)):
city_from.append(paths[i][0])
city_to.append(paths[i][1])
for city in city_to:
if city not in city_from:
return city | destination-city | simple python solution faster than 93.14% and less than 77.87% | The-Dude | 2 | 159 | destination city | 1,436 | 0.776 | Easy | 21,415 |
https://leetcode.com/problems/destination-city/discuss/610050/Python-sol-by-set-operation-w-Comment | class Solution:
def destCity(self, paths: List[List[str]]) -> str:
all_cities = set()
src_cities = set()
# Update all cities and source cities
for start_city, end_city in paths:
all_cities.add( start_city )
all_cities.add( end_city )
src_cities.add( start_city )
# Destination city never shows up in source cities
# The only element remains in the difference set is the destination city
return (all_cities - src_cities).pop() | destination-city | Python sol by set operation [w/ Comment] | brianchiang_tw | 2 | 280 | destination city | 1,436 | 0.776 | Easy | 21,416 |
https://leetcode.com/problems/destination-city/discuss/1980565/Python-(Simple-Approach-and-Beginner-Friendly) | class Solution:
def destCity(self, paths: List[List[str]]) -> str:
dest = []
arr = []
if len(paths) == 1:
return paths[0][-1]
else:
for i in paths:
dest.append(i[-1])
for i in paths:
arr.append(i[0])
for i in dest:
if i not in arr:
return i | destination-city | Python (Simple Approach and Beginner-Friendly) | vishvavariya | 1 | 82 | destination city | 1,436 | 0.776 | Easy | 21,417 |
https://leetcode.com/problems/destination-city/discuss/1199095/Python3-Simple-Solution | class Solution:
def destCity(self, paths: List[List[str]]) -> str:
def find_start(s , paths):
for i in range(len(paths)):
start , stop = paths[i]
if(start == s):
return i
return None
i = 0
for _ in range(len(paths)):
start , dest = paths[i]
i = find_start(dest , paths)
if(i == None):
return dest | destination-city | [Python3] Simple Solution | VoidCupboard | 1 | 94 | destination city | 1,436 | 0.776 | Easy | 21,418 |
https://leetcode.com/problems/destination-city/discuss/1115862/Python-simple-solution-using-set-difference | class Solution:
def destCity(self, paths: List[List[str]]) -> str:
s1 = set(x for x,y in paths)
s2 = set(y for x,y in paths)
return (s2 - s1).pop() | destination-city | Python - simple solution using set difference | waltersm1 | 1 | 185 | destination city | 1,436 | 0.776 | Easy | 21,419 |
https://leetcode.com/problems/destination-city/discuss/609844/Python3-Sets-Easy-to-understand | class Solution:
def destCity(self, paths: List[List[str]]) -> str:
visited = set()
started = set()
for p in paths:
visited.add(p[1])
started.add(p[0])
for c in visited.union(started):
if c in visited and c not in started:
return c
return None | destination-city | Python3 Sets Easy to understand | sonaksh | 1 | 102 | destination city | 1,436 | 0.776 | Easy | 21,420 |
https://leetcode.com/problems/destination-city/discuss/609781/Python-simple-solution | class Solution:
def destCity(self, paths: List[List[str]]) -> str:
"""
paths ---> each tuple(c1, c2)
"""
c1 = [c[0] for c in paths]
c2 = [c[1] for c in paths]
for city in c2:
if city not in c1:
return city | destination-city | Python simple solution | var42 | 1 | 252 | destination city | 1,436 | 0.776 | Easy | 21,421 |
https://leetcode.com/problems/destination-city/discuss/609754/Python3-using-set | class Solution:
def destCity(self, paths: List[List[str]]) -> str:
fm, to = zip(*paths)
return (set(to) - set(fm)).pop() | destination-city | [Python3] using set | ye15 | 1 | 93 | destination city | 1,436 | 0.776 | Easy | 21,422 |
https://leetcode.com/problems/destination-city/discuss/2783016/Python-solution-99.28-faster-using-dictionary | class Solution:
def destCity(self, paths: List[List[str]]) -> str:
dict_paths = {}
for path in paths:
for p in path:
if p not in dict_paths:
dict_paths[p] = [1, path.index(p)]
else:
dict_paths[p][0] += 1
destination = ""
for k, v in dict_paths.items():
if v[0] == 1 and v[1] == 1:
destination = k
return destination | destination-city | Python solution 99.28% faster using dictionary | samanehghafouri | 0 | 7 | destination city | 1,436 | 0.776 | Easy | 21,423 |
https://leetcode.com/problems/destination-city/discuss/2768877/Python-Iterative-Easy-Understanding-Solution | class Solution:
def destCity(self, paths: List[List[str]]) -> str:
idx = 0 # START POSITION
while True: # yeah I get it it's bad practice, shoot me.
temp = idx
for dst in range(len(paths)): #find matching destination
if idx!=dst and paths[idx][1] == paths[dst][0]:
idx = dst
break
if temp == idx:
return paths[idx][1] #if no change in planes pos, we assume that this is the end | destination-city | [Python] Iterative Easy Understanding Solution | keioon | 0 | 5 | destination city | 1,436 | 0.776 | Easy | 21,424 |
https://leetcode.com/problems/destination-city/discuss/2747053/Easy-and-Understandable-Solution-with-Set-Python3 | class Solution:
def destCity(self, paths: List[List[str]]) -> str:
set_s = set()
set_d = set()
for path in paths:
set_s.add(path[0])
set_d.add(path[1])
return set_d.difference(set_s).pop() | destination-city | Easy & Understandable Solution with Set Python3 | ben_wei | 0 | 5 | destination city | 1,436 | 0.776 | Easy | 21,425 |
https://leetcode.com/problems/destination-city/discuss/2659731/3-Liner-Solution-or-Easy-to-Understand-or-Python | class Solution(object):
def destCity(self, paths):
hashT = {}
for i in range(len(paths)): hashT[paths[i][0]] = paths[i][1]
for ch in hashT:
if hashT[ch] not in hashT: return hashT[ch] | destination-city | 3 Liner Solution | Easy to Understand | Python | its_krish_here | 0 | 9 | destination city | 1,436 | 0.776 | Easy | 21,426 |
https://leetcode.com/problems/destination-city/discuss/2565492/python-1-liner | class Solution:
def destCity(self, paths: List[List[str]]) -> str:
return set(to_ for from_, to_ in paths).difference(from_ for from_, to_ in paths).pop() | destination-city | python 1-liner | Potentis | 0 | 64 | destination city | 1,436 | 0.776 | Easy | 21,427 |
https://leetcode.com/problems/destination-city/discuss/2421769/Python3-or-map-source-and-destination-and-return-detected-dead-end | class Solution:
def destCity(self, paths: List[List[str]]) -> str:
g = {src:des for src, des in paths}
return [des for src, des in g.items() if des not in g][0] | destination-city | Python3 | map source and destination and return detected dead end | Ploypaphat | 0 | 44 | destination city | 1,436 | 0.776 | Easy | 21,428 |
https://leetcode.com/problems/destination-city/discuss/2136403/Python-Solution-using-set | class Solution:
def destCity(self, paths: List[List[str]]) -> str:
start = set()
for path in paths:
start.add(path[0])
for path in paths:
if not path[1] in start:
return path[1] | destination-city | Python Solution using set | bjrshussain | 0 | 42 | destination city | 1,436 | 0.776 | Easy | 21,429 |
https://leetcode.com/problems/destination-city/discuss/2122222/EASY-and-Simple-using-lists-and-set-oror-beats-81.9-solutions-in-memory-usage. | '''class Solution:
def destCity(self, paths: List[List[str]]) -> str:
total=[]
havepaths=[]
for i in paths:
total.append(i[0])
havepaths.append(i[0])
total.append(i[1])
t=list(set(total))
ans='x'
for j in t:
if j not in havepaths:
ans=j
return ans
print(destCity(paths))''' | destination-city | EASY and Simple using lists and set || beats 81.9% solutions in memory usage. | keertika27 | 0 | 51 | destination city | 1,436 | 0.776 | Easy | 21,430 |
https://leetcode.com/problems/destination-city/discuss/2027989/Python-clean-solution | class Solution:
def destCity(self, paths: List[List[str]]) -> str:
destCities = [x[0] for x in paths]
for i in paths:
if i[1] in destCities:
pass
else:
return i[1] | destination-city | Python clean solution | StikS32 | 0 | 72 | destination city | 1,436 | 0.776 | Easy | 21,431 |
https://leetcode.com/problems/destination-city/discuss/1740241/Python3-using-2-Sets | class Solution:
def destCity(self, paths: List[List[str]]) -> str:
start = set()
stop = set()
for path in paths:
start.add(path[0])
stop.add(path[1])
return stop.difference(start).pop() | destination-city | Python3 using 2 Sets | langyinan | 0 | 153 | destination city | 1,436 | 0.776 | Easy | 21,432 |
https://leetcode.com/problems/destination-city/discuss/1607177/Easy-Python-Solution | class Solution:
def destCity(self, paths: List[List[str]]) -> str:
dict = {}
for j in paths:
if j[0] not in dict:
dict[j[0]] = []
dict[j[0]].append(j[1])
for x,y in dict.items():
for k in y:
if k not in dict:
return k | destination-city | Easy Python Solution | jodyzhou | 0 | 67 | destination city | 1,436 | 0.776 | Easy | 21,433 |
https://leetcode.com/problems/destination-city/discuss/1591930/Python-one-pass-using-two-sets | class Solution:
def destCity(self, paths: List[List[str]]) -> str:
starts, ends = set(), set()
for start, end in paths:
starts.add(start)
if start in ends:
ends.remove(start)
if end not in starts:
ends.add(end)
return next(iter(ends)) | destination-city | Python one pass using two sets | dereky4 | 0 | 170 | destination city | 1,436 | 0.776 | Easy | 21,434 |
https://leetcode.com/problems/destination-city/discuss/1193623/Python-using-set-difference | class Solution:
def destCity(self, paths: List[List[str]]) -> str:
takeoffs = set()
landings = set()
for i in paths:
takeoffs.add(i[0])
landings.add(i[1])
retval = landings - takeoffs
return retval.pop() | destination-city | Python using set difference | fadista | 0 | 45 | destination city | 1,436 | 0.776 | Easy | 21,435 |
https://leetcode.com/problems/destination-city/discuss/1029139/Python-3-O(N) | class Solution:
def destCity(self, paths: List[List[str]]) -> str:
n=len(paths)
in_city = [paths[i][0] for i in range(n)]
out_city = [paths[i][1] for i in range(n)]
for i in range(n):
if out_city[i] not in in_city:
return out_city[i] | destination-city | Python 3, O(N) | DavidHB | 0 | 94 | destination city | 1,436 | 0.776 | Easy | 21,436 |
https://leetcode.com/problems/destination-city/discuss/940927/Using-recursion | class Solution:
def destCity(self, paths: List[List[str]]) -> str:
start = {}
for i in range(len(paths)):
start[paths[i][0]] = i
ans = [1]
def journey(a: int):
if paths[a][1] in start:
journey(start[paths[a][1]])
else:
ans[0] = paths[a][1]
journey(0)
return ans[0] | destination-city | Using recursion | yeha_audrey | 0 | 48 | destination city | 1,436 | 0.776 | Easy | 21,437 |
https://leetcode.com/problems/destination-city/discuss/907718/Python-1-set-2-traversals | class Solution:
def destCity(self, paths: List[List[str]]) -> str:
destinationSet = {cities[1] for cities in paths}
for starting in paths: destinationSet.discard(starting[0])
return destinationSet.pop() | destination-city | Python - 1 set, 2 traversals | JuanRodriguez | 0 | 127 | destination city | 1,436 | 0.776 | Easy | 21,438 |
https://leetcode.com/problems/destination-city/discuss/766400/Easy-python-Solution-with-dictionary-O(N) | class Solution:
def destCity(self, paths: List[List[str]]) -> str:
d=dict(paths)
x=paths[0][0]
while(True):
if d.get(x)!=None:
x=d[x]
else:
return x | destination-city | Easy python Solution with dictionary - O(N) | NvsYashwanth | 0 | 105 | destination city | 1,436 | 0.776 | Easy | 21,439 |
https://leetcode.com/problems/destination-city/discuss/708005/simple-of-simple-(just-set) | class Solution:
def destCity(self, paths: List[List[str]]) -> str:
f = set()
t = set()
for p in paths:
f.add(p[0])
t.add(p[1])
return list(t - f)[0] | destination-city | simple of simple (just set) | seunggabi | 0 | 79 | destination city | 1,436 | 0.776 | Easy | 21,440 |
https://leetcode.com/problems/destination-city/discuss/695399/Python-Easy-to-understand-solution-O(n) | class Solution:
def destCity(self, paths: List[List[str]]) -> str:
source = set([path[1] for path in paths])
destination = set([path[0] for path in paths])
destination_city = source.difference(destination)
return destination_city.pop() | destination-city | Python Easy to understand solution O(n) | abhijeetmallick29 | 0 | 138 | destination city | 1,436 | 0.776 | Easy | 21,441 |
https://leetcode.com/problems/check-if-all-1s-are-at-least-length-k-places-away/discuss/609823/Python-O(n)-Easy-(For-Loop-List-Comprehension) | class Solution:
def kLengthApart(self, nums: List[int], k: int) -> bool:
indices = [i for i, x in enumerate(nums) if x == 1]
if not indices:
return True
for i in range(1, len(indices)):
if indices[i] - indices[i-1] < k + 1:
return False
return True | check-if-all-1s-are-at-least-length-k-places-away | Python O(n) Easy (For Loop, List Comprehension) | sonaksh | 2 | 180 | check if all 1s are at least length k places away | 1,437 | 0.591 | Easy | 21,442 |
https://leetcode.com/problems/check-if-all-1s-are-at-least-length-k-places-away/discuss/1825026/2-Lines-Python-Solution-oror-75-Faster-oror-Memory-less-than-30 | class Solution:
def kLengthApart(self, nums: List[int], k: int) -> bool:
indices = [i for i,x in enumerate(nums) if x==1]
return all([indices[i+1]-indices[i]>k for i in range(len(indices)-1)]) | check-if-all-1s-are-at-least-length-k-places-away | 2-Lines Python Solution || 75% Faster || Memory less than 30% | Taha-C | 1 | 53 | check if all 1s are at least length k places away | 1,437 | 0.591 | Easy | 21,443 |
https://leetcode.com/problems/check-if-all-1s-are-at-least-length-k-places-away/discuss/633178/Python-O(n)-by-linear-scan.-90%2B-w-Comment | class Solution:
def kLengthApart(self, nums: List[int], k: int) -> bool:
if k == 0:
# Quick acception when k = 0
return True
# record previous index of 1
prev_position = None
for idx, number in enumerate(nums):
if number == 1:
if ( prev_position is not None ) and (idx - prev_position) <= k:
# Reject when distance to previous 1 is too close
return False
prev_position = idx
# Accept if all 1s are separated of distance k
return True | check-if-all-1s-are-at-least-length-k-places-away | Python O(n) by linear scan. 90%+ [w/ Comment] | brianchiang_tw | 1 | 126 | check if all 1s are at least length k places away | 1,437 | 0.591 | Easy | 21,444 |
https://leetcode.com/problems/check-if-all-1s-are-at-least-length-k-places-away/discuss/609784/Python3-two-lines-using-bit-and | class Solution:
def kLengthApart(self, nums: List[int], k: int) -> bool:
x = int("".join(map(str, nums)), 2)
return all((x & (x << i)) == 0 for i in range(1, k+1)) | check-if-all-1s-are-at-least-length-k-places-away | [Python3] two lines using bit & | ye15 | 1 | 42 | check if all 1s are at least length k places away | 1,437 | 0.591 | Easy | 21,445 |
https://leetcode.com/problems/check-if-all-1s-are-at-least-length-k-places-away/discuss/609784/Python3-two-lines-using-bit-and | class Solution:
def kLengthApart(self, nums: List[int], k: int) -> bool:
ii = -inf
for i, x in enumerate(nums):
if x:
if i - ii <= k: return False
ii = i
return True | check-if-all-1s-are-at-least-length-k-places-away | [Python3] two lines using bit & | ye15 | 1 | 42 | check if all 1s are at least length k places away | 1,437 | 0.591 | Easy | 21,446 |
https://leetcode.com/problems/check-if-all-1s-are-at-least-length-k-places-away/discuss/2661141/Python-Solution-(Beats-96.64-solutions) | class Solution:
def kLengthApart(self, nums: List[int], k: int) -> bool:
arr=[]
for i in range(len(nums)):
if nums[i]==1:
arr.append(i)
for j in range(len(arr)-1):
if arr[j+1]-arr[j]>=k+1:
flag=True
else:
return False
return True | check-if-all-1s-are-at-least-length-k-places-away | Python Solution (Beats 96.64% solutions) | KPrananjay | 0 | 10 | check if all 1s are at least length k places away | 1,437 | 0.591 | Easy | 21,447 |
https://leetcode.com/problems/check-if-all-1s-are-at-least-length-k-places-away/discuss/2554989/python3-ororOptimized-approach | class Solution:
def kLengthApart(self, nums: List[int], k: int) -> bool:
start = 0
end = 1
while start<len(nums) and start==0 :
start+=1
end = start+1
while end<len(nums):
if nums[end]:
if (end-start-1)<k:
return False
else:
start = end
end +=1
return True | check-if-all-1s-are-at-least-length-k-places-away | python3 ||Optimized approach | shacid | 0 | 8 | check if all 1s are at least length k places away | 1,437 | 0.591 | Easy | 21,448 |
https://leetcode.com/problems/check-if-all-1s-are-at-least-length-k-places-away/discuss/2315630/Easy-question-Python-one-pass-check-O(n) | class Solution:
def kLengthApart(self, nums: List[int], k: int) -> bool:
l=len(nums)
c=0
for i in range(l):
if nums[i]==1:
if c==0:
prev=i
c+=1
else:
dist = i-prev
prev=i
if dist <=k:
return False
return True | check-if-all-1s-are-at-least-length-k-places-away | Easy question - Python - one pass check O(n) | sunakshi132 | 0 | 26 | check if all 1s are at least length k places away | 1,437 | 0.591 | Easy | 21,449 |
https://leetcode.com/problems/check-if-all-1s-are-at-least-length-k-places-away/discuss/2297073/simple-iterative-solution | class Solution:
def kLengthApart(self, nums: List[int], k: int) -> bool:
# k represents the minimum distance 1's are allowed to be apart
# keep count of 1's and 0's seen
# if the count of 1's equals 2, check to make sure the count of 0's is greater
# than k
# if it is, reset 1's count to 1 (because we just saw a 1) and make 0's
# count 0
# time O(N) space O(1)
seen = count = 0
for i in range(len(nums)):
if nums[i]:
seen += 1
if seen == 2 and count < k:
return False
seen, count = 1, 0
else:
count += 1
return True | check-if-all-1s-are-at-least-length-k-places-away | simple iterative solution | andrewnerdimo | 0 | 20 | check if all 1s are at least length k places away | 1,437 | 0.591 | Easy | 21,450 |
https://leetcode.com/problems/check-if-all-1s-are-at-least-length-k-places-away/discuss/1751246/Python-dollarolution | class Solution:
def kLengthApart(self, nums: List[int], k: int) -> bool:
x = -k-1
for i in range(len(nums)):
if nums[i] == 1:
if i - x < k+1:
return False
x = i
return True | check-if-all-1s-are-at-least-length-k-places-away | Python $olution | AakRay | 0 | 45 | check if all 1s are at least length k places away | 1,437 | 0.591 | Easy | 21,451 |
https://leetcode.com/problems/check-if-all-1s-are-at-least-length-k-places-away/discuss/1745419/Easy-Python | class Solution:
def kLengthApart(self, nums: List[int], k: int) -> bool:
prev = -inf
for idx, val in enumerate(nums):
if val == 1:
if idx - prev <= k:
return False
else:
prev = idx
return True | check-if-all-1s-are-at-least-length-k-places-away | Easy Python | MengyingLin | 0 | 21 | check if all 1s are at least length k places away | 1,437 | 0.591 | Easy | 21,452 |
https://leetcode.com/problems/check-if-all-1s-are-at-least-length-k-places-away/discuss/1590710/Python-3-O(n)-easy | class Solution:
def kLengthApart(self, nums: List[int], k: int) -> bool:
prev = -k - 1
for i, num in enumerate(nums):
if num == 1:
if i - prev - 1 < k:
return False
prev = i
return True | check-if-all-1s-are-at-least-length-k-places-away | Python 3 O(n) easy | dereky4 | 0 | 53 | check if all 1s are at least length k places away | 1,437 | 0.591 | Easy | 21,453 |
https://leetcode.com/problems/check-if-all-1s-are-at-least-length-k-places-away/discuss/1516055/Python-O(n)-time-O(1)-space-solution | class Solution:
def kLengthApart(self, nums: List[int], k: int) -> bool:
prev = -1
n = len(nums)
for i in range(n):
if nums[i] == 0:
pass
else: # nums[i] == 1:
if prev < 0:
pass
else:
if i - prev -1 < k:
return False
prev = i
return True | check-if-all-1s-are-at-least-length-k-places-away | Python O(n) time, O(1) space solution | byuns9334 | 0 | 38 | check if all 1s are at least length k places away | 1,437 | 0.591 | Easy | 21,454 |
https://leetcode.com/problems/check-if-all-1s-are-at-least-length-k-places-away/discuss/1442219/One-pass-93-speed | class Solution:
def kLengthApart(self, nums: List[int], k: int) -> bool:
if not k:
return True
last_idx = -k - 1
for i, v in enumerate(nums):
if v:
if i - last_idx <= k:
return False
else:
last_idx = i
return True | check-if-all-1s-are-at-least-length-k-places-away | One pass, 93% speed | EvgenySH | 0 | 55 | check if all 1s are at least length k places away | 1,437 | 0.591 | Easy | 21,455 |
https://leetcode.com/problems/check-if-all-1s-are-at-least-length-k-places-away/discuss/1342003/Python-solution | class Solution:
def kLengthApart(self, nums: List[int], k: int) -> bool:
if k == 0:
return True
dist = len(nums)
for i in range(len(nums)):
if nums[i] == 1:
if dist>=k:
dist = 0
else:
return False
else:
dist+=1
return True | check-if-all-1s-are-at-least-length-k-places-away | Python solution | Wyhever | 0 | 28 | check if all 1s are at least length k places away | 1,437 | 0.591 | Easy | 21,456 |
https://leetcode.com/problems/check-if-all-1s-are-at-least-length-k-places-away/discuss/1183504/Python-fast | class Solution:
def kLengthApart(self, nums: List[int], k: int) -> bool:
try:
temp = nums.index(1)
except ValueError:
return True
for index, value in enumerate(nums[temp+1:], temp+1):
if value:
if index - temp > k:
temp = index
else:
return False
return True | check-if-all-1s-are-at-least-length-k-places-away | [Python] fast | cruim | 0 | 62 | check if all 1s are at least length k places away | 1,437 | 0.591 | Easy | 21,457 |
https://leetcode.com/problems/check-if-all-1s-are-at-least-length-k-places-away/discuss/1080970/Ptyhon3-simple-solution | class Solution:
def kLengthApart(self, nums: List[int], k: int) -> bool:
l = []
for i in range(len(nums)):
if nums[i] == 1:
l.append(i)
for i in range(len(l)-1):
if l[i+1] - l[i] <= k:
return False
return True | check-if-all-1s-are-at-least-length-k-places-away | Ptyhon3 simple solution | EklavyaJoshi | 0 | 47 | check if all 1s are at least length k places away | 1,437 | 0.591 | Easy | 21,458 |
https://leetcode.com/problems/check-if-all-1s-are-at-least-length-k-places-away/discuss/1035397/PythonPython3-or-Easy-to-Understand-or-Check-If-All-1's-Are-at-Least-Length-K-Places-Away | class Solution:
def kLengthApart(self, nums, k):
nums_occu = []
for idx, digits in enumerate(nums):
# getting the index and the value from the list
if digits == 1:
# checking whether there are 2 indexes or one because we need 2 to compare the distance between them
if len(nums_occu) == 0:
nums_occu.append(idx)
# if we already have 1 in the list then we can append the other and check the distance between the indices.
elif len(nums_occu) == 1:
nums_occu.append(idx)
# if they are less than k+1(k+1 because when finding distance we calculate the position of last 1 also, so to nullify that +1 is added)
if (nums_occu[1] - nums_occu[0]) < k+1:
return False
else:
# if we dont get the error then we are good to go and now we need the latest index of 1 for comparision so we discard the last index of first 1.
nums_occu = nums_occu[1:]
return True | check-if-all-1s-are-at-least-length-k-places-away | [Python/Python3] | Easy to Understand | Check If All 1's Are at Least Length K Places Away | newborncoder | 0 | 45 | check if all 1s are at least length k places away | 1,437 | 0.591 | Easy | 21,459 |
https://leetcode.com/problems/check-if-all-1s-are-at-least-length-k-places-away/discuss/976879/Python-O(N) | class Solution:
def kLengthApart(self, nums: List[int], k: int) -> bool:
last = -math.inf
for i, n in enumerate(nums):
if n:
if i - last < k + 1:
return False
last = i
return True | check-if-all-1s-are-at-least-length-k-places-away | Python O(N) | blue_sky5 | 0 | 45 | check if all 1s are at least length k places away | 1,437 | 0.591 | Easy | 21,460 |
https://leetcode.com/problems/check-if-all-1s-are-at-least-length-k-places-away/discuss/777032/Python3-simple-solution-95-faster | class Solution:
def kLengthApart(self, nums: List[int], k: int) -> bool:
if 1 not in nums:
count = len(nums)-1
if count>=k:
return True
return False
first = nums.index(1)
for i in range(first+1,len(nums)):
if nums[i]==1:
diff = i - first-1
j=i
first = j
if diff>=k:
continue
else:
return False
return True | check-if-all-1s-are-at-least-length-k-places-away | Python3 simple solution 95% faster | Geeky-star | 0 | 39 | check if all 1s are at least length k places away | 1,437 | 0.591 | Easy | 21,461 |
https://leetcode.com/problems/check-if-all-1s-are-at-least-length-k-places-away/discuss/644668/Intuitive-approach-by-translate-numbers-into-string-for-split-operation | class Solution:
def kLengthApart(self, nums: List[int], k: int) -> bool:
split_by_one = ''.join(map(lambda e: str(e), nums)).rstrip("0").lstrip("0").split('1')[1:-1]
''' substring (consecutive '0') between each '1' '''
dist_list = list(map(lambda e: len(e), split_by_one))
''' translate substring into length of them as distance'''
return all(map(lambda e: e >= k, dist_list))
''' Make sure each distance is greater or equal to the k setting''' | check-if-all-1s-are-at-least-length-k-places-away | Intuitive approach by translate numbers into string for split operation | puremonkey2001 | 0 | 24 | check if all 1s are at least length k places away | 1,437 | 0.591 | Easy | 21,462 |
https://leetcode.com/problems/check-if-all-1s-are-at-least-length-k-places-away/discuss/1034786/Python-Solution | class Solution:
def kLengthApart(self, nums, k: int) -> bool:
prev = -k - 1
for i in range(len(nums)):
if nums[i] == 1:
if i - prev - 1 < k:
return False
prev = i
return True | check-if-all-1s-are-at-least-length-k-places-away | Python Solution | mariandanaila01 | -1 | 39 | check if all 1s are at least length k places away | 1,437 | 0.591 | Easy | 21,463 |
https://leetcode.com/problems/longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/discuss/2798749/nlogn-solution-by-this-dude | class Solution:
def longestSubarray(self, nums: List[int], limit: int) -> int:
#[8,2,4,3,6,11] limit = 5
#if the new number is greater than max this becomes new max,
#if new number is less than min this becomes new min
#if max - min exceeds limit, pop the left most element -> if the left most element was max or min, recompute max - min and see if it goes limit
q = []
min_heap = []
max_heap = []
max_ans = 1
popped_index = set()
for i,v in enumerate(nums):
q.append((v,i))
# max_ans = max(max_ans,len(q))
heapq.heappush(min_heap,(v,i))
heapq.heappush(max_heap,(v*-1,i))
while(max_heap[0][0]*-1 - min_heap[0][0] > limit):
temp = q.pop(0)
popped_ele = temp[0]
popped_index.add(temp[1])
while(min_heap[0][1] in popped_index):
heapq.heappop(min_heap)
while(max_heap[0][1] in popped_index):
heapq.heappop(max_heap)
if len(q) > max_ans:
max_ans = len(q)
return max_ans | longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit | nlogn solution by this dude | ariboi27 | 0 | 6 | longest continuous subarray with absolute diff less than or equal to limit | 1,438 | 0.481 | Medium | 21,464 |
https://leetcode.com/problems/longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/discuss/2672332/Python-Two-Deque-Min-and-Max | class Solution:
def longestSubarray(self, nums: List[int], limit: int) -> int:
incq = deque()
decq = deque()
ans = 0
s = e = 0
while e < len(nums):
curr = nums[e]
while incq and incq[-1] < curr:
incq.pop()
incq.append(curr)
while decq and decq[-1] > curr:
decq.pop()
decq.append(curr)
while incq[0] - decq[0] > limit:
if incq[0] == nums[s]:
incq.popleft()
if decq[0] == nums[s]:
decq.popleft()
s += 1
ans = max(ans, e-s+1)
e += 1
return ans | longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit | Python - Two Deque - Min and Max | jainsiddharth99 | 0 | 21 | longest continuous subarray with absolute diff less than or equal to limit | 1,438 | 0.481 | Medium | 21,465 |
https://leetcode.com/problems/longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/discuss/1319692/TEMPLATE-DETAILED-dynamic-sliding-window-O(N)-and-binarysearch-O(NlogN)-and-BST-NlogN | class Solution:
# no need of binary search, described below....
def solve(self, nums, k):
def valid(n):
# slide a window length N
minq = deque() # stores (val, index)
maxq = deque() # descending
for r, v in enumerate(nums):
while maxq and maxq[-1][0] < v:
# i replace him as a maximum
# candidate in the current window
maxq.pop()
while minq and minq[-1][0] > v:
# i replace him as a minimum
# candidate in the current window
minq.pop()
# now adding self will maintain property
maxq.append((v, r))
minq.append((v, r))
# lazy pop max/min whom no longer in window
while maxq and maxq[0][1] <= (r - n):
maxq.popleft()
while minq and minq[0][1] <= (r - n):
minq.popleft()
# check if valid ;)
# print(' ',maxq,minq)
if r >= (n - 1) and maxq[0][0] - minq[0][0] <= k:
return True
return False
l, r = 1, len(nums) + 1
while l < r:
n = (l + r) // 2
print(l, r, n)
if valid(n):
l = n + 1
else:
r = n
return l - 1 | longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit | TEMPLATE DETAILED dynamic sliding window O(N) & binarysearch O(NlogN) & BST NlogN | yozaam | 0 | 126 | longest continuous subarray with absolute diff less than or equal to limit | 1,438 | 0.481 | Medium | 21,466 |
https://leetcode.com/problems/find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/discuss/1928887/Python3-or-O(m-*-knlogkn) | class Solution:
def kthSmallest(self, mat: List[List[int]], k: int) -> int:
row=len(mat)
col=len(mat[0])
temp=[i for i in mat[0]]
for i in range(1,row):
currSum=[]
for j in range(col):
for it in range(len(temp)):
currSum.append(temp[it]+mat[i][j])
currSum.sort()
temp.clear()
maxSize=min(k,len(currSum))
for size in range(maxSize):
temp.append(currSum[size])
return temp[k-1] | find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows | [Python3] | O(m * knlogkn) | swapnilsingh421 | 2 | 66 | find the kth smallest sum of a matrix with sorted rows | 1,439 | 0.614 | Hard | 21,467 |
https://leetcode.com/problems/build-an-array-with-stack-operations/discuss/1291707/Easy-Python-Solution(96.97) | class Solution:
def buildArray(self, target: List[int], n: int) -> List[str]:
stack=[]
for i in range(1,n+1):
if(i in target):
stack.append("Push")
else:
stack.append("Push")
stack.append("Pop")
if(i==(target[-1])):
break
return stack | build-an-array-with-stack-operations | Easy Python Solution(96.97%) | Sneh17029 | 6 | 407 | build an array with stack operations | 1,441 | 0.714 | Medium | 21,468 |
https://leetcode.com/problems/build-an-array-with-stack-operations/discuss/1941504/easy-python-code | class Solution:
def buildArray(self, target: List[int], n: int) -> List[str]:
output = []
new_target = []
l = [i for i in range(1,n+1)]
for i in l:
if new_target == target:
return output
output.append("Push")
new_target.append(i)
if i not in target:
output.append("Pop")
new_target.pop()
return output | build-an-array-with-stack-operations | easy python code | dakash682 | 2 | 106 | build an array with stack operations | 1,441 | 0.714 | Medium | 21,469 |
https://leetcode.com/problems/build-an-array-with-stack-operations/discuss/1040042/Python3-simple-solution | class Solution:
def buildArray(self, target: List[int], n: int) -> List[str]:
ans = []
arr = []
for i in range(1,n+1):
if i in target:
ans.append("Push")
arr.append(i)
else:
ans.append("Push")
ans.append("Pop")
if arr == target:
return ans
return ans | build-an-array-with-stack-operations | Python3 simple solution | EklavyaJoshi | 1 | 106 | build an array with stack operations | 1,441 | 0.714 | Medium | 21,470 |
https://leetcode.com/problems/build-an-array-with-stack-operations/discuss/624729/Python-O(t)-sol-by-simulation-w-Comment | class Solution:
def buildArray(self, target: List[int], n: int) -> List[str]:
target_idx, cur_read_num = 0, 1
stack_operation = []
while target_idx < len(target):
# Push current read number
stack_operation.append('Push')
if target[target_idx] == cur_read_num:
# Current read number is what we need, keep it and update target index
target_idx += 1
else:
# Pop out unnecessary element
stack_operation.append('Pop')
# current read number always +1 after each iteration
cur_read_num += 1
return stack_operation | build-an-array-with-stack-operations | Python O(t) sol by simulation [w/ Comment] | brianchiang_tw | 1 | 156 | build an array with stack operations | 1,441 | 0.714 | Medium | 21,471 |
https://leetcode.com/problems/build-an-array-with-stack-operations/discuss/2811662/PYTHON-SOLUTION-EXPLAINED-100 | class Solution:
def buildArray(self, target: List[int], n: int) -> List[str]:
l=[] #will store stream of integers
stack=[] #applying push and pop of elements
ans=[] #answer -> storing operations
x=0 #indexes for target
j=0 #indexes for l
for i in range(1,n+1): # list of stream of integers from 1 to n numbers
l.append(i)
while target!=stack and j<len(l): #stop operations when equal to target found or l come to an end
stack.append(l[j]) #everytime a number get pushed until reached till the end of l
ans.append("Push") #operation
if len(stack)!=0 and stack[-1]!=target[x]: #if the stack element which is pushed recently is
#not same as target in that position theN pop the element
stack.pop()
ans.append("Pop") #operation
elif stack[-1]==target[x]: #if correct element pushed into stack then time to check for
#the next element of target for its equality with stack's position ,so increment the index of target
x+=1
j+=1 #everytimr the next element will be chosen from the l till its end
return ans | build-an-array-with-stack-operations | PYTHON SOLUTION - EXPLAINED 100% ✔ | T1n1_B0x1 | 0 | 3 | build an array with stack operations | 1,441 | 0.714 | Medium | 21,472 |
https://leetcode.com/problems/build-an-array-with-stack-operations/discuss/2773032/Easy-Python-or-Iterate-over-target | class Solution:
def buildArray(self, target: List[int], n: int) -> List[str]:
i = 1
ans = []
for x in target:
while i < x:
ans.append("Push")
ans.append("Pop")
i += 1
ans.append("Push")
i += 1
return ans | build-an-array-with-stack-operations | Easy Python | Iterate over target | on_danse_encore_on_rit_encore | 0 | 3 | build an array with stack operations | 1,441 | 0.714 | Medium | 21,473 |
https://leetcode.com/problems/build-an-array-with-stack-operations/discuss/2764570/python-solution-Build-an-Array-With-Stack-Operations | class Solution:
def buildArray(self, target: List[int], n: int) -> List[str]:
stack = []
op = []
l = len(target)
j = 0
for i in range(1,n+1):
stack.append(i)
op.append("Push")
if stack[-1] == target[j]:
j += 1
if j == l:
break
else:
stack.pop()
op.append("Pop")
return op | build-an-array-with-stack-operations | python solution Build an Array With Stack Operations | sarthakchawande14 | 0 | 4 | build an array with stack operations | 1,441 | 0.714 | Medium | 21,474 |
https://leetcode.com/problems/build-an-array-with-stack-operations/discuss/2647247/Simple-Python-Solution-or-Stack | class Solution:
def buildArray(self, target: List[int], n: int) -> List[str]:
stack=[]
ans=[]
i=1
j=0
while stack!=target:
stack.append(i)
ans.append('Push')
if stack[-1]!=target[j]:
stack.pop()
ans.append('Pop')
j-=1
i+=1
j+=1
return ans | build-an-array-with-stack-operations | Simple Python Solution | Stack | Siddharth_singh | 0 | 3 | build an array with stack operations | 1,441 | 0.714 | Medium | 21,475 |
https://leetcode.com/problems/build-an-array-with-stack-operations/discuss/2644317/Python3-two-pointer-solution | class Solution:
def buildArray(self, target: List[int], n: int) -> List[str]:
res = []
current = 0
#below the loop starts and go through each element in the target array.
for i in range(len(target)):
#define the distance between current pointer to the upcoming number in the target array
diff = target[i]-current
#execute the operation based on the 'distance'
res.extend(['Push','Pop']*(diff-1))
res.append('Push')
#update current pointer, this is the key of the two pointer method
current = target[i]
return res | build-an-array-with-stack-operations | Python3 two pointer solution | yueqiu | 0 | 3 | build an array with stack operations | 1,441 | 0.714 | Medium | 21,476 |
https://leetcode.com/problems/build-an-array-with-stack-operations/discuss/2614606/Python-Concise-O(len(targets))-Solution | class Solution:
def buildArray(self, target: List[int], n: int) -> List[str]:
# go through the targets
start = 0
extension = ["Push", "Pop"]
result = []
for tar in target:
# check what the difference is
diff = tar - start -1
# if diff is more than one, we need several push pop pairs
result.extend(extension*diff)
result.append('Push')
# set the new target
start = tar
return result | build-an-array-with-stack-operations | [Python] - Concise O(len(targets)) Solution | Lucew | 0 | 9 | build an array with stack operations | 1,441 | 0.714 | Medium | 21,477 |
https://leetcode.com/problems/build-an-array-with-stack-operations/discuss/2473866/Simple-Python3-solution | class Solution:
def buildArray(self, target: List[int], n: int) -> List[str]:
stack=[i for i in range(1,n+1)]
res=[]
count=0
i=0
j=0
while count!=len(target) and i<len(stack):
if stack[i]==target[j]:
res.append('Push')
count+=1
j+=1
else:
res.append('Push')
res.append('Pop')
i+=1
return res | build-an-array-with-stack-operations | Simple Python3 solution | anirudh422 | 0 | 19 | build an array with stack operations | 1,441 | 0.714 | Medium | 21,478 |
https://leetcode.com/problems/build-an-array-with-stack-operations/discuss/2391514/simple-and-easy-PYTHON-solution | class Solution:
def buildArray(self, target: List[int], n: int) -> List[str]:
temp = []
result = []
x = target[-1]
for i in range(1,x+1):
temp.append(i)
for i in range(len(temp)):
if temp[i] in target:
result.append("Push")
elif temp[i] not in target:
result.append("Push")
result.append("Pop")
return result | build-an-array-with-stack-operations | simple and easy PYTHON solution | BANALA_DEEPTHI | 0 | 38 | build an array with stack operations | 1,441 | 0.714 | Medium | 21,479 |
https://leetcode.com/problems/build-an-array-with-stack-operations/discuss/2384581/pythonororeasy-solutionororstack-or-listororcheck-it-out! | class Solution:
def buildArray(self, target: List[int], n: int) -> List[str]:
stack=[]
for i in range(1,n+1):
stack.append("Push")
if i not in target:
stack.append("Pop")
if i==target[-1]:
break
return stack | build-an-array-with-stack-operations | python||easy-solution||stack or list||check it out! | shikhar_srivastava391 | 0 | 31 | build an array with stack operations | 1,441 | 0.714 | Medium | 21,480 |
https://leetcode.com/problems/build-an-array-with-stack-operations/discuss/2310423/Easy-Python | class Solution:
def buildArray(self, target: List[int], n: int) -> List[str]:
i=0
j=1
t=len(target)
ans=[]
while (i < t) :
ans.append("Push")
if target[i] == j:
i+=1
j+=1
else:
ans.append("Pop")
j+=1
return ans | build-an-array-with-stack-operations | Easy Python | sunakshi132 | 0 | 31 | build an array with stack operations | 1,441 | 0.714 | Medium | 21,481 |
https://leetcode.com/problems/build-an-array-with-stack-operations/discuss/2223267/Python-%3A-easy-stack-concept | class Solution(object):
def buildArray(self, target, n):
"""
:type target: List[int]
:type n: int
:rtype: List[str]
"""
stack = []
out = []
j = 0
for i in range(n):
if(stack == target):break #Boundary condition
out.append("Push")
stack.append(i+1) # Follow the push
if(target[j] == i+1): j += 1
else:
stack.pop()
out.append("Pop") # Follow the pop
return out | build-an-array-with-stack-operations | Python : easy stack concept | ytinghau820 | 0 | 59 | build an array with stack operations | 1,441 | 0.714 | Medium | 21,482 |
https://leetcode.com/problems/build-an-array-with-stack-operations/discuss/2130960/python-O(n) | class Solution:
def buildArray(self, target: List[int], n: int) -> List[str]:
t = set(target)
res = []
for i in range(1, target[-1] + 1):
res.append("Push")
if i not in t:
res.append("Pop")
return res | build-an-array-with-stack-operations | python O(n) | andrewnerdimo | 0 | 33 | build an array with stack operations | 1,441 | 0.714 | Medium | 21,483 |
https://leetcode.com/problems/build-an-array-with-stack-operations/discuss/2085131/python3-or-Runtime%3A-96.30-or-Memory-Usage%3A-69.77 | class Solution:
def buildArray(self, target: List[int], n: int) -> List[str]:
stack = []
res = []
i = 1
while stack != target:
if i not in target:
res.append('Push')
res.append('Pop')
else:
res.append('Push')
stack.append(i)
i += 1
return res | build-an-array-with-stack-operations | python3 | Runtime: 96.30% | Memory Usage: 69.77% | An_222 | 0 | 36 | build an array with stack operations | 1,441 | 0.714 | Medium | 21,484 |
https://leetcode.com/problems/build-an-array-with-stack-operations/discuss/1937277/Python3-Solution | class Solution:
def buildArray(self, target: List[int], n: int) -> List[str]:
stack = []
ans = []
thelist = list(range(1, n+1))
for i in range(n):
if len(stack) != len(target): # Prevent the situations like Testcase: target=[1,2] n=3
stack.append(thelist[i])
ans += ['Push']
if stack[-1] not in target:
stack.pop()
ans += ['Pop']
return ans | build-an-array-with-stack-operations | Python3 Solution | Mr_Watermelon | 0 | 15 | build an array with stack operations | 1,441 | 0.714 | Medium | 21,485 |
https://leetcode.com/problems/build-an-array-with-stack-operations/discuss/1921929/Python-easy-solution-for-beginners | class Solution:
def buildArray(self, target: List[int], n: int) -> List[str]:
res = []
for i in range(1, max(target)+1):
if i in target:
res.append("Push")
else:
res.append("Push")
res.append("Pop")
return res | build-an-array-with-stack-operations | Python easy solution for beginners | alishak1999 | 0 | 40 | build an array with stack operations | 1,441 | 0.714 | Medium | 21,486 |
https://leetcode.com/problems/build-an-array-with-stack-operations/discuss/1831384/5-Lines-Python-Solution-oror-Memory-less-than-100-oror-10-Faster | class Solution:
def buildArray(self, T: List[int], n: int) -> List[str]:
ans=[]
for i in range(1,T[-1]+1):
if i in T: ans.append('Push')
else: ans.extend(['Push','Pop'])
return ans | build-an-array-with-stack-operations | 5-Lines Python Solution || Memory less than 100% || 10% Faster | Taha-C | 0 | 53 | build an array with stack operations | 1,441 | 0.714 | Medium | 21,487 |
https://leetcode.com/problems/build-an-array-with-stack-operations/discuss/1751286/Python-dollarolution-(faster-than-96-better-mem-use-than-96) | class Solution:
def buildArray(self, target: List[int], n: int) -> List[str]:
v, i, j = [], 1, 0
while i < target[-1]+1:
v.append("Push")
if target[j] == i:
j += 1
else:
v.append("Pop")
i += 1
return v | build-an-array-with-stack-operations | Python $olution (faster than 96%, better mem use than 96%) | AakRay | 0 | 88 | build an array with stack operations | 1,441 | 0.714 | Medium | 21,488 |
https://leetcode.com/problems/build-an-array-with-stack-operations/discuss/1590702/Python-3-faster-than-92 | class Solution:
def buildArray(self, target: List[int], n: int) -> List[str]:
res = []
prev = 0
for num in target:
res.extend(['Push', 'Pop'] * (num - prev - 1))
res.append('Push')
prev = num
return res | build-an-array-with-stack-operations | Python 3 faster than 92% | dereky4 | 0 | 104 | build an array with stack operations | 1,441 | 0.714 | Medium | 21,489 |
https://leetcode.com/problems/build-an-array-with-stack-operations/discuss/1457861/Build-an-Array-With-Stack-Operations-or-Runtime%3A-20ms-(faster-than-99.60-Python3-Submissions) | class Solution:
def buildArray(self, target: List[int], n: int) -> List[str]:
answer = []
i = 1
while i <= target[-1]:
if i in target:
answer.append("Push")
i += 1
else:
answer.append("Push")
answer.append("Pop")
i += 1
return answer | build-an-array-with-stack-operations | Build an Array With Stack Operations | Runtime: 20ms (faster than 99.60% Python3 Submissions) | thisisashwinraj | 0 | 72 | build an array with stack operations | 1,441 | 0.714 | Medium | 21,490 |
https://leetcode.com/problems/build-an-array-with-stack-operations/discuss/1442236/One-pass-96-speed | class Solution:
def buildArray(self, target: List[int], n: int) -> List[str]:
missing = set(range(1, n + 1)) - set(target)
ans = []
for n in range(1, min(target[-1], n) + 1):
ans.append("Push")
if n in missing:
ans.append("Pop")
return ans | build-an-array-with-stack-operations | One pass, 96% speed | EvgenySH | 0 | 91 | build an array with stack operations | 1,441 | 0.714 | Medium | 21,491 |
https://leetcode.com/problems/build-an-array-with-stack-operations/discuss/1399683/Python3-Solution | class Solution:
def buildArray(self, target: List[int], n: int) -> List[str]:
words_arr = []
nums_arr = []
for i in range(1, n + 1):
if nums_arr == target:
return words_arr
if i in target:
nums_arr.append(i)
words_arr.append("Push")
else:
words_arr.append("Push")
words_arr.append("Pop")
return words_arr | build-an-array-with-stack-operations | Python3 Solution | RobertObrochta | 0 | 34 | build an array with stack operations | 1,441 | 0.714 | Medium | 21,492 |
https://leetcode.com/problems/build-an-array-with-stack-operations/discuss/1385675/Runtime%3A-28-ms-faster-than-89.90-of-Python3-online-submissions | class Solution:
def buildArray(self, target: List[int], n: int) -> List[str]:
j=0
l=[]
for i in range(1,n+1):
# if j==(len(target)):
# break
if target[j]==i:
l.append("Push")
j+=1
else:
l.append("Push")
l.append("Pop")
if i==target[-1]:
break
return l | build-an-array-with-stack-operations | Runtime: 28 ms, faster than 89.90% of Python3 online submissions | harshmalviya7 | 0 | 48 | build an array with stack operations | 1,441 | 0.714 | Medium | 21,493 |
https://leetcode.com/problems/build-an-array-with-stack-operations/discuss/1361658/Zero-kills-bhai-mai-nhi-khelra | class Solution:
def buildArray(self, target, n):
ans = [] # push and pop
stack = [] # ans array
for i in range(1, n+1):
if i in target:
ans.append("Push")
stack.append(i)
elif i not in target:
ans.append("Push")
ans.append("Pop")
if target == stack:
break
return ans
sol = Solution()
print(sol.buildArray([1, 3, 4, 6, 7, 8], 9))
# ["Push","Push","Pop","Push","Push","Push","Pop","Push","Push","Push"] | build-an-array-with-stack-operations | Zero kills bhai mai nhi khelra | RishikeshChouksey | 0 | 33 | build an array with stack operations | 1,441 | 0.714 | Medium | 21,494 |
https://leetcode.com/problems/build-an-array-with-stack-operations/discuss/1237757/Easy-Python3 | class Solution:
def buildArray(self, target: List[int], n: int) -> List[str]:
res = []
count = 1
for i in range(n):
if i>=max(target):
break
elif count in target:
res.append('Push')
elif count not in target:
res.append('Push')
res.append('Pop')
count+=1
return res | build-an-array-with-stack-operations | Easy Python3 | Sanyamx1x | 0 | 55 | build an array with stack operations | 1,441 | 0.714 | Medium | 21,495 |
https://leetcode.com/problems/build-an-array-with-stack-operations/discuss/939087/2-solution-including-O(n) | class Solution:
def buildArray(self, target: List[int], n: int) -> List[str]:
# naive solution
mylist = []
for num in range(1,max(target)+1):
mylist.append("Push")
#make O(n^2)
if num not in target:
mylist.append("Pop")
return mylist
# O(n) solution
mylist = []
currentNumber = 1
for num in target:
while currentNumber < num:
mylist.extend(["Push", "Pop"])
currentNumber += 1
mylist.append("Push")
currentNumber = num+1
return mylist | build-an-array-with-stack-operations | 2 solution including O(n) | serdarkuyuk | 0 | 59 | build an array with stack operations | 1,441 | 0.714 | Medium | 21,496 |
https://leetcode.com/problems/build-an-array-with-stack-operations/discuss/766088/Easy-python-solution-Linear-time-(-Fast-) | class Solution:
def buildArray(self, target: List[int], n: int) -> List[str]:
# We have another array called ans which basically runs from 1 to n (given integer)
# Using list comprehension
ans=[i for i in range(1,n+1)]
z=[]
i=0 # Points to target array
j=0 # Points to ans array
# We iterate over the target array during which we compare the target array with the ans array
while(i!=len(target)):
# If not equal find the difference and append the operations as per the difference number.
if target[i]!=ans[j]:
diff=target[i]-ans[j]
# Moving j to point to the same element as i
j+=diff
z.extend(['Push','Pop']*diff)
# Since both i,j point to same element, just do push operation now.
z.append("Push")
i+=1
j+=1
return z | build-an-array-with-stack-operations | Easy python solution - Linear time ( Fast ) | NvsYashwanth | 0 | 64 | build an array with stack operations | 1,441 | 0.714 | Medium | 21,497 |
https://leetcode.com/problems/build-an-array-with-stack-operations/discuss/652649/Intuitive-approach-by-skip-and-get-functions-according-to-target | class Solution:
def buildArray(self, target: List[int], n: int) -> List[str]:
actions = []
def skip():
actions.extend(["Push", "Pop"])
def get():
target.pop(0)
actions.append("Push")
for i in range(1, n+1):
if i == target[0]:
get()
else:
skip()
if not target:
break
return actions | build-an-array-with-stack-operations | Intuitive approach by skip and get functions according to target | puremonkey2001 | 0 | 15 | build an array with stack operations | 1,441 | 0.714 | Medium | 21,498 |
https://leetcode.com/problems/build-an-array-with-stack-operations/discuss/628302/Python3-Concise-Clean-O(N) | class Solution:
def buildArray(self, target: List[int], n: int) -> List[str]:
currEl = 0
res = []
for num in target:
res.extend(["Push", "Pop"] * (num - currEl - 1) + ["Push"])
currEl = num
return res | build-an-array-with-stack-operations | [Python3] Concise, Clean O(N) | ilkercankaya | 0 | 36 | build an array with stack operations | 1,441 | 0.714 | Medium | 21,499 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.