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/defanging-an-ip-address/discuss/2481046/Python-one-line-answer | class Solution:
def defangIPaddr(self, address: str) -> str:
return ("[.]".join(address.split("."))) | defanging-an-ip-address | Python one line answer | rohansardar | 0 | 22 | defanging an ip address | 1,108 | 0.893 | Easy | 17,500 |
https://leetcode.com/problems/defanging-an-ip-address/discuss/2424915/Python-solution-or-easy-to-understand | class Solution:
def defangIPaddr(self, address: str) -> str:
# return address.replace(".","[.]") # first approach
new_str = "" # Second approach
for i in range(len(address)):
if address[i]==".":
new_str+="[.]"
else:
new_str+=address[i]
return new_str | defanging-an-ip-address | Python solution | easy to understand | shivanshv3508 | 0 | 5 | defanging an ip address | 1,108 | 0.893 | Easy | 17,501 |
https://leetcode.com/problems/defanging-an-ip-address/discuss/2330639/Defanging-An-IP-Address-Solution-(One-line-code) | class Solution:
def defangIPaddr(self, address: str) -> str:
return address.replace('.','[.]') | defanging-an-ip-address | Defanging An IP Address Solution (One-line code) | a1289sahu | 0 | 14 | defanging an ip address | 1,108 | 0.893 | Easy | 17,502 |
https://leetcode.com/problems/defanging-an-ip-address/discuss/2319014/1-line-python-solution-or-Defanging-an-IP-Address | class Solution:
def defangIPaddr(self, address: str) -> str:
return address.replace(".", "[.]") | defanging-an-ip-address | 1 line python solution | Defanging an IP Address | nishanrahman1994 | 0 | 44 | defanging an ip address | 1,108 | 0.893 | Easy | 17,503 |
https://leetcode.com/problems/defanging-an-ip-address/discuss/2260225/Python-One-Line | class Solution:
def defangIPaddr(self, address: str) -> str:
return address.replace(".", "[.]") | defanging-an-ip-address | ✅Python - One Line | Skiper228 | 0 | 38 | defanging an ip address | 1,108 | 0.893 | Easy | 17,504 |
https://leetcode.com/problems/defanging-an-ip-address/discuss/2160512/Simple-single-line-code-or-Python-Python3-Java-JavaScript-C-TypeScript-and-PHP | class Solution(object):
def defangIPaddr(self, address):
return address.replace(".", "[.]") | defanging-an-ip-address | Simple single-line code | Python, Python3, Java, JavaScript, C#, TypeScript and PHP | AmolCode | 0 | 53 | defanging an ip address | 1,108 | 0.893 | Easy | 17,505 |
https://leetcode.com/problems/defanging-an-ip-address/discuss/2160512/Simple-single-line-code-or-Python-Python3-Java-JavaScript-C-TypeScript-and-PHP | class Solution:
def defangIPaddr(self, address: str) -> str:
return address.replace(".", "[.]") | defanging-an-ip-address | Simple single-line code | Python, Python3, Java, JavaScript, C#, TypeScript and PHP | AmolCode | 0 | 53 | defanging an ip address | 1,108 | 0.893 | Easy | 17,506 |
https://leetcode.com/problems/defanging-an-ip-address/discuss/2102799/SHORT-or-SIMPLE-or-EASY-or-with-runtiome-69ms | class Solution:
def defangIPaddr(self, address: str) -> str:
s=""
for i in address:
if i==".":
s=s+"[.]"
else:
s=s+i
return s | defanging-an-ip-address | SHORT | SIMPLE | EASY | with runtiome 69ms | T1n1_B0x1 | 0 | 19 | defanging an ip address | 1,108 | 0.893 | Easy | 17,507 |
https://leetcode.com/problems/defanging-an-ip-address/discuss/2013051/Python3-using-method-replace | class Solution:
def defangIPaddr(self, address: str) -> str:
return address.replace(".", "[.]") | defanging-an-ip-address | [Python3] using method replace | Shiyinq | 0 | 35 | defanging an ip address | 1,108 | 0.893 | Easy | 17,508 |
https://leetcode.com/problems/defanging-an-ip-address/discuss/1981049/Simple-solution | class Solution:
def defangIPaddr(self, address: str) -> str:
address = address.replace(".", "[.]")
return address | defanging-an-ip-address | Simple solution | andrewnerdimo | 0 | 55 | defanging an ip address | 1,108 | 0.893 | Easy | 17,509 |
https://leetcode.com/problems/defanging-an-ip-address/discuss/1863125/Python-solution-faster-than-98 | class Solution:
def defangIPaddr(self, address: str) -> str:
res = ""
for i in address:
if i.isnumeric():
res += i
if i == ".":
res += "[.]"
return res | defanging-an-ip-address | Python solution faster than 98% | alishak1999 | 0 | 62 | defanging an ip address | 1,108 | 0.893 | Easy | 17,510 |
https://leetcode.com/problems/defanging-an-ip-address/discuss/1861066/Python | class Solution:
def defangIPaddr(self, address: str) -> str:
arr = []
for letter in address:
if letter == ".":
arr.append("[.]")
else:
arr.append(letter)
return "".join(arr) | defanging-an-ip-address | Python | hardik097 | 0 | 16 | defanging an ip address | 1,108 | 0.893 | Easy | 17,511 |
https://leetcode.com/problems/defanging-an-ip-address/discuss/1711134/1108-defang-IP-address-python-obvious-solution | class Solution(object):
def defangIPaddr(self, address):
return address.replace(".","[.]") | defanging-an-ip-address | 1108 - defang IP address python obvious solution | ankit61d | 0 | 46 | defanging an ip address | 1,108 | 0.893 | Easy | 17,512 |
https://leetcode.com/problems/defanging-an-ip-address/discuss/1419788/Python-3-One-line | class Solution:
def defangIPaddr(self, address: str) -> str:
return address.replace(".", "[.]") | defanging-an-ip-address | Python 3 One line | amestri890 | 0 | 85 | defanging an ip address | 1,108 | 0.893 | Easy | 17,513 |
https://leetcode.com/problems/defanging-an-ip-address/discuss/1397099/Python3-(One-Liner-Solution) | class Solution:
def defangIPaddr(self, address: str) -> str:
return address.replace('.', '[.]') | defanging-an-ip-address | Python3 (One-Liner Solution) | terrencetang | 0 | 80 | defanging an ip address | 1,108 | 0.893 | Easy | 17,514 |
https://leetcode.com/problems/defanging-an-ip-address/discuss/1376471/C%2B%2BPythonJava-Runtime%3A-0-ms-faster-than-100.00 | class Solution:
def defangIPaddr(self, address: str) -> str:
res = address.replace(".","[.]")
return res | defanging-an-ip-address | [C++/Python/Java] Runtime: 0 ms, faster than 100.00% | tranhoangcore | 0 | 151 | defanging an ip address | 1,108 | 0.893 | Easy | 17,515 |
https://leetcode.com/problems/defanging-an-ip-address/discuss/1352311/Python-solution-straight-forward | class Solution:
def defangIPaddr(self, address: str) -> str:
output = ''
for i in address:
if i != '.':
output += i
else:
output += '[.]'
return output | defanging-an-ip-address | Python solution straight forward | tianshuhuang6 | 0 | 51 | defanging an ip address | 1,108 | 0.893 | Easy | 17,516 |
https://leetcode.com/problems/defanging-an-ip-address/discuss/1017160/Easy-solution | class Solution:
def defangIPaddr(self, address: str) -> str:
return address.replace(".","[.]") | defanging-an-ip-address | Easy solution | ziqizhangt | 0 | 62 | defanging an ip address | 1,108 | 0.893 | Easy | 17,517 |
https://leetcode.com/problems/defanging-an-ip-address/discuss/894462/Python-Easy-and-Effective-Solution | class Solution:
def defangIPaddr(self, address: str) -> str:
outputString:str = ""
for i in address:
if i == '.': outputString += '[.]'
else: outputString += i
return outputString | defanging-an-ip-address | [Python] Easy and Effective Solution | rizwanmustafa0000 | 0 | 72 | defanging an ip address | 1,108 | 0.893 | Easy | 17,518 |
https://leetcode.com/problems/defanging-an-ip-address/discuss/742022/python-3-in-place-defang | class Solution(object):
def defangIPaddr(self, address):
"""
:type address: str
:rtype: str
"""
address = list(address)
address += [' ' for _ in range(6)]
endptr = len(address) - 1
fptr = endptr-6
while(fptr>0):
if address[fptr]=='.':
address[endptr] = ']'
address[endptr - 1] = '.'
address[endptr - 2] = '['
endptr -= 3
else:
address[endptr] = address[fptr]
endptr -= 1
fptr -= 1
return "".join(address) | defanging-an-ip-address | python 3 in place defang | yazido | 0 | 132 | defanging an ip address | 1,108 | 0.893 | Easy | 17,519 |
https://leetcode.com/problems/defanging-an-ip-address/discuss/739197/Python3-One-Line-Solution-%3A-Faster-Than-89-Better-Memory-Usage-Than-82 | class Solution:
def defangIPaddr(self, address: str) -> str:
return address.replace('.','[.]') | defanging-an-ip-address | [Python3] One Line Solution : Faster Than 89% Better Memory Usage Than 82% | mihirverma | 0 | 134 | defanging an ip address | 1,108 | 0.893 | Easy | 17,520 |
https://leetcode.com/problems/defanging-an-ip-address/discuss/533521/Python3-99.5-using-split-and-join-with-inline-commentary | class Solution:
def defangIPaddr(self, address: str) -> str:
if len(address) == 0:
return ''
# Split string on '.'
values = address.split('.')
# Rejoin on '[.]'
result = ('[.]').join(values)
return(result) | defanging-an-ip-address | Python3 - 99.5 using split and join with inline commentary | dentedghost | 0 | 98 | defanging an ip address | 1,108 | 0.893 | Easy | 17,521 |
https://leetcode.com/problems/defanging-an-ip-address/discuss/331400/Python-Three-one-line-solutions | class Solution:
def defangIPaddr(self, address: str) -> str:
return address.replace('.','[.]') | defanging-an-ip-address | [Python] Three one line solutions | dxftctcdtc | 0 | 68 | defanging an ip address | 1,108 | 0.893 | Easy | 17,522 |
https://leetcode.com/problems/defanging-an-ip-address/discuss/331400/Python-Three-one-line-solutions | class Solution:
def defangIPaddr(self, address: str) -> str:
return '[.]'.join(address.split('.')) | defanging-an-ip-address | [Python] Three one line solutions | dxftctcdtc | 0 | 68 | defanging an ip address | 1,108 | 0.893 | Easy | 17,523 |
https://leetcode.com/problems/defanging-an-ip-address/discuss/331400/Python-Three-one-line-solutions | class Solution:
def defangIPaddr(self, address: str) -> str:
return re.sub('\.', '[.]', address) | defanging-an-ip-address | [Python] Three one line solutions | dxftctcdtc | 0 | 68 | defanging an ip address | 1,108 | 0.893 | Easy | 17,524 |
https://leetcode.com/problems/defanging-an-ip-address/discuss/1034820/Python-solution%3A-Memory-usage-99.91-less-and-execution-time-98-less | class Solution:
def defangIPaddr(self, address: str) -> str:
return ("[.]".join(address.split("."))) | defanging-an-ip-address | Python solution: Memory usage 99.91% less and execution time 98% less | chiopra | -1 | 104 | defanging an ip address | 1,108 | 0.893 | Easy | 17,525 |
https://leetcode.com/problems/corporate-flight-bookings/discuss/2309125/Easy-Python-O(n)-using-accumulate | class Solution:
def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:
res = [0]*n
for first, last, seat in bookings:
res[first - 1] += seat
if last < n:
res[last] -= seat
return accumulate(res) | corporate-flight-bookings | Easy Python O(n) using accumulate | rinaba501 | 3 | 140 | corporate flight bookings | 1,109 | 0.604 | Medium | 17,526 |
https://leetcode.com/problems/corporate-flight-bookings/discuss/1076571/Python-Easy-to-understand-Explained-~-beats-75 | class Solution:
def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:
arr = [[0, 0] for i in range(n)]
ans = []
for i, j, k in bookings:
arr[i-1][0] += k
arr[j-1][1] += k
curr = 0
for i in range(len(arr)):
ans.append(curr + arr[i][0])
curr += arr[i][0] - arr[i][1]
return ans | corporate-flight-bookings | [Python] Easy to understand, Explained ~ beats 75% | vs152 | 3 | 386 | corporate flight bookings | 1,109 | 0.604 | Medium | 17,527 |
https://leetcode.com/problems/corporate-flight-bookings/discuss/1609678/Python-or-O(n)-or-Simple-Solution | class Solution:
def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:
result = [0]*n
for start, end, value in bookings:
result[start-1] += value
if end < n:
result[end] -= value
for index, value in enumerate(result):
if index != 0:
result[index] += result[index-1]
return result | corporate-flight-bookings | Python | O(n) | Simple Solution | Call-Me-AJ | 2 | 102 | corporate flight bookings | 1,109 | 0.604 | Medium | 17,528 |
https://leetcode.com/problems/corporate-flight-bookings/discuss/2174574/PYTHON-SOL-or-O(-M-%2B-N-)-or-EXPLAINED-WELL-or-FAST-or-ARRAYS-or | class Solution:
def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:
ans = [0]*n
m = len(bookings)
for start,end,seats in bookings:
ans[start-1]+=seats
if end < n : ans[end] -= seats
for i in range(1,n):
ans[i] += ans[i-1]
return ans | corporate-flight-bookings | PYTHON SOL | O( M + N ) | EXPLAINED WELL | FAST | ARRAYS | | reaper_27 | 1 | 60 | corporate flight bookings | 1,109 | 0.604 | Medium | 17,529 |
https://leetcode.com/problems/corporate-flight-bookings/discuss/1809331/WEEB-DOES-PYTHONC%2B%2B-DPPREFIX-SUM | class Solution:
def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:
result = [0] * n
for start, end, val in bookings:
result[start-1] += val
if end < n:
result[end] -= val
for idx, val in enumerate(result):
if idx != 0:
result[idx] += result[idx-1]
return result | corporate-flight-bookings | WEEB DOES PYTHON/C++ DP/PREFIX SUM | Skywalker5423 | 1 | 60 | corporate flight bookings | 1,109 | 0.604 | Medium | 17,530 |
https://leetcode.com/problems/corporate-flight-bookings/discuss/2832935/100-python | class Solution:
def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:
A=[0 for i in range(n+2)]
for i in bookings:
A[i[0]]+=i[2]
A[i[1]+1]-=i[2]
for i in range(1,n+1):
A[i]+=A[i-1]
return A[1:n+1] | corporate-flight-bookings | 100% python | RjRahul003 | 0 | 1 | corporate flight bookings | 1,109 | 0.604 | Medium | 17,531 |
https://leetcode.com/problems/corporate-flight-bookings/discuss/2803667/Python-3-or-O(n)-Solution-using-HashMap | class Solution:
def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:
ans = [0]*n
changeDict = defaultdict(int)
for first,last,seat in bookings:
changeDict[first-1]+=seat
changeDict[last]-=seat
nowSeat = 0
for i in range(n):
nowSeat+=changeDict[i]
ans[i] = nowSeat
return ans | corporate-flight-bookings | Python 3 | O(n) Solution using HashMap | ty2134029 | 0 | 2 | corporate flight bookings | 1,109 | 0.604 | Medium | 17,532 |
https://leetcode.com/problems/corporate-flight-bookings/discuss/2711117/Python3-or-5-Lines-or-Faster-than-99 | class Solution:
def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:
seats = [0] * (n + 1)
for f, l, s in bookings:
seats[f-1] += s
seats[l] -= s
return list(accumulate(seats[:-1])) | corporate-flight-bookings | Python3 | 5 Lines | Faster than 99% | ryangrayson | 0 | 9 | corporate flight bookings | 1,109 | 0.604 | Medium | 17,533 |
https://leetcode.com/problems/corporate-flight-bookings/discuss/2660759/Python3-Solution-oror-O(N)-Time-and-Space-Complexity | class Solution:
def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:
array=[0]*n
for itr in bookings:
array[itr[0]-1]+=itr[2]
if itr[1]!=n:
array[itr[1]]-=itr[2]
prefixSum=0
for i in range(n):
prefixSum+=array[i]
array[i]=prefixSum
return array | corporate-flight-bookings | Python3 Solution || O(N) Time & Space Complexity | akshatkhanna37 | 0 | 11 | corporate flight bookings | 1,109 | 0.604 | Medium | 17,534 |
https://leetcode.com/problems/corporate-flight-bookings/discuss/2618806/Difference | class Solution:
def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:
result = []
diff = [0] * (n+1)
for book in bookings:
diff[book[0]-1] += book[2]
diff[book[1]] -= book[2]
accum = 0
for i in range(n):
accum +=diff[i]
result.append(accum)
return result | corporate-flight-bookings | Difference | ngokchaoho | 0 | 7 | corporate flight bookings | 1,109 | 0.604 | Medium | 17,535 |
https://leetcode.com/problems/corporate-flight-bookings/discuss/2612023/Python-or-Prefix-sum-or-O(n) | class Solution:
def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:
def update(first, last, seats):
diff[first] += seats
if last + 1 < n:
diff[last + 1] -= seats
def getResult():
result = [diff[0]]
for i in range(1, n):
result.append(result[i - 1] + diff[i])
return result
diff = [0 for _ in range(n)]
for info in bookings:
update(info[0] - 1, info[1] - 1, info[2])
return getResult() | corporate-flight-bookings | Python | Prefix sum | O(n) | MichelleZou | 0 | 30 | corporate flight bookings | 1,109 | 0.604 | Medium | 17,536 |
https://leetcode.com/problems/corporate-flight-bookings/discuss/2597102/Python-or-Range-Addition-Technique | class Solution:
def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:
res = [0]*n
for f, l, seats in bookings:
res[f-1] += seats
if l < n:
res[l] -= seats
for i in range(1, n):
res[i] += res[i-1]
return res | corporate-flight-bookings | Python | Range Addition Technique | leet_satyam | 0 | 28 | corporate flight bookings | 1,109 | 0.604 | Medium | 17,537 |
https://leetcode.com/problems/corporate-flight-bookings/discuss/2561163/Sweep-Line-Python | class Solution:
# Sweep Line solution
def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:
res = [0] * (n + 1)
for i, j, k in bookings:
res[i - 1] += k
res[j] -= k
for i in range(1, n):
res[i] += res[i - 1]
return res[:n] | corporate-flight-bookings | Sweep Line Python | shiv-codes | 0 | 8 | corporate flight bookings | 1,109 | 0.604 | Medium | 17,538 |
https://leetcode.com/problems/corporate-flight-bookings/discuss/2291016/Python-oror-Easy-Solution-O(n) | class Solution:
def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:
flights = [0]*n
for start,end,seats in bookings:
flights[start-1] += seats
if end < n: flights[end] -= seats
for i in range(n-1):
flights[i+1] += flights[i]
return flights | corporate-flight-bookings | Python || Easy Solution O(n) | morpheusdurden | 0 | 57 | corporate flight bookings | 1,109 | 0.604 | Medium | 17,539 |
https://leetcode.com/problems/corporate-flight-bookings/discuss/1843439/Pythoon3-Clean-solution-with-Difference-Array | class Solution:
def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:
res, diffs = [0]*n, [0]*n
for i in range(0, len(bookings)):
first = bookings[i][0] - 1
last = bookings[i][1] - 1
k = bookings[i][2]
# increment res[first..] by k
diffs[first] += k
# decrement res[last+1..] by k
if (last+1 < n):
diffs[last+1] -= k
res[0] = diffs[0]
for i in range(1, n):
res[i] = res[i-1] + diffs[i]
return res | corporate-flight-bookings | [Pythoon3] Clean solution with Difference Array | leqinancy | 0 | 53 | corporate flight bookings | 1,109 | 0.604 | Medium | 17,540 |
https://leetcode.com/problems/corporate-flight-bookings/discuss/1773010/Python-or-RangeSum | class Solution:
def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:
#RangeSum
dp=[0]*(n+2)
for start,end,seats in bookings:
dp[start]+=seats
dp[end+1]-=seats
for i in range(1,n+1):
dp[i]=dp[i]+dp[i-1]
dp.pop(0)
dp.pop()
return dp | corporate-flight-bookings | Python | RangeSum | heckt27 | 0 | 49 | corporate flight bookings | 1,109 | 0.604 | Medium | 17,541 |
https://leetcode.com/problems/corporate-flight-bookings/discuss/1768131/sum-of-differnce-python3 | class Solution:
def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:
diff = [ 0 for i in range(n)]
for li in bookings:
diff[li[0]-1] += li[2]
if li[1] < n:
diff[li[1]] -= li[2]
answer = []
accum_sum = 0
for num in diff:
accum_sum += num
answer.append(accum_sum)
return answer | corporate-flight-bookings | sum of differnce python3 | ngokchaoho | 0 | 17 | corporate flight bookings | 1,109 | 0.604 | Medium | 17,542 |
https://leetcode.com/problems/corporate-flight-bookings/discuss/1743687/Python3-oror-O(n)-time-oror-O(1)-space-oror-Prefix-Sum | class Solution:
def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:
res = [0] * (n+1)
for idx in range(len(bookings)):
start, end = bookings[idx][0], bookings[idx][1]
res[start] += bookings[idx][2]
if end < n:
res[end+1] += -bookings[idx][2]
for idx in range(1,n+1):
res[idx] += res[idx-1]
res.pop(0)
return res
#TC -> O(N) || SC -> O(1) | corporate-flight-bookings | Python3 || O(n) time || O(1) space || Prefix Sum | s_m_d_29 | 0 | 73 | corporate flight bookings | 1,109 | 0.604 | Medium | 17,543 |
https://leetcode.com/problems/corporate-flight-bookings/discuss/328907/Why-isn't-my-code-efficient | class Solution:
def corpFlightBookings(self, b: List[List[int]], n: int) -> List[int]:
res=[0]*n
for i,j,k in b:
for m in range(i-1,j):
res[m]+=k
return res | corporate-flight-bookings | Why isn't my code efficient? | ketan35 | 0 | 118 | corporate flight bookings | 1,109 | 0.604 | Medium | 17,544 |
https://leetcode.com/problems/delete-nodes-and-return-forest/discuss/1025341/Python3-dfs-O(N) | class Solution:
def delNodes(self, root: TreeNode, to_delete: List[int]) -> List[TreeNode]:
to_delete = set(to_delete) # O(1) lookup
def fn(node, pval):
"""Return node upon deletion of required values."""
if not node: return
if node.val in to_delete:
node.left = fn(node.left, None)
node.right = fn(node.right, None)
return
else:
if not pval: ans.append(node)
node.left = fn(node.left, node.val)
node.right = fn(node.right, node.val)
return node
ans = []
fn(root, None)
return ans | delete-nodes-and-return-forest | [Python3] dfs O(N) | ye15 | 5 | 233 | delete nodes and return forest | 1,110 | 0.693 | Medium | 17,545 |
https://leetcode.com/problems/delete-nodes-and-return-forest/discuss/925272/Python-Recursive-DFS. | class Solution:
def delNodes(self, root_node: TreeNode, to_delete: List[int]) -> List[TreeNode]:
blacklist = set(to_delete)
forest = []
def helper(root, parent):
"""
Delete all blacklisted nodes from the tree rooted at `root`, append all resulting
non-empty trees to the forest, then return root (or None if the root is blacklisted).
`parent` is the parent node of `root` (or None if it has no parent).
"""
if root is None:
return None
if root.val in blacklist:
helper(root.left, None)
helper(root.right, None)
return None
root.left = helper(root.left, root)
root.right = helper(root.right, root)
if parent is None:
forest.append(root)
return root
helper(root_node, None)
return forest | delete-nodes-and-return-forest | [Python] Recursive DFS. | ehsquared92 | 3 | 180 | delete nodes and return forest | 1,110 | 0.693 | Medium | 17,546 |
https://leetcode.com/problems/delete-nodes-and-return-forest/discuss/1440151/Python-Clean-Iterative-DFS-or-98.64-faster | class Solution:
def delNodes(self, root: TreeNode, to_delete: List[int]) -> List[TreeNode]:
to_remove, queue, forest = set(to_delete), deque([(root, True)]), []
while queue:
node, flag = queue.pop()
if node.right:
queue.append((node.right, node.val in to_remove))
if node.right.val in to_remove: node.right = None
if node.left:
queue.append((node.left, node.val in to_remove))
if node.left.val in to_remove: node.left = None
if node.val not in to_remove and flag:
forest.append(node)
return forest | delete-nodes-and-return-forest | [Python] Clean Iterative DFS | 98.64% faster | soma28 | 2 | 268 | delete nodes and return forest | 1,110 | 0.693 | Medium | 17,547 |
https://leetcode.com/problems/delete-nodes-and-return-forest/discuss/1787062/Python-DFS | class Solution:
def delNodes(self, root: Optional[TreeNode], to_delete: List[int]) -> List[TreeNode]:
def dfs(node, is_root):
if not node:
return
is_node_deleted = node.val in to_delete
if is_root and not is_node_deleted:
result.append(node)
node.left = dfs(node.left, is_node_deleted)
node.right = dfs(node.right, is_node_deleted)
return node if not is_node_deleted else None
result = []
to_delete = set(to_delete)
dfs(root, True)
return result | delete-nodes-and-return-forest | Python, DFS | blue_sky5 | 1 | 111 | delete nodes and return forest | 1,110 | 0.693 | Medium | 17,548 |
https://leetcode.com/problems/delete-nodes-and-return-forest/discuss/720532/Python-Recursive-Solution-With-Comments | class Solution:
def delNodes(self, root: TreeNode, to_delete: List[int]) -> List[TreeNode]:
if not root: return []
def delUtil(root,roots):
if not root:return False
left = delUtil(root.left,roots)
right = delUtil(root.right,roots)
#If the left child has to be deleted, make it None
if left:root.left = None
#Same goes with right child
if right:root.right = None
#If the current node has to be deleted
if root.val in to_delete:
#Append the left child to roots
if root.left:roots.append(root.left)
#Append the right child to roots
if root.right:roots.append(root.right)
#Make the current node's left and right child None
root.left = root.right = None
#Return True if the current node has to be deleted
return True
#Returns False if the current node doesn't have to be deleted
return False
roots = []
#If delUtil returns False, append the root of the tree to roots
if not delUtil(root,roots):roots.append(root)
return roots | delete-nodes-and-return-forest | [Python] Recursive Solution With Comments | spongeb0b | 1 | 60 | delete nodes and return forest | 1,110 | 0.693 | Medium | 17,549 |
https://leetcode.com/problems/delete-nodes-and-return-forest/discuss/1426784/Python3-Recursion-DFS | class Solution:
def traversal(self, node, to_delete, ans):
if node == None:
return False
if self.traversal(node.left, to_delete, ans):
node.left = None
if self.traversal(node.right, to_delete, ans):
node.right = None
if node.val in to_delete:
if node.left and node.left.val not in to_delete:
ans.append(node.left)
if node.right and node.right.val not in to_delete:
ans.append(node.right)
return True
return False
def delNodes(self, root: TreeNode, to_delete: List[int]) -> List[TreeNode]:
s = set()
for i in to_delete:
s.add(i)
ans = []
if not self.traversal(root, s, ans):
ans.append(root)
return ans | delete-nodes-and-return-forest | [Python3] Recursion DFS | maosipov11 | 0 | 60 | delete nodes and return forest | 1,110 | 0.693 | Medium | 17,550 |
https://leetcode.com/problems/delete-nodes-and-return-forest/discuss/1149635/Python3%3A-Delete-Nodes-(1110) | class Solution:
def delNodes(self, root: TreeNode, to_delete: List[int]) -> List[TreeNode]:
to_be_deleted = set(to_delete)
self.roots = []
if root.val not in to_be_deleted:
self.roots.append(root)
self.delete_nodes(root, None, to_be_deleted)
return self.roots
def delete_nodes(self, root, p, to_be_deleted):
if root.val in to_be_deleted:
if p:
if p.left == root:
p.left = None
else:
p.right = None
if root.left:
if root.left.val not in to_be_deleted:
self.roots.append(root.left)
self.delete_nodes(root.left, root, to_be_deleted)
root.left = None
if root.right:
if root.right.val not in to_be_deleted:
self.roots.append(root.right)
self.delete_nodes(root.right, root, to_be_deleted)
root.right = None
else:
if root.left:
self.delete_nodes(root.left, root, to_be_deleted)
if root.right:
self.delete_nodes(root.right, root, to_be_deleted) | delete-nodes-and-return-forest | [Python3]: Delete Nodes (1110) | ManmayB | 0 | 47 | delete nodes and return forest | 1,110 | 0.693 | Medium | 17,551 |
https://leetcode.com/problems/delete-nodes-and-return-forest/discuss/769806/Python-DFS-Recursion | class Solution:
# Time: O(n)
# Space: O(h)
def delNodes(self, root: TreeNode, to_delete: List[int]) -> List[TreeNode]:
self.delete = set(to_delete)
if root.val in self.delete:
self.res = []
else:
self.res = [root]
def dfs(node):
if not node:
return False
l = dfs(node.left)
r = dfs(node.right)
ret = False
if node.val in self.delete:
if node.left and not l:
self.res.append(node.left)
if node.right and not r:
self.res.append(node.right)
ret = True
if l:
node.left = None
if r:
node.right = None
return ret
dfs(root)
return self.res | delete-nodes-and-return-forest | Python DFS Recursion | whissely | 0 | 144 | delete nodes and return forest | 1,110 | 0.693 | Medium | 17,552 |
https://leetcode.com/problems/delete-nodes-and-return-forest/discuss/328872/Python-recursive-solution | class Solution:
def delNodes(self, root: TreeNode, to_delete: List[int]) -> List[TreeNode]:
res=[]
def rec(roo):
if not roo.left and not roo.right:
if roo.val in to_delete:
return None
return roo
nonlocal res
if roo.left:
roo.left=rec(roo.left)
if roo.right:
roo.right=rec(roo.right)
if roo.val in to_delete:
if roo.left: res.append(roo.left)
if roo.right:res.append(roo.right)
return None
return roo
root=rec(root)
if root:
res.append(root)
return res | delete-nodes-and-return-forest | Python recursive solution | ketan35 | 0 | 37 | delete nodes and return forest | 1,110 | 0.693 | Medium | 17,553 |
https://leetcode.com/problems/delete-nodes-and-return-forest/discuss/1216822/Python3-Concise-Postorder-DFS | class Solution:
def delNodes(self, root: TreeNode, to_delete: List[int]) -> List[TreeNode]:
trees = []
targets = set(to_delete)
def dfs(root):
if (not root): return root
root.left = dfs(root.left)
root.right = dfs(root.right)
if (root.val not in targets): return root
if (root.left): trees.append(root.left)
if (root.right): trees.append(root.right)
return None
dummy = TreeNode(to_delete[0], left=root)
dfs(dummy)
return trees | delete-nodes-and-return-forest | Python3 - Concise Postorder DFS | Bruception | -1 | 224 | delete nodes and return forest | 1,110 | 0.693 | Medium | 17,554 |
https://leetcode.com/problems/maximum-nesting-depth-of-two-valid-parentheses-strings/discuss/2825324/Python-oror-98.06-Faster-oror-Greedy-Approach-oror-O(N)-Solution | class Solution:
def maxDepthAfterSplit(self, seq: str) -> List[int]:
ans=[]
prev=1
for i in seq:
if i=='(':
if prev==0:
ans.append(1)
else:
ans.append(0)
else:
ans.append(prev)
if prev==0:
prev=1
else:
prev=0
return ans | maximum-nesting-depth-of-two-valid-parentheses-strings | Python || 98.06% Faster || Greedy Approach || O(N) Solution | DareDevil_007 | 1 | 10 | maximum nesting depth of two valid parentheses strings | 1,111 | 0.732 | Medium | 17,555 |
https://leetcode.com/problems/maximum-nesting-depth-of-two-valid-parentheses-strings/discuss/2825291/Python-oror-Easy-oror-Explained-oror-O(n)-Solution | class Solution:
def maxDepthAfterSplit(self, seq: str) -> List[int]:
m,c,n=0,0,len(seq)
for i in range(n):
if seq[i]=='(':
c+=1
m=max(c,m) # Here m is the maximium depth of the VPS
elif seq[i]==')':
c-=1
a=[]
m//=2 # Minimum depth possible by breaking string in two parts A and B
for i in range(n):
if seq[i]=='(':
c+=1
if c<=m:
a.append(0) #For A
else:
a.append(1) #For B
else:
if c<=m:
a.append(0)
else:
a.append(1)
c-=1
return a | maximum-nesting-depth-of-two-valid-parentheses-strings | Python || Easy || Explained || O(n) Solution | DareDevil_007 | 1 | 9 | maximum nesting depth of two valid parentheses strings | 1,111 | 0.732 | Medium | 17,556 |
https://leetcode.com/problems/maximum-nesting-depth-of-two-valid-parentheses-strings/discuss/1295673/easy-greedy-or-O(n)-or-python | class Solution:
def maxDepthAfterSplit(self, seq: str) -> List[int]:
ans=[]
la=0
lb=0
for i in range(len(seq)):
if seq[i]=='(':
if la > lb:
lb+=1
ans.append(0)
elif lb>la:
la+=1
ans.append(1)
else:
la+=1
ans.append(1)
else:
if la >0:
ans.append(1)
la-=1
elif lb>0:
ans.append(0)
lb-=1
return ans | maximum-nesting-depth-of-two-valid-parentheses-strings | easy greedy | O(n) | python | chikushen99 | 1 | 191 | maximum nesting depth of two valid parentheses strings | 1,111 | 0.732 | Medium | 17,557 |
https://leetcode.com/problems/maximum-nesting-depth-of-two-valid-parentheses-strings/discuss/461180/Python-3-(beats-~95)-(readable) | class Solution:
def maxDepthAfterSplit(self, P: str) -> List[int]:
D, A, v = {'(':1, ')':-1}, [], 0
for p in P:
if v*D[p] > 0:
v -= D[p]
A.append(0)
else:
v += D[p]
A.append(1)
return A
- Junaid Mansuri
- Chicago, IL | maximum-nesting-depth-of-two-valid-parentheses-strings | Python 3 (beats ~95%) (readable) | junaidmansuri | 1 | 408 | maximum nesting depth of two valid parentheses strings | 1,111 | 0.732 | Medium | 17,558 |
https://leetcode.com/problems/maximum-nesting-depth-of-two-valid-parentheses-strings/discuss/2792026/python-solution | class Solution:
def maxDepthAfterSplit(self, seq: str) -> List[int]:
A = []
B = []
ans = []
for i in seq:
if i == '(':
if A == [] and B == []:
A.append(i)
ans.append(0)
elif len(A) < len(B):
A.append(i)
ans.append(0)
else:
B.append(i)
ans.append(1)
elif i == ')':
if A and A[-1] == '(':
A.pop()
ans.append(0)
elif B and B[-1] == '(':
B.pop()
ans.append(1)
return ans | maximum-nesting-depth-of-two-valid-parentheses-strings | python solution | shingnapure_shilpa17 | 0 | 3 | maximum nesting depth of two valid parentheses strings | 1,111 | 0.732 | Medium | 17,559 |
https://leetcode.com/problems/maximum-nesting-depth-of-two-valid-parentheses-strings/discuss/2786540/python-3-or-simple-O(n)O(1) | class Solution:
def maxDepthAfterSplit(self, seq: str) -> List[int]:
curOpen = 0
answer = []
for c in seq:
if c == '(':
curOpen += 1
answer.append(curOpen & 1)
else:
answer.append(curOpen & 1)
curOpen -= 1
return answer | maximum-nesting-depth-of-two-valid-parentheses-strings | python 3 | simple O(n)/O(1) | dereky4 | 0 | 4 | maximum nesting depth of two valid parentheses strings | 1,111 | 0.732 | Medium | 17,560 |
https://leetcode.com/problems/maximum-nesting-depth-of-two-valid-parentheses-strings/discuss/2178655/PYTHON-SOL-or-GREEDY-or-EASY-or-EXPLAINED-or-LINEAR-TIME-COMPLEXITY-or | class Solution:
def maxDepthAfterSplit(self, seq: str) -> List[int]:
ans = []
last = 1
for i in seq:
if i == '(':
if last == 0: ans.append(1)
else:ans.append(0)
else:
ans.append(last)
last = (last + 1) % 2
return ans | maximum-nesting-depth-of-two-valid-parentheses-strings | PYTHON SOL | GREEDY | EASY | EXPLAINED | LINEAR TIME COMPLEXITY | | reaper_27 | 0 | 85 | maximum nesting depth of two valid parentheses strings | 1,111 | 0.732 | Medium | 17,561 |
https://leetcode.com/problems/maximum-nesting-depth-of-two-valid-parentheses-strings/discuss/1216948/Python3-greedy | class Solution:
def maxDepthAfterSplit(self, seq: str) -> List[int]:
ans, depth = [], 0
for i, x in enumerate(seq):
if x == "(": depth += 1
ans.append(depth & 1)
if x == ")": depth -= 1
return ans | maximum-nesting-depth-of-two-valid-parentheses-strings | [Python3] greedy | ye15 | 0 | 51 | maximum nesting depth of two valid parentheses strings | 1,111 | 0.732 | Medium | 17,562 |
https://leetcode.com/problems/maximum-nesting-depth-of-two-valid-parentheses-strings/discuss/474252/Python3-95.27-(40-ms)100.00-(13.1-MB)-O(n)-time-O(n)-space-(output)-greedy | class Solution:
def maxDepthAfterSplit(self, seq: str) -> List[int]:
depths = [0, 0] #depths[0]: A, depths[1]: B
answer = []
for char in seq:
if (char == '('):
if (depths[0] < depths[1]):
answer.append(0)
depths[0] += 1
else:
answer.append(1)
depths[1] += 1
else:
if (depths[0] > depths[1]):
depths[0] -= 1
answer.append(0)
else:
depths[1] -= 1
answer.append(1)
return answer | maximum-nesting-depth-of-two-valid-parentheses-strings | Python3 95.27% (40 ms)/100.00% (13.1 MB) -- O(n) time / O(n) space (output) -- greedy | numiek_p | 0 | 143 | maximum nesting depth of two valid parentheses strings | 1,111 | 0.732 | Medium | 17,563 |
https://leetcode.com/problems/relative-sort-array/discuss/343445/Python3.-Actually-easy-to-understand.-Beats-75-on-speed-and-100-on-memory | class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
# initialise a dictionary since we're going to want to count the occurences of each element in arr1
dic = {}
# this loop populates the dictionary with the number of occurences for each element
for elem in arr1:
if dic.get(elem) is None:
dic[elem] = 1
else:
dic[elem] = dic[elem] + 1
# initialise a new list to store the values which exist in both arr2 and arr1
output = []
# populate output with the elements multiplied by their occurences (e.g. [1]*2 = [1, 1])
for elem in arr2:
output += [elem]*dic[elem]
# initialise a new list to store the elements which are in arr1 but not arr2
extra_output = []
# populate extra_output with these elements multiplied by their occurences.
# Note: set(arr1)-set(arr2) provides us with the set of numbers which exist in arr1 but not in arr2
for elem in set(arr1)-set(arr2):
extra_output += [elem]*dic[elem]
# return the first list and the sorted second list
return output + sorted(extra_output) | relative-sort-array | Python3. Actually easy to understand. Beats 75% on speed and 100% on memory | softbabywipes | 12 | 1,800 | relative sort array | 1,122 | 0.684 | Easy | 17,564 |
https://leetcode.com/problems/relative-sort-array/discuss/2272852/Python3-Fast-solution-with-low-memory-usage | class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
sorted_lst = []
for x in arr2:
while x in arr1:
sorted_lst.append(x)
arr1.remove(x)
return(sorted_lst+sorted(arr1)) | relative-sort-array | Python3 Fast solution with low memory usage | Yodawgz0 | 6 | 184 | relative sort array | 1,122 | 0.684 | Easy | 17,565 |
https://leetcode.com/problems/relative-sort-array/discuss/1278973/python-easy-to-understand | class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
result = []
temp = []
for i in arr2:
count = arr1.count(i)
while count > 0:
result.append(i)
count -= 1
for i in arr1:
if i not in arr2:
temp.append(i)
result += sorted(temp)
return result | relative-sort-array | python easy to understand | user2227R | 2 | 125 | relative sort array | 1,122 | 0.684 | Easy | 17,566 |
https://leetcode.com/problems/relative-sort-array/discuss/2678086/Python-HashMap-Fast-Solution-Step-by-Step-Explanation | class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
#Start with creating an array/list to store answer
ans = []
#Create a hashmap and store all the elements as key and their frequency as value
mapD = {}
for i in arr1:
#map.get(i, 0) to avoid key error in hashmap/dictionary
mapD[i] = 1 + mapD.get(i, 0)
#update the answer with elements as their frequncy in arr1 but in the sequence of arr2
for i in arr2:
ans[:] += [i] * mapD[i]
#create another hashmap and a temporary list to find and store all elements that are not in arr2
h = {}
li = []
for i in arr1:
h[i] = 1 + h.get(i, 0)
#Update the temporary list with elements and their frequency which are distinct in arr1
for i in h:
if i not in arr2:
li[:] += [i] * h[i]
li.sort()
#merge the both arrays and here is the final ans
ans[:] += li[:]
return ans | relative-sort-array | Python HashMap Fast Solution - Step by Step Explanation | iamgauravshukla | 1 | 238 | relative sort array | 1,122 | 0.684 | Easy | 17,567 |
https://leetcode.com/problems/relative-sort-array/discuss/2660687/Python-oror-O(NlogN) | class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
ans1=[]
ans2=[]
for i in arr2:
c=arr1.count(i)
for j in range(c):
ans1.append(i)
for i in arr1:
if i not in arr2:
ans2.append(i)
ans2.sort()
return ans1+ans2 | relative-sort-array | Python || O(NlogN) | Sneh713 | 1 | 129 | relative sort array | 1,122 | 0.684 | Easy | 17,568 |
https://leetcode.com/problems/relative-sort-array/discuss/2371845/Relative-Sort-Array | class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
x = {}
for i in arr1:
if i in x:
x[i]+=1
else:
x[i]= 1
out = []
for i in arr2:
for j in range(x[i]):
out.append(i)
x[i]-=1
tobesorted = []
for i in x:
if x[i]>0:
for j in range(x[i]):
tobesorted.append(i)
x[i]-=1
print(tobesorted)
for i in range (1,len(tobesorted)):
key = tobesorted[i]
j = i-1
while j>=0 and key <tobesorted[j]:
tobesorted[j+1]=tobesorted[j]
j-=1
tobesorted[j+1]= key
return out+tobesorted | relative-sort-array | Relative Sort Array | dhananjayaduttmishra | 1 | 40 | relative sort array | 1,122 | 0.684 | Easy | 17,569 |
https://leetcode.com/problems/relative-sort-array/discuss/2371845/Relative-Sort-Array | class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
x = [0]*1001
for i in arr1:
x[i]+=1
out = []
for i in arr2:
for j in range(x[i]):
out.append(i)
x[i]-=1
for i in range(len(x)):
if x[i]>0:
for j in range(x[i]):
out.append(i)
x[i]-=1
return out | relative-sort-array | Relative Sort Array | dhananjayaduttmishra | 1 | 40 | relative sort array | 1,122 | 0.684 | Easy | 17,570 |
https://leetcode.com/problems/relative-sort-array/discuss/2256866/Python-O(N-%2B-M)-Time-and-O(N)-Space-Bucket-Sort | class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
obj = {}
for i, n in enumerate(arr2):
obj[n] = i
# create fixed bucket
bucket = [0] * (1001)
# find freq of values from arr1
for num in arr1:
bucket[num] += 1
res = []
# for all values in arr2 one pass bucket and add to res list and set val to 0
for num in arr2:
res += bucket[num] * [num]
bucket[num] = 0
# final one pass on bucket to find remaining values from arr1 to add in ascending order
for i, n in enumerate(bucket):
if n:
res += (n * [i])
return res | relative-sort-array | Python O(N + M) Time and O(N) Space Bucket Sort | jlee9077 | 1 | 54 | relative sort array | 1,122 | 0.684 | Easy | 17,571 |
https://leetcode.com/problems/relative-sort-array/discuss/1476140/Python-easy-to-understand | class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
h = defaultdict(int)
for i in range(len(arr2)):
h[arr2[i]] = i
k = max(arr1)
arr1.sort(key = lambda x: h.get(x, k+x))
return arr1 | relative-sort-array | Python easy to understand | byuns9334 | 1 | 122 | relative sort array | 1,122 | 0.684 | Easy | 17,572 |
https://leetcode.com/problems/relative-sort-array/discuss/1037776/Python3-simple-solution | class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
ans = []
c = Counter(arr1)
for i in range(len(arr2)):
ans += [arr2[i]]*c[arr2[i]]
for i in ans:
arr1.remove(i)
return ans+sorted(arr1) | relative-sort-array | Python3 simple solution | EklavyaJoshi | 1 | 158 | relative sort array | 1,122 | 0.684 | Easy | 17,573 |
https://leetcode.com/problems/relative-sort-array/discuss/335412/Solution-in-Python-3 | class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
S = []
for i in arr2:
j = 0
while j < len(arr1):
if arr1[j] == i:
S += [i]
del arr1[j]
j -= 1
j += 1
return(S+sorted(arr1))
- Python 3
- Junaid Mansuri | relative-sort-array | Solution in Python 3 | junaidmansuri | 1 | 557 | relative sort array | 1,122 | 0.684 | Easy | 17,574 |
https://leetcode.com/problems/relative-sort-array/discuss/2827343/python-easy-to-understand | class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
h = collections.Counter(arr1)
output = []
for num in arr2:
while h[num] > 0:
output.append(num)
h[num] -= 1
l = sorted([item for item in arr1 if item not in arr2])
for item in l:
output.append(item)
return output | relative-sort-array | python - easy to understand | IAMdkk | 0 | 1 | relative sort array | 1,122 | 0.684 | Easy | 17,575 |
https://leetcode.com/problems/relative-sort-array/discuss/2818719/Python3-Easy-O(len(arr1)%2Blen(arr2)) | class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
res = []
counter = Counter(arr1)
for a in arr2:
res += [a] * counter[a]
del counter[a]
for k, v in sorted(counter.items()):
res += [k]* v
return res | relative-sort-array | Python3 Easy O(len(arr1)+len(arr2)) | hcodecode | 0 | 5 | relative sort array | 1,122 | 0.684 | Easy | 17,576 |
https://leetcode.com/problems/relative-sort-array/discuss/2788903/Easy-Solution-oror-Brute-Force-approach-oror-Python | class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
lst=[]
e=arr1
for i in arr2:
arr1.remove(i)
b=set(arr1)
a=Counter(arr2)
for i,j in a.items():
if i in b:
di={}
c=arr1.count(i)
c=c+j
di={i:c-1}
a.update(di)
dst=[]
for i in e:
if i not in arr2:
dst.append(i)
s=""
dst.sort()
nst=[]
for i,j in a.items():
for k in range(j):
nst.append(i)
return nst+dst | relative-sort-array | Easy Solution || Brute Force approach || Python | Kaustubhmishra | 0 | 2 | relative sort array | 1,122 | 0.684 | Easy | 17,577 |
https://leetcode.com/problems/relative-sort-array/discuss/2783567/python3-beats-94 | class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
d = collections.Counter(arr1)
out = []
for i in arr2:
out += [i] * d[i]
del d[i]
for k in sorted(d):
out += [k] * d[k]
return out | relative-sort-array | python3 beats 94% | mishraharekrushna16 | 0 | 5 | relative sort array | 1,122 | 0.684 | Easy | 17,578 |
https://leetcode.com/problems/relative-sort-array/discuss/2755861/faster-than-99-of-python | class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
l = []
for i in arr2:
if i in arr1:
for _ in range(arr1.count(i)):
l.append(i)
arr1.remove(i)
arr1.sort()
for i in arr1:
if i not in l:
for _ in range(arr1.count(i)):
l.append(i)
return l | relative-sort-array | faster than 99% of python | dastankg | 0 | 8 | relative sort array | 1,122 | 0.684 | Easy | 17,579 |
https://leetcode.com/problems/relative-sort-array/discuss/2748741/One-Dictionary-and-Sorting-with-Custom-Criteria | class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
hashmap = {num:idx for idx, num in enumerate(arr2)}
return sorted(arr1, key=lambda num: hashmap.get(num, len(arr1) + num)) | relative-sort-array | One Dictionary and Sorting with Custom Criteria | kcstar | 0 | 10 | relative sort array | 1,122 | 0.684 | Easy | 17,580 |
https://leetcode.com/problems/relative-sort-array/discuss/2700262/Python3-solution-!-defaultdict-!-99.89-in-time-and-9.08-in-space | class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
res = []
dit = defaultdict(int)
for i in arr1:
dit[i] += 1
for j in arr2:
res.extend([j]*dit[j])
for k in sorted(list(set(arr1) - set(arr2))):
res.extend([k]*dit[k])
return res | relative-sort-array | Python3 solution ! defaultdict ! 99.89% in time and 9.08% in space | w7Pratham | 0 | 12 | relative sort array | 1,122 | 0.684 | Easy | 17,581 |
https://leetcode.com/problems/relative-sort-array/discuss/2667164/Python-3-Easy-Solution | class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
k = []
q = []
for j in range(len(arr2)):
for i in range(len(arr1)):
search = arr2[j]
if search == arr1[i]:
k.append(arr1[i])
y = set(arr1)
x = set(arr2)
for i in arr1:
if i not in arr2:
q.append(i)
q.sort()
for i in q:
k.append(i)
return k | relative-sort-array | Python 3 Easy Solution | rahulnakum | 0 | 9 | relative sort array | 1,122 | 0.684 | Easy | 17,582 |
https://leetcode.com/problems/relative-sort-array/discuss/2620507/Easy-Understanding-Python | class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
count = [0] * len(arr2)
for i in range(len(arr2)):
count[i] = arr1.count(arr2[i])
left = []
for i in range(len(arr1)):
if arr1[i] not in arr2:
left.append(arr1[i])
left = sorted(left)
res = []
for i in range(len(arr2)):
for j in range(count[i]):
res.append(arr2[i])
res = res + left
return res | relative-sort-array | Easy Understanding Python | EdenXiao | 0 | 16 | relative sort array | 1,122 | 0.684 | Easy | 17,583 |
https://leetcode.com/problems/relative-sort-array/discuss/2590528/Python-solution-using-dictionary | class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
dict_ar1 = collections.Counter(arr1)
new_arr = []
for num in arr2:
if num in dict_ar1:
[new_arr.append(num) for _ in range(dict_ar1[num])]
for num in new_arr:
arr1.remove(num)
arr1.sort()
return new_arr + arr1 | relative-sort-array | Python solution using dictionary | samanehghafouri | 0 | 20 | relative sort array | 1,122 | 0.684 | Easy | 17,584 |
https://leetcode.com/problems/relative-sort-array/discuss/2445522/easy-python-solution | class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
diff = []
for i in arr1 :
if i not in arr2 :
diff.append(i)
diff.sort()
ans = []
for num in arr2 :
for i in range(arr1.count(num)) :
ans.append(num)
return ans + diff | relative-sort-array | easy python solution | sghorai | 0 | 57 | relative sort array | 1,122 | 0.684 | Easy | 17,585 |
https://leetcode.com/problems/relative-sort-array/discuss/2263276/5-simple-steps-using-Python | class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
res = []
freq = {}
// First make freq cache
for i in arr1:
freq[i] = 1 + freq.get(i, 0)
// Second according to occurance add element into res
for j in arr2:
res = res + [j] * freq[j]
// Third find left elements and sort them in acccessding order
left = [i for i in arr1 if i not in res]
left.sort()
// Last if left array is not empty then add into res
return res + left if left else res | relative-sort-array | 5 simple steps using Python | ankurbhambri | 0 | 55 | relative sort array | 1,122 | 0.684 | Easy | 17,586 |
https://leetcode.com/problems/relative-sort-array/discuss/2178958/Python-Solution-Beginner-Friendly | class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
l=[]
for i in range(len(arr2)):
s=arr1.count(arr2[i])
while(s!=0):
arr1.remove(arr2[i])
l.append(arr2[i])
s-=1
if len(arr1)!=0:
arr1.sort()
return l[:]+arr1[:]
else:
return l | relative-sort-array | Python Solution - Beginner Friendly | T1n1_B0x1 | 0 | 45 | relative sort array | 1,122 | 0.684 | Easy | 17,587 |
https://leetcode.com/problems/relative-sort-array/discuss/2003209/easy-python-code | class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
j = 0
for i in arr2:
k = j
while(k<len(arr1)):
if arr1[k] == i:
arr1[j],arr1[k] = arr1[k],arr1[j]
j+=1
k+=1
arr1[j:] = sorted(arr1[j:])
return arr1 | relative-sort-array | easy python code | dakash682 | 0 | 123 | relative sort array | 1,122 | 0.684 | Easy | 17,588 |
https://leetcode.com/problems/relative-sort-array/discuss/1923505/Python-simple-solution-using-key-function-for-sorting | class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
order = {num: i for i, num in enumerate(arr2)}
def key_func(x):
# we want anything that isn't in arr2 to be sorted to the end of the array, so we use
# infinity in that case
prio = order[x] if x in order else float("inf")
# given a number x, sort it based on its priority as dictated by arr2
# if it's not in arr2 then it will have infinity as its priority
# in cases of ties for prio, we want to compare the value x itself
# which is why we return a tuple
return (prio, x)
arr1.sort(key=key_func)
return arr1 | relative-sort-array | Python simple solution using key function for sorting | mjhoward540 | 0 | 151 | relative sort array | 1,122 | 0.684 | Easy | 17,589 |
https://leetcode.com/problems/relative-sort-array/discuss/1896286/Python-easy-solution-using-concept-of-sets | class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
res = []
for i in arr2:
res.extend([i] * arr1.count(i))
for i in sorted(set(arr1).difference(set(arr2))):
res.extend([i] * arr1.count(i))
return res | relative-sort-array | Python easy solution using concept of sets | alishak1999 | 0 | 116 | relative sort array | 1,122 | 0.684 | Easy | 17,590 |
https://leetcode.com/problems/relative-sort-array/discuss/1889818/Python3-or-Simple | class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
new_arr2 = []
for n in arr2:
count = arr1.count(n)
new_arr2 = new_arr2 + [n] * count
for _ in range(count):
arr1.remove(n)
arr1.sort()
return new_arr2 + arr1 | relative-sort-array | Python3 | Simple | user0270as | 0 | 57 | relative sort array | 1,122 | 0.684 | Easy | 17,591 |
https://leetcode.com/problems/relative-sort-array/discuss/1865399/Python-(Simple-Approach-and-Beginner-Friendly) | class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
leftover = []
res = []
for i in arr2:
if i in arr1:
for j in range(arr1.count(i)):
res.append(i)
for i in arr1:
if i not in arr2:
leftover.append(i)
for i in sorted(leftover):
res.append(i)
return res | relative-sort-array | Python (Simple Approach and Beginner-Friendly) | vishvavariya | 0 | 97 | relative sort array | 1,122 | 0.684 | Easy | 17,592 |
https://leetcode.com/problems/relative-sort-array/discuss/1813456/Python-easy-to-read-and-understand | class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
ans = []
for val in arr2:
num = arr1.count(val)
for i in range(num):
ans.append(val)
temp = []
for val in arr1:
if val not in arr2:
temp.append(val)
temp.sort()
return ans + temp | relative-sort-array | Python easy to read and understand | sanial2001 | 0 | 84 | relative sort array | 1,122 | 0.684 | Easy | 17,593 |
https://leetcode.com/problems/relative-sort-array/discuss/1807677/Simple-understandable-code-in-pyhton | class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
dict1=dict(collections.Counter(arr1))
arr=[]
sec=[]
for i in range(len(arr2)):
temp=[]
if arr2[i] in dict1.keys():
temp.append(arr2[i])
arr=arr+temp*dict1[arr2[i]]
for key,values in dict1.items():
if key not in arr:
res=[]
res.append(key)
sec=sec+res*values
sec.sort()
return arr+sorted(sec) | relative-sort-array | Simple understandable code in pyhton | amannarayansingh10 | 0 | 89 | relative sort array | 1,122 | 0.684 | Easy | 17,594 |
https://leetcode.com/problems/relative-sort-array/discuss/1806352/5-Lines-Python-Solution-oror-82-Faster-oror-Memory-less-than-92 | class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
ans = []
for c in arr2:
if c in arr1:
for i in range(arr1.count(c)): ans.append(c)
return ans + sorted([x for x in arr1 if x not in ans]) | relative-sort-array | 5-Lines Python Solution || 82% Faster || Memory less than 92% | Taha-C | 0 | 83 | relative sort array | 1,122 | 0.684 | Easy | 17,595 |
https://leetcode.com/problems/relative-sort-array/discuss/1794752/Dump-solution-using-python3 | class Solution:
def relativeSortArray(self, a: List[int], b: List[int]) -> List[int]:
data = []
for item in b:
if item in a:
data.append((item, a.count(item)))
ans = []
for item in data:
for i in range(item[1]):
ans.append(item[0])
others = []
for item in a :
if item in b :
continue
else :
others.append(item)
others.sort()
return ans+others | relative-sort-array | Dump solution using python3 | shakilbabu | 0 | 53 | relative sort array | 1,122 | 0.684 | Easy | 17,596 |
https://leetcode.com/problems/relative-sort-array/discuss/1664398/Python-dollarolution | class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
d, v = {}, []
for i in arr1:
if i not in d:
d[i] = 1
else:
d[i] += 1
for i in arr2:
for j in range(d[i]):
v.append(i)
d[i] -= 1
for i in sorted(set(arr1) - set(arr2)):
for j in range(d[i]):
v.append(i)
return v | relative-sort-array | Python $olution | AakRay | 0 | 114 | relative sort array | 1,122 | 0.684 | Easy | 17,597 |
https://leetcode.com/problems/relative-sort-array/discuss/1473052/Python-Sort | class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
def sort(x):
try:
return arr2.index(x)
except:
return len(arr2) + x - 1
arr1.sort(key = sort)
return arr1 | relative-sort-array | [Python] Sort | dev-josh | 0 | 73 | relative sort array | 1,122 | 0.684 | Easy | 17,598 |
https://leetcode.com/problems/relative-sort-array/discuss/1447282/WEEB-DOES-PYTHON-(BEATS-97.06) | class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
memo = Counter(arr1)
nums1, nums2 = set(arr1), set(arr2)
result= []
arr3 = sorted(nums1.difference(nums2))
for val in arr2:
result += [val] * memo[val]
for val in arr3:
result += [val] * memo[val]
return result | relative-sort-array | WEEB DOES PYTHON (BEATS 97.06%) | Skywalker5423 | 0 | 159 | relative sort array | 1,122 | 0.684 | Easy | 17,599 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.