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/sort-characters-by-frequency/discuss/2811397/PYTHON-SOLUTION-EXPLAINED-LINE-BY-LINE | class Solution:
def frequencySort(self, s: str) -> str:
#this method is done with the help of list for storing frequency for the ease of sorting
s=sorted(s) #you can do if you want for your easy understanding
new=list(set(s)) #for ease of storing frequncy in list
l=[] #store subarrays like ['frequency',character']
#storing the indexes of new (thats how we will make
#total subarrays in l) -> d={'character':'index in new'} further using those stored indeces in l
d={}
for i in range(len(new)):
d[new[i]]=i #storing index
for i in d.keys(): #creatig subarrays in l
l.append([0,i]) #initailly all frequencies are 0
for i in s: #updating frequncy
l[d[i]][0]+=1 #d[i] telling index in l of particular character
l.sort(reverse=True)
#sort in decreasing order as large frequency's
#characters should be at first (sorting according to the 0th indexes of l's subarrays)
ans="" #final string
for i in l:
ans=ans+(i[1]*i[0])
#i[1] having character and i[0] having its frequency
#(appending the character number of times its frequency is)
return ans | sort-characters-by-frequency | PYTHON SOLUTION - EXPLAINED LINE BY LINE✔ | T1n1_B0x1 | 0 | 2 | sort characters by frequency | 451 | 0.686 | Medium | 8,000 |
https://leetcode.com/problems/sort-characters-by-frequency/discuss/2802109/Python-%3A-Priority-Queue-(Heap)-oror-Intuitive-Solution | class Solution:
def frequencySort(self, s: str) -> str:
d={}
for i in s:
if i in d.keys():
d[i]+=1
else:
d[i]=1
ans=[]
for i,j in d.items():
ans.append([-j,i])
heapq.heapify(ans)
l=[]
while len(ans)>0:
c=heapq.heappop(ans)
a=c[0]
a*=-1
b=c[1]
for i in range(a):
l.append(b)
return "".join(l) | sort-characters-by-frequency | Python : Priority Queue (Heap) || Intuitive Solution | utsa_gupta | 0 | 2 | sort characters by frequency | 451 | 0.686 | Medium | 8,001 |
https://leetcode.com/problems/sort-characters-by-frequency/discuss/2793105/Beginner-Solution.-Full-explanation | class Solution:
def frequencySort(self, s: str) -> str:
d = (Counter(s))
t = d.most_common()
ans = ''
for k, v in t:
for i in range(v):
ans += k
return ans | sort-characters-by-frequency | Beginner Solution. Full explanation | _debanjan_10 | 0 | 2 | sort characters by frequency | 451 | 0.686 | Medium | 8,002 |
https://leetcode.com/problems/sort-characters-by-frequency/discuss/2702802/Easy-to-Understand-Python-Bucket-Sort-Solution | class Solution:
def frequencySort(self, s: str) -> str:
freq_by_letter = collections.Counter(s)
#len(s)+1 because need to account for "0"
letters_by_freq = [[] for i in range(len(s)+1)]
#fill buckets
for letter, freq in freq_by_letter.items():
letters_by_freq[freq].append(letter)
#iterate backwards from most frequent to least
res = ""
for i in range(len(letters_by_freq)-1,-1,-1):
letters = letters_by_freq[i]
for letter in letters:
res += letter*i
return res | sort-characters-by-frequency | Easy to Understand Python Bucket Sort Solution | sc1233 | 0 | 14 | sort characters by frequency | 451 | 0.686 | Medium | 8,003 |
https://leetcode.com/problems/sort-characters-by-frequency/discuss/2689544/Python-3-Solution-(Using-Heapq) | class Solution:
def frequencySort(self, s: str) -> str:
count=Counter(s)
pq=[]
heapq.heapify(pq)
for word,fre in count.items():
heapq.heappush(pq,(fre,word))
res=""
for i in range(len(pq)):
fre,word=heapq.heappop(pq)
res=fre*word+res
return res | sort-characters-by-frequency | Python 3 Solution (Using Heapq) | KRITGYA2001 | 0 | 5 | sort characters by frequency | 451 | 0.686 | Medium | 8,004 |
https://leetcode.com/problems/sort-characters-by-frequency/discuss/2679670/Simple-5-lines-of-python-code-with-clear-explanation-beats-99.98-by-time | class Solution:
def frequencySort(self, s: str) -> str:
d = collections.Counter(list(s))
heap = []
for i in d :
heapq.heappush(heap, [-d[i], i])
return "".join(-heap[0][0]*heapq.heappop(heap)[1] for _ in d) | sort-characters-by-frequency | Simple 5 lines of python code with clear explanation beats 99.98% by time | thrinadhsai78 | 0 | 5 | sort characters by frequency | 451 | 0.686 | Medium | 8,005 |
https://leetcode.com/problems/sort-characters-by-frequency/discuss/2674688/Easy-Python-Solution-Using-Dictionary | class Solution:
def frequencySort(self, s: str) -> str:
dic={}
for i in s:
if i not in dic:
dic[i]=1
else:
dic[i]+=1
t=list(s)
t=sorted(t,key=lambda x:(dic[x],x),reverse=True)
return ''.join(t) | sort-characters-by-frequency | Easy Python Solution Using Dictionary | ankitr8055 | 0 | 3 | sort characters by frequency | 451 | 0.686 | Medium | 8,006 |
https://leetcode.com/problems/sort-characters-by-frequency/discuss/2639744/python3or-using-heap | class Solution:
def frequencySort(self, s: str) -> str:
# count = Counter(s)
temp = [(-v,k) for k,v in Counter(s).items()]
heapify(temp)
r = []
for _ in range(len(temp)):
f,c = heappop(temp)
r.append(c*abs(f))
return ''.join(r) | sort-characters-by-frequency | python3| using heap | toddlers | 0 | 10 | sort characters by frequency | 451 | 0.686 | Medium | 8,007 |
https://leetcode.com/problems/sort-characters-by-frequency/discuss/2565156/easy-python-solution | class Solution:
def frequencySort(self, s: str) -> str:
count_list = []
char_list = [i for i in s]
chars = set(char_list)
for ch in chars :
count_list.append([ch, char_list.count(ch)])
sorted_list = sorted(count_list, key = lambda x: x[1], reverse = True)
ans = ""
for tp in sorted_list :
for i in range(tp[1]) :
ans += tp[0]
return ans | sort-characters-by-frequency | easy python solution | sghorai | 0 | 33 | sort characters by frequency | 451 | 0.686 | Medium | 8,008 |
https://leetcode.com/problems/sort-characters-by-frequency/discuss/2548987/Python-or-Fast-(98.98)-Short-and-Clear-Solution | class Solution:
def frequencySort(self, s: str) -> str:
res = [c[0] * c[1] for c in Counter(s).most_common()]
return ''.join(res) | sort-characters-by-frequency | Python | Fast (98.98%), Short and Clear Solution | Wartem | 0 | 51 | sort characters by frequency | 451 | 0.686 | Medium | 8,009 |
https://leetcode.com/problems/sort-characters-by-frequency/discuss/2508825/Python-solution-using-dictionary-heap | class Solution:
def frequencySort(self, s: str) -> str:
D = {l: s.count(l) for l in set(s)}
D = sorted(D.items(), key = lambda x: x[1])
res = ""
while D:
k, v = D.pop()
res += k*v
return "".join(res) | sort-characters-by-frequency | Python solution using dictionary / heap | yhc22593 | 0 | 13 | sort characters by frequency | 451 | 0.686 | Medium | 8,010 |
https://leetcode.com/problems/sort-characters-by-frequency/discuss/2508825/Python-solution-using-dictionary-heap | class Solution:
def frequencySort(self, s: str) -> str:
heap = [(-s.count(i), i) for i in set(s)]
heapify(heap)
res = ""
while heap:
v, k = heappop(heap)
res += k*(-v)
return res | sort-characters-by-frequency | Python solution using dictionary / heap | yhc22593 | 0 | 13 | sort characters by frequency | 451 | 0.686 | Medium | 8,011 |
https://leetcode.com/problems/sort-characters-by-frequency/discuss/2360882/simple-python-heap | class Solution:
def frequencySort(self, s: str) -> str:
counter = Counter(list(s))
h = []
for ch in counter:
heappush(h, (-counter[ch], ch))
res = ""
while h:
kv = heappop(h)
res = res + str(kv[1])*(kv[0]*-1)
return res | sort-characters-by-frequency | simple python heap | gasohel336 | 0 | 28 | sort characters by frequency | 451 | 0.686 | Medium | 8,012 |
https://leetcode.com/problems/sort-characters-by-frequency/discuss/2277041/Python-1-Liner | class Solution:
def frequencySort(self, s: str) -> str:
return "".join([k * n for k, n in sorted([(k, v) for k, v in Counter(s).items()], key=lambda t: t[1], reverse=True)]) | sort-characters-by-frequency | Python 1-Liner | amaargiru | 0 | 34 | sort characters by frequency | 451 | 0.686 | Medium | 8,013 |
https://leetcode.com/problems/sort-characters-by-frequency/discuss/2011633/Python-Solution-using-Map-and-sorting | class Solution:
def frequencySort(self, s: str) -> str:
string_count = {}
counts = []
for letter in s:
if letter not in string_count:
count = s.count(letter)
string_count[letter] = count
counts.append(count)
counts.sort(reverse=True)
result = []
for count in counts:
char = list(string_count.keys())[list(string_count.values()).index(count)]
result.append(char*count)
del string_count[char]
return "".join(result) | sort-characters-by-frequency | Python Solution using Map and sorting | hardik097 | 0 | 48 | sort characters by frequency | 451 | 0.686 | Medium | 8,014 |
https://leetcode.com/problems/sort-characters-by-frequency/discuss/1986640/Python-one-line-solution-with-comment | class Solution:
def frequencySort(self, s: str) -> str:
return "".join(letter * count for letter, count in Counter(s).most_common())
# s = "Aabb"
# Counter(s).most_common() --> [('b', 2), ('A', 1), ('a', 1)]
# letter * count for letter, count in Counter(s).most_common() --> ['bb', 'A', 'a']
# "".join(letter * count for letter, count in Counter(s).most_common()) --> 'bbAa' | sort-characters-by-frequency | Python one-line solution with comment | byroncharly3 | 0 | 69 | sort characters by frequency | 451 | 0.686 | Medium | 8,015 |
https://leetcode.com/problems/sort-characters-by-frequency/discuss/1929605/Python-Counter-or-Heap-or-Bucket-Sort-Multiple-Solutions-%2B-One-Liners | class Solution:
def frequencySort(self, s):
d = {}
for c in s:
if c not in d: d[c] = 1
else: d[c] += 1
s_sorted = sorted(s, key=lambda x: (d[x], x), reverse=True)
return "".join(s_sorted) | sort-characters-by-frequency | Python - Counter | Heap | Bucket Sort - Multiple Solutions + One Liners | domthedeveloper | 0 | 40 | sort characters by frequency | 451 | 0.686 | Medium | 8,016 |
https://leetcode.com/problems/sort-characters-by-frequency/discuss/1929605/Python-Counter-or-Heap-or-Bucket-Sort-Multiple-Solutions-%2B-One-Liners | class Solution:
def frequencySort(self, s):
c = Counter(s)
s_sorted = sorted(s, key=lambda x: (c[x], x), reverse=True)
return "".join(s_sorted) | sort-characters-by-frequency | Python - Counter | Heap | Bucket Sort - Multiple Solutions + One Liners | domthedeveloper | 0 | 40 | sort characters by frequency | 451 | 0.686 | Medium | 8,017 |
https://leetcode.com/problems/sort-characters-by-frequency/discuss/1929605/Python-Counter-or-Heap-or-Bucket-Sort-Multiple-Solutions-%2B-One-Liners | class Solution:
def frequencySort(self, s):
return (lambda c : "".join(sorted(s, key=lambda x: (c[x], x), reverse=True)))(Counter(s)) | sort-characters-by-frequency | Python - Counter | Heap | Bucket Sort - Multiple Solutions + One Liners | domthedeveloper | 0 | 40 | sort characters by frequency | 451 | 0.686 | Medium | 8,018 |
https://leetcode.com/problems/sort-characters-by-frequency/discuss/1929605/Python-Counter-or-Heap-or-Bucket-Sort-Multiple-Solutions-%2B-One-Liners | class Solution:
def frequencySort(self, s):
return "".join(c*f for c,f in sorted(Counter(s).items(), key=lambda x:x[1], reverse=True)) | sort-characters-by-frequency | Python - Counter | Heap | Bucket Sort - Multiple Solutions + One Liners | domthedeveloper | 0 | 40 | sort characters by frequency | 451 | 0.686 | Medium | 8,019 |
https://leetcode.com/problems/sort-characters-by-frequency/discuss/1929605/Python-Counter-or-Heap-or-Bucket-Sort-Multiple-Solutions-%2B-One-Liners | class Solution:
def frequencySort(self, s):
return "".join(c*f for c,f in Counter(s).most_common()) | sort-characters-by-frequency | Python - Counter | Heap | Bucket Sort - Multiple Solutions + One Liners | domthedeveloper | 0 | 40 | sort characters by frequency | 451 | 0.686 | Medium | 8,020 |
https://leetcode.com/problems/sort-characters-by-frequency/discuss/1929605/Python-Counter-or-Heap-or-Bucket-Sort-Multiple-Solutions-%2B-One-Liners | class Solution:
def frequencySort(self, s):
counter = Counter(s)
buckets = [[] for bucket in range(len(s)+1)]
for char, freq in counter.items():
buckets[freq].append(char)
ans = ""
for i in range(len(buckets)-1,-1,-1):
for char in buckets[i]:
ans += char*i
return ans | sort-characters-by-frequency | Python - Counter | Heap | Bucket Sort - Multiple Solutions + One Liners | domthedeveloper | 0 | 40 | sort characters by frequency | 451 | 0.686 | Medium | 8,021 |
https://leetcode.com/problems/sort-characters-by-frequency/discuss/1929605/Python-Counter-or-Heap-or-Bucket-Sort-Multiple-Solutions-%2B-One-Liners | class Solution:
def frequencySort(self, s):
counter = Counter(s)
heap = [(-f, c) for c, f in counter.items()]
heapify(heap)
results = [heappop(heap) for i in range(len(heap))]
ans = "".join(c*(-f) for f, c in results)
return ans | sort-characters-by-frequency | Python - Counter | Heap | Bucket Sort - Multiple Solutions + One Liners | domthedeveloper | 0 | 40 | sort characters by frequency | 451 | 0.686 | Medium | 8,022 |
https://leetcode.com/problems/sort-characters-by-frequency/discuss/1929605/Python-Counter-or-Heap-or-Bucket-Sort-Multiple-Solutions-%2B-One-Liners | class Solution:
def frequencySort(self, s):
heapify(h := [(-f, c) for c, f in Counter(s).items()])
return "".join(c*-f for f,c in [heappop(h) for i in range(len(h))]) | sort-characters-by-frequency | Python - Counter | Heap | Bucket Sort - Multiple Solutions + One Liners | domthedeveloper | 0 | 40 | sort characters by frequency | 451 | 0.686 | Medium | 8,023 |
https://leetcode.com/problems/sort-characters-by-frequency/discuss/1928654/Python-Two-Line-Heap-O(nlogk) | class Solution:
def frequencySort(self, s: str) -> str:
# calculate the freq
count = Counter(s)
# heap pop out the largest
return "".join(c*count[c] for c in heapq.nlargest(len(count),count.keys(),
count.get)) | sort-characters-by-frequency | Python Two Line Heap O(nlogk) | jlu56 | 0 | 28 | sort characters by frequency | 451 | 0.686 | Medium | 8,024 |
https://leetcode.com/problems/sort-characters-by-frequency/discuss/1878348/Python-one-line-solution-faster-than-88-memory-usage-less-than-84 | class Solution:
def frequencySort(self, s: str) -> str:
return ''.join([x[0] * x[1] for x in Counter(s).most_common()]) | sort-characters-by-frequency | Python one line solution faster than 88%, memory usage less than 84% | alishak1999 | 0 | 57 | sort characters by frequency | 451 | 0.686 | Medium | 8,025 |
https://leetcode.com/problems/sort-characters-by-frequency/discuss/1865363/Python-(Simple-Approach-and-Beginner-Friendly) | class Solution:
def frequencySort(self, s: str) -> str:
a = Counter(s)
b = ""
abc = sorted(a, reverse = True, key = a.get)
for i in abc:
for j in range(a[i]):
b+=i
return b | sort-characters-by-frequency | Python (Simple Approach and Beginner-Friendly) | vishvavariya | 0 | 64 | sort characters by frequency | 451 | 0.686 | Medium | 8,026 |
https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/discuss/1686588/Python3-COMBO-Explained | class Solution:
def findMinArrowShots(self, points: List[List[int]]) -> int:
pts = sorted(points, key=lambda el: el[1])
res, combo = 0, (float("-inf"), float("-inf"))
for start, end in pts:
if start <= combo[1]: # overlaps?
combo = (max(combo[0], start), min(combo[1], end))
else:
combo = (start, end)
res += 1
return res | minimum-number-of-arrows-to-burst-balloons | ✔️ [Python3] ➵ COMBO 🌸, Explained | artod | 9 | 290 | minimum number of arrows to burst balloons | 452 | 0.532 | Medium | 8,027 |
https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/discuss/1686486/Python-or-VISUAL-or-Greedy-or-Simple-or-O(NLogN)-Time-or-O(1)-Space | class Solution:
def findMinArrowShots(self, points):
n = len(points)
if n<2:
return n
#sort by start and end point
START, END = 0,1
points.sort(key=lambda i: (i[START],i[END]) )
prev, cur = points[0], None
darts = 0
for i in range(1, n):
cur = points[i]
if cur[START] <= prev[END]:
#overlap, wait for more overlap to throw dart
prev = [cur[START], min(cur[END],prev[END])]
else:
#no overlap, throw dart at previous
darts += 1
prev = cur
#pop the last balloon and return
return darts+1 | minimum-number-of-arrows-to-burst-balloons | [Python] | [VISUAL] | Greedy | Simple | O(NLogN) Time | O(1) Space | matthewlkey | 8 | 628 | minimum number of arrows to burst balloons | 452 | 0.532 | Medium | 8,028 |
https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/discuss/1725242/Python-3-greedy-sorting-solution-O(nlogn)-time-O(n)-space | class Solution:
def findMinArrowShots(self, points: List[List[int]]) -> int:
points.sort()
cur_end = -math.inf
res = 0
for start, end in points:
if cur_end >= start:
cur_end = min(cur_end, end)
else:
res += 1
cur_end = end
return res | minimum-number-of-arrows-to-burst-balloons | Python 3, greedy sorting solution, O(nlogn) time, O(n) space | dereky4 | 1 | 99 | minimum number of arrows to burst balloons | 452 | 0.532 | Medium | 8,029 |
https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/discuss/1686747/Python3-Solution-or-Array-Sorting-and-Greedy-or-Easy-to-understand | class Solution:
def findMinArrowShots(self, points: List[List[int]]) -> int:
points.sort(key = lambda x: x[0]) # sorting so that you always get the next closest start point of balloons
end = float('inf') # This end constraint will ensure that the overlapping balloon can be hit with single arrow
res = 1 # I initialized res with 1 since we are given in constraint that min length of points is 1 so 1 arrow would always be the base case
for p in points: # Traversing the points array once
if p[0] <= end: # p[0] means the starting point. If this is less than or equal to our end constraint, that means that this ballon can be shot with the current arrow.
end = min(end, p[1]) # The end constraint for the current arrow would always be the min of all the end points we have encountered for the current arrow
else:
end = p[1] # If the start is after the end constraint, The iteration for the current arrow is over.
res += 1 # We can say here, we released our current arrow and loaded a new one
return res
``` | minimum-number-of-arrows-to-burst-balloons | [Python3] Solution | Array Sorting and Greedy | Easy to understand | nandhakiran366 | 1 | 31 | minimum number of arrows to burst balloons | 452 | 0.532 | Medium | 8,030 |
https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/discuss/1686289/Python-3-Brute-Force-sorting-and-Line-Sweep | class Solution:
def findMinArrowShots(self, points: List[List[int]]) -> int:
# Line Sweep
points = sorted(points, key = lambda x:x[0])
start = points[0][0]
end = points[0][1]
ans = len(points)
for i in range(1,len(points)):
if points[i][0] > end:
start = points[i][0]
end = points[i][1]
else:
start = points[i][0]
ans -= 1
if end > points[i][1]:
end = points[i][1]
return ans | minimum-number-of-arrows-to-burst-balloons | Python 3 Brute Force, sorting and Line Sweep | AndrewHou | 1 | 164 | minimum number of arrows to burst balloons | 452 | 0.532 | Medium | 8,031 |
https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/discuss/2827520/Activity-Selection-Problem-(Greedy)-Python | class Solution:
def findMinArrowShots(self, points: List[List[int]]) -> int:
a=[]
b=[]
d=[]
e=0
f=1
for i,j in points:
a.append(i)
b.append(j)
c=list(zip(b,a))
c.sort()
for k in c:
d.append(list(reversed(k)))
print(d)
for i in range(1,len(d)):
if d[e][1]<d[i][0]:
print(d[e][1],end=" ")
print(d[i][0])
f+=1
e=i
else:
continue
return f | minimum-number-of-arrows-to-burst-balloons | Activity Selection Problem (Greedy) [Python🐍] | Saransh_MG | 0 | 3 | minimum number of arrows to burst balloons | 452 | 0.532 | Medium | 8,032 |
https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/discuss/2786684/Python-solution-easy-to-understand | class Solution:
def findMinArrowShots(self, points: List[List[int]]) -> int:
points.sort(key=lambda p: p[1])
count = 0
prev = points[0][1]
count = 1
print(points)
for i in range(1,len(points)):
if points[i][0]<=prev:
continue
else:
count+=1
prev = points[i][1]
return count | minimum-number-of-arrows-to-burst-balloons | Python solution easy to understand | adla2424 | 0 | 7 | minimum number of arrows to burst balloons | 452 | 0.532 | Medium | 8,033 |
https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/discuss/2776426/python | class Solution:
def findMinArrowShots(self, intervals: List[List[int]]) -> int:
if len(intervals) == 1:
return 1
#sort it based one the first value
intervals = sorted(intervals, key=lambda x:x[0])
count = 1
start = intervals[0][0]
end = intervals[0][1]
#the main logic is when you find a point that has start value greater than your considered/present array value
#that is the time to reset your values
# for example: In [[1,6],[2,8],[7,12],[10,16]]
#6 is the lowest end value of [1,6] and [2,8], so you can blast within that range
#so reset when you see start time 7
for i in range(1, len(intervals)):
if intervals[i][0] > end:
count += 1
start = intervals[i][0]
end = intervals[i][1]
elif intervals[i][1] < end:
end = intervals[i][1]
return count | minimum-number-of-arrows-to-burst-balloons | python | shivanigowda | 0 | 4 | minimum number of arrows to burst balloons | 452 | 0.532 | Medium | 8,034 |
https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/discuss/2771182/Simple-merge-interval-application-python | class Solution:
def findMinArrowShots(self, points: List[List[int]]) -> int:
# T(c)=O(nlogn)*O(n)
# S(c)=O(n)
# Just advanced version of merge-interval problem
points.sort()
res=[]
count=0
print(points)
for i in range(len(points)):
if len(res)!=0 and res[-1][1]>=points[i][0]:
res[-1][1]=min(res[-1][1],points[i][1])
else:
count+=1
res.append(points[i])
return count | minimum-number-of-arrows-to-burst-balloons | Simple merge interval application, python | Aniket_liar07 | 0 | 2 | minimum number of arrows to burst balloons | 452 | 0.532 | Medium | 8,035 |
https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/discuss/2724778/Python-By-merging-interval-using-Stack-with-O(N)-runtime | class Solution(object):
def findMinArrowShots(self, points):
"""
:type points: List[List[int]]
:rtype: int
"""
points.sort()
res = [points[0]]
for i in range(1, len(points)):
prev = res.pop()
cur = points[i]
xleft, xright = prev[0], prev[1]
yleft, yright = cur[0], cur[1]
if xright < yleft:
res.append(prev)
res.append(cur)
else:
xcur = max(xleft, yleft)
ycur = min(xright, yright)
new = (xcur, ycur)
res.append(new)
return len(res) ``` | minimum-number-of-arrows-to-burst-balloons | [Python] By merging interval using Stack with O(N) runtime | waynewang1119 | 0 | 13 | minimum number of arrows to burst balloons | 452 | 0.532 | Medium | 8,036 |
https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/discuss/2559240/Python-Greedy-Solution | class Solution:
def findMinArrowShots(self, points: List[List[int]]) -> int:
# sort the points in increasing order of its start time
points = sorted(points)
'''
Intuition behind this problem is that if next intervals is in intersection with current interval,
the commonpoint will be the minimum of end of all the interval, so for all such group of intervals which
will intersect, there is single arrow required to hit at the commonpoint of all the balloons to burst
group of baloons which intersect
'''
commonPointOfIntersectedIntervals = points[0][1]
ans = 1
for i in range(1,len(points)):
start = points[i][0]
end = points[i][1]
if start <= commonPointOfIntersectedIntervals:
commonPointOfIntersectedIntervals = min(commonPointOfIntersectedIntervals, end)
else:
ans += 1
commonPointOfIntersectedIntervals = end
return ans | minimum-number-of-arrows-to-burst-balloons | Python Greedy Solution | DietCoke777 | 0 | 49 | minimum number of arrows to burst balloons | 452 | 0.532 | Medium | 8,037 |
https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/discuss/2512653/python-greedy-solution | class Solution:
def findMinArrowShots(self, points: List[List[int]]) -> int:
points.sort()
mm,mx,n=points[0][0],points[0][1],len(points)
res=0
for i in range(1,n):
if points[i][0] in range(mm,mx+1) or points[i][1] in range(mm,mx+1):
mm=max(points[i][0],mm)
mx=min(points[i][1],mx)
else:
mm,mx=points[i][0],points[i][1]
res+=1
res+=1
return res | minimum-number-of-arrows-to-burst-balloons | python greedy solution | benon | 0 | 23 | minimum number of arrows to burst balloons | 452 | 0.532 | Medium | 8,038 |
https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/discuss/2505643/Fast-python3-solution-with-complexity-analysis | class Solution:
# O(nlogn) time,
# O(1) space,
# Approach: sorting, greedy
def findMinArrowShots(self, points:List[List[int]]) -> int:
n = len(points)
points.sort()
arrows = 0
i = 0
while i < n:
arrows +=1
curr = points[i]
nxt = i+1
hi = curr[1]
while nxt < n and points[nxt][0] <= hi:
hi = min(hi, points[nxt][1])
nxt +=1
i = nxt
return arrows | minimum-number-of-arrows-to-burst-balloons | Fast python3 solution with complexity analysis | destifo | 0 | 13 | minimum number of arrows to burst balloons | 452 | 0.532 | Medium | 8,039 |
https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/discuss/2338069/Python3-and-Java-or-Greedy-or-Activity-Solution-Problem-Logic-or-O(n-log-n) | class Solution:
def findMinArrowShots(self, points: List[List[int]]) -> int:
# Sort intervals by ending time
points.sort(key=lambda x:x[1])
# Keep track of previous interval
previous = points[0]
# Keep track the # of intervals (first interval is already counted)
balloons = 1
# Loop through interval (balloons) starting from the 2nd element as the 1st element is already counted
for i in range(1, len(points)):
# If ending time of previous interval if less than the starting time of current interval
if previous[-1] < points[i][0]:
# If the above condition is true, include that interval
balloons += 1
# Update the previous interval
previous = points[i]
return balloons | minimum-number-of-arrows-to-burst-balloons | Python3 & Java | Greedy | Activity Solution Problem Logic | O(n log n) | khaydaraliev99 | 0 | 27 | minimum number of arrows to burst balloons | 452 | 0.532 | Medium | 8,040 |
https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/discuss/2271261/Python-Simplest-Solution-With-Explanation-or-Beg-to-adv-or-Sorting-or-Interval | class Solution:
def findMinArrowShots(self, points: List[List[int]]) -> int:
if len(points) == 0: # we are checking if there is no element in the list
return 0 # then return 0
points.sort() # as we might have unsorted list, to make it simple we are sorting it.
end = points[0][1] # We must be having some values to compare/ to check if we are having a overlap or not. Usually we take start = list[0][0] & end = [0][1].
counter = 1 # for counting the number of arrows required, taking its value as 1 bcz list must have at least one element in it as we checked that earlier.
for i in range(1, len(points)):
if points[i][0] > end: # checking for overlapping and if its true, implies there is no overlapping.
end = points[i][1] # updating the end
counter += 1 # increasing the arrow count
else:
end = min(end, points[i][1])# updating end, taking min to avoid overlapping
return counter | minimum-number-of-arrows-to-burst-balloons | Python Simplest Solution With Explanation | Beg to adv | Sorting | Interval | rlakshay14 | 0 | 13 | minimum number of arrows to burst balloons | 452 | 0.532 | Medium | 8,041 |
https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/discuss/1896829/Python-easy-to-read-and-understand-or-sorting | class Solution:
def findMinArrowShots(self, points: List[List[int]]) -> int:
points.sort(key=lambda x:x[1])
ans, curr = 1, points[0]
for i in range(len(points)):
if points[i][0] > curr[1]:
ans += 1
curr = points[i]
return ans | minimum-number-of-arrows-to-burst-balloons | Python easy to read and understand | sorting | sanial2001 | 0 | 41 | minimum number of arrows to burst balloons | 452 | 0.532 | Medium | 8,042 |
https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/discuss/1689089/Python-3-oror-Greedy-oror-Easy-understanding-oror-Self-understandable | class Solution:
def findMinArrowShots(self, points: List[List[int]]) -> int:
points.sort(key=lambda x:x[1])
arrows=1
start,end=points[0]
for x,y in points[1:]:
if end>=x and end<=y:
continue
end=y
arrows+=1
return arrows | minimum-number-of-arrows-to-burst-balloons | Python 3 || Greedy || Easy-understanding || Self-understandable | bug_buster | 0 | 18 | minimum number of arrows to burst balloons | 452 | 0.532 | Medium | 8,043 |
https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/discuss/1687890/Python3-Solution | class Solution:
def findMinArrowShots(self, points: List[List[int]]) -> int:
points.sort(key=lambda z: z[0])
endpoint = points[0][1]
arrows = 1
for index in range(1, len(points)):
endpoint = min(endpoint, points[index][1])
if points[index][0] <= endpoint <= points[index][1]:
continue
else:
arrows += 1
endpoint = points[index][1]
return arrows | minimum-number-of-arrows-to-burst-balloons | Python3 Solution | nomanaasif9 | 0 | 19 | minimum number of arrows to burst balloons | 452 | 0.532 | Medium | 8,044 |
https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/discuss/1686890/Python-O(nlog(n))-Solution-Clean-and-Easy | class Solution:
def findMinArrowShots(self, points: List[List[int]]) -> int:
points.sort()
best_y = -float('inf')
ans = 0
for (x,y) in points:
if best_y>=x:
best_y = min(best_y, y)
else:
ans+=1
best_y = y
return ans | minimum-number-of-arrows-to-burst-balloons | Python O(nlog(n)) Solution - Clean and Easy | eastwoodsamuel4 | 0 | 23 | minimum number of arrows to burst balloons | 452 | 0.532 | Medium | 8,045 |
https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/discuss/1686684/Simple.-One-pass-through-the-sorted-list. | class Solution:
def findMinArrowShots(self, points: List[List[int]]) -> int:
points.sort()
pend = points[0][1]
ans = 1 # last shoot
for p in points:
if p[0] > pend:
ans += 1
pend = p[1]
else:
pend = min(pend, p[1])
return ans | minimum-number-of-arrows-to-burst-balloons | Simple. One pass through the sorted list. | MihailP | 0 | 18 | minimum number of arrows to burst balloons | 452 | 0.532 | Medium | 8,046 |
https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/discuss/1686669/PYTHON-3or-Intuitive-or-O(N)-or-O(1)-or-Beats-99.1-or | class Solution:
def findMinArrowShots(self, points: List[List[int]]) -> int:
points.sort()
i=1
while i<len(points):
if points[i-1][0]<=points[i][0]<=points[i-1][1]:
points[i][0]=max(points[i][0],points[i-1][0])
points[i][1]=min(points[i][1],points[i-1][1])
del points[i-1]
i-=1
i+=1
return len(points) | minimum-number-of-arrows-to-burst-balloons | PYTHON 3| Intuitive | O(N) | O(1) | Beats 99.1% | | saa_73 | 0 | 17 | minimum number of arrows to burst balloons | 452 | 0.532 | Medium | 8,047 |
https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/discuss/1686342/Python-3-O(n-log-n)-In-place-Explained | class Solution:
def findMinArrowShots(self, points: List[List[int]]) -> int:
points.sort()
n = len(points)
if n == 1:
return 1
i = 0
while (i < len(points)-1):
x1, y1 = points[i]
x2, y2 = points[i+1]
mx, my = ( max(x1, x2), min(y1, y2))
if mx <= my:
points[i+1] = (mx,my)
del points[i]
else:
i += 1
return len(points) | minimum-number-of-arrows-to-burst-balloons | 🤠[Python 3] O(n log n) In-place Explained | letyrodri | 0 | 10 | minimum number of arrows to burst balloons | 452 | 0.532 | Medium | 8,048 |
https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/discuss/932014/python3-simple-intervals-merge | class Solution:
def findMinArrowShots(self, points: List[List[int]]) -> int:
if not points:
return 0
points.sort(key = lambda x:x[0])
start, end = points[0]
res = []
for i in range(1, len(points)):
if points[i][0] <= end:
end = min(end, points[i][1])
else:
res.append([start, end])
start, end = points[i]
res.append([start, end])
return len(res) | minimum-number-of-arrows-to-burst-balloons | python3 simple intervals merge | ermolushka2 | 0 | 65 | minimum number of arrows to burst balloons | 452 | 0.532 | Medium | 8,049 |
https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/discuss/888383/Python3-dp-O(NlogN)-with-explanation | class Solution:
def findMinArrowShots(self, points: List[List[int]]) -> int:
n = len(points)
if n == 0:
return 0
points.sort()
dp = [0 for _ in range(n)]
for i in range(n):
if i == 0:
dp[i] = 1
end = points[i][1]
continue
if points[i][0] <= end:
dp[i] = dp[i - 1]
end = min(end, points[i][1])
else:
dp[i] = dp[i - 1] + 1
end = points[i][1]
return dp[-1] | minimum-number-of-arrows-to-burst-balloons | Python3 dp O(NlogN) with explanation | ethuoaiesec | 0 | 30 | minimum number of arrows to burst balloons | 452 | 0.532 | Medium | 8,050 |
https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/discuss/848174/Python3-greedy | class Solution:
def findMinArrowShots(self, points: List[List[int]]) -> int:
ans, prev = 0, -inf
for x, y in sorted(points):
if prev < x:
ans += 1
prev = y
else: prev = min(prev, y)
return ans | minimum-number-of-arrows-to-burst-balloons | [Python3] greedy | ye15 | 0 | 53 | minimum number of arrows to burst balloons | 452 | 0.532 | Medium | 8,051 |
https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/discuss/848174/Python3-greedy | class Solution:
def findMinArrowShots(self, points: List[List[int]]) -> int:
ans, prev = 0, -inf
for x, y in sorted(points, key=lambda x: x[1]):
if prev < x:
ans += 1
prev = y
return ans | minimum-number-of-arrows-to-burst-balloons | [Python3] greedy | ye15 | 0 | 53 | minimum number of arrows to burst balloons | 452 | 0.532 | Medium | 8,052 |
https://leetcode.com/problems/minimum-moves-to-equal-array-elements/discuss/1909521/1-line-solution-beats-98-O(N)-time-and-96-O(1)-space-easy-to-understand | class Solution:
def minMoves(self, nums: List[int]) -> int:
return sum(nums) - (len(nums) * min(nums)) | minimum-moves-to-equal-array-elements | 1 line solution; beats 98% O(N) time and 96% O(1) space; easy to understand | sahajamatya | 10 | 461 | minimum moves to equal array elements | 453 | 0.557 | Medium | 8,053 |
https://leetcode.com/problems/minimum-moves-to-equal-array-elements/discuss/1621347/Python-2-Short-and-Simple-Approaches-with-Explanation | class Solution:
def minMoves(self, nums: List[int]) -> int:
nums.sort(reverse=True)
return sum((nums[i-1]-nums[i])*i for i in range(1, len(nums))) | minimum-moves-to-equal-array-elements | [Python] 2 Short and Simple Approaches with Explanation | zayne-siew | 10 | 767 | minimum moves to equal array elements | 453 | 0.557 | Medium | 8,054 |
https://leetcode.com/problems/minimum-moves-to-equal-array-elements/discuss/1621347/Python-2-Short-and-Simple-Approaches-with-Explanation | class Solution:
def minMoves(self, nums: List[int]) -> int:
_min, _sum = min(nums), 0
for num in nums:
_sum += num-_min # for num->_min, -1 per move takes (num-_min) moves
return _sum | minimum-moves-to-equal-array-elements | [Python] 2 Short and Simple Approaches with Explanation | zayne-siew | 10 | 767 | minimum moves to equal array elements | 453 | 0.557 | Medium | 8,055 |
https://leetcode.com/problems/minimum-moves-to-equal-array-elements/discuss/1621347/Python-2-Short-and-Simple-Approaches-with-Explanation | class Solution:
def minMoves(self, nums: List[int]) -> int:
return sum(nums)-min(nums)*len(nums) | minimum-moves-to-equal-array-elements | [Python] 2 Short and Simple Approaches with Explanation | zayne-siew | 10 | 767 | minimum moves to equal array elements | 453 | 0.557 | Medium | 8,056 |
https://leetcode.com/problems/minimum-moves-to-equal-array-elements/discuss/1621347/Python-2-Short-and-Simple-Approaches-with-Explanation | class Solution:
def minMoves(self, nums: List[int]) -> int:
_sum, _min = 0, float('inf')
for num in nums:
_sum += num
_min = _min if _min < num else num
return _sum-_min*len(nums) | minimum-moves-to-equal-array-elements | [Python] 2 Short and Simple Approaches with Explanation | zayne-siew | 10 | 767 | minimum moves to equal array elements | 453 | 0.557 | Medium | 8,057 |
https://leetcode.com/problems/minimum-moves-to-equal-array-elements/discuss/881567/Simple-solution-with-description-of-the-intuitive-approach | class Solution:
def minMoves(self, nums: List[int]) -> int:
# If we observe some sample arrays we will see that the minimum number has to equal the maximum number so that they are equal
# However during this time (n - 2) elements will also increase by 1 for each step where n is the length of the array.
# Example 1 :- [1, 2, 3]
# For 1 to increase to 3 it will take exactly 2 steps but during these 2 steps 2 will also increase by 2 taking it to 4. Thus we would have to again take the two resulting 3s and make them into 4s in the next step.
# Example 2:- [2, 2, 4]
# 1st iteration : [3, 3, 4]
# 2nd iteration : [4, 4, 4]
# Let us now see the pattern. If we do abs(4 - 2 ) + abs (2 - 2) + abs (2 - 2) we get 2.
# For [1, 2, 3] its abs(1 - 1) + abs(1 - 2) + abs(1 - 3) = 3
# After the pattern is decoded, the implementation becomes simple.
steps = 0
min_num = min(nums)
for num in nums:
steps += abs(min_num - num)
return steps | minimum-moves-to-equal-array-elements | Simple solution with description of the intuitive approach | rassel | 6 | 454 | minimum moves to equal array elements | 453 | 0.557 | Medium | 8,058 |
https://leetcode.com/problems/minimum-moves-to-equal-array-elements/discuss/1539251/Intuitive-approach-with-Python-example | class Solution:
def minMoves(self, nums: List[int]) -> int:
total = 0
min_num = None
for x in nums:
if min_num == None or x < min_num:
min_num = x
total += x
return total - min_num * len(nums) | minimum-moves-to-equal-array-elements | Intuitive approach with Python example | supersam710 | 3 | 370 | minimum moves to equal array elements | 453 | 0.557 | Medium | 8,059 |
https://leetcode.com/problems/minimum-moves-to-equal-array-elements/discuss/466067/One-step-pure-math-Python3-w-explanation | class Solution:
def minMoves(self, nums: List[int]) -> int:
'''
min of nums needs x moves to get final number
# x moves add x(n-1) to the initial sum (n is the len)
# since every number is the same, the final sum is n * (min+x)
'''
return sum(nums) - len(nums) * min(nums) | minimum-moves-to-equal-array-elements | One step pure math Python3 w/ explanation | SilverCHN | 3 | 336 | minimum moves to equal array elements | 453 | 0.557 | Medium | 8,060 |
https://leetcode.com/problems/minimum-moves-to-equal-array-elements/discuss/2350796/Python3-Detailed-Explanation-in-comments-O(N)-O(1) | class Solution:
def minMoves(self, nums: List[int]) -> int:
# Approach:
# we want to make all the elements equal ; question does not
# say "to which element" they should be made equal so that means
# we can "choose" to what element they all should finally reach
# Choose the minimum element of the array as a starting point
# because the statement says -
# we can increment all elements except one element
# which can be interpreted as "decreasing that one element" in each
# move to make all the elements equal
# for eg:
# [1,2,3] -> [1,1,3] -> [1,1,2] -> [1,1,1]
# at each step, we decrement one element towards the smallest
_min = min(nums)
ans = 0
# if all elements are already equal; ans = 0
if all(ele == nums[0] for ele in nums):
return 0
else:
for ele in nums:
ans = ans + (ele - _min)
# ele - _min because it takes ele - _min steps to make ele
# equal to the minimum element
return ans | minimum-moves-to-equal-array-elements | Python3 Detailed Explanation in comments O(N), O(1) | jinwooo | 1 | 107 | minimum moves to equal array elements | 453 | 0.557 | Medium | 8,061 |
https://leetcode.com/problems/minimum-moves-to-equal-array-elements/discuss/1404050/Python3-With-Fully-Explanations!!!!!!! | class Solution:
def minMoves(self, nums: List[int]) -> int:
return sum(nums) - len(nums) * min(nums)
#####intuition########
# Original Sum of nums: sum(nums)
# The length of nums: n
# The Minimum steps of moves: x
# The increasement of each step: n-1
# The Sum after Move: sum(nums) + x*(n-1)
####
# The minimum number: min(nums)
# The final number after x moves: min(nums) + x
# The Sum finally: (min(nums) + x) * n
#So 'The Sum after Move' = 'The Sum finally'
#We get:
x*(n-1) + sum(nums) = (min(nums) + x) * n
#After simple calculation:
x = sum(nums) - n * min(nums)
#Hope this could help you! | minimum-moves-to-equal-array-elements | Python3 With Fully Explanations!!!!!!! | yjin232 | 1 | 251 | minimum moves to equal array elements | 453 | 0.557 | Medium | 8,062 |
https://leetcode.com/problems/minimum-moves-to-equal-array-elements/discuss/2217556/Python-or-Easy-solution-with-comments-or-97-faster-than-other-python-submissions | class Solution:
def minMoves(self, nums: List[int]) -> int:
# finding min element in array takes O(n)
Min = min(nums)
moves = 0
# now we need to find the difference between each elements with the min ele and add all diff
# will we the required result
for n in nums:
moves += abs(Min - n)
return moves | minimum-moves-to-equal-array-elements | Python | Easy solution with comments | 97% faster than other python submissions | __Asrar | 0 | 92 | minimum moves to equal array elements | 453 | 0.557 | Medium | 8,063 |
https://leetcode.com/problems/minimum-moves-to-equal-array-elements/discuss/1767124/Python-3-two-lines-O(n)-time-O(1)-space | class Solution:
def minMoves(self, nums: List[int]) -> int:
minNum = min(nums)
return sum(num - minNum for num in nums) | minimum-moves-to-equal-array-elements | Python 3, two lines, O(n) time, O(1) space | dereky4 | 0 | 336 | minimum moves to equal array elements | 453 | 0.557 | Medium | 8,064 |
https://leetcode.com/problems/minimum-moves-to-equal-array-elements/discuss/1587838/Python-Easy-Solution-or-Optimal-Approach | class Solution:
def minMoves(self, nums: List[int]) -> int:
ele = min(nums)
sum = 0
for num in nums:
sum += num-ele
return sum | minimum-moves-to-equal-array-elements | Python Easy Solution | Optimal Approach | leet_satyam | 0 | 394 | minimum moves to equal array elements | 453 | 0.557 | Medium | 8,065 |
https://leetcode.com/problems/minimum-moves-to-equal-array-elements/discuss/1576416/Python3-or-Difference-of-all-Element-with-min-Element. | class Solution:
def minMoves(self, nums: List[int]) -> int:
currMin=min(nums)
ans=0
for i in nums:
ans+=i-currMin
return ans | minimum-moves-to-equal-array-elements | [Python3] | Difference of all Element with min Element. | swapnilsingh421 | 0 | 176 | minimum moves to equal array elements | 453 | 0.557 | Medium | 8,066 |
https://leetcode.com/problems/minimum-moves-to-equal-array-elements/discuss/401235/Python-Concise-Solution | class Solution:
def minMoves(self, nums: List[int]) -> int:
t = sum(nums)
n = len(nums)
m = min(nums)
return t-n*m | minimum-moves-to-equal-array-elements | Python Concise Solution | saffi | 0 | 495 | minimum moves to equal array elements | 453 | 0.557 | Medium | 8,067 |
https://leetcode.com/problems/minimum-moves-to-equal-array-elements/discuss/1217883/Python3-simple-one-liner-solution-beats-94-users | class Solution:
def minMoves(self, nums: List[int]) -> int:
return sum(nums) - min(nums)*len(nums) | minimum-moves-to-equal-array-elements | Python3 simple one-liner solution beats 94% users | EklavyaJoshi | -1 | 82 | minimum moves to equal array elements | 453 | 0.557 | Medium | 8,068 |
https://leetcode.com/problems/4sum-ii/discuss/1741072/Python-Clean-and-concise-or-Detail-explanation-or-One-linear | class Solution:
def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
# hashmap and final result count
nums12, res = defaultdict(int), 0
# storing all possible combinations of sum
for i in nums1:
for j in nums2:
nums12[i+j] += 1
# iterating the left out two array to find negation of same value
for k in nums3:
for l in nums4:
res += nums12[-(k+l)]
return res | 4sum-ii | [Python] Clean and concise | Detail explanation | One linear | sidheshwar_s | 19 | 939 | 4sum ii | 454 | 0.573 | Medium | 8,069 |
https://leetcode.com/problems/4sum-ii/discuss/1741072/Python-Clean-and-concise-or-Detail-explanation-or-One-linear | class Solution:
def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
return sum(counts[-(c + d)] for counts in [Counter(a + b for a in nums1 for b in nums2)] for c in nums3 for d in nums4) | 4sum-ii | [Python] Clean and concise | Detail explanation | One linear | sidheshwar_s | 19 | 939 | 4sum ii | 454 | 0.573 | Medium | 8,070 |
https://leetcode.com/problems/4sum-ii/discuss/1742209/Python-3-(500ms)-or-N2-Approach-or-Easy-to-Understand | class Solution:
def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
ht = defaultdict(int)
for n1 in nums1:
for n2 in nums2:
ht[n1 + n2] += 1
ans = 0
c=0
for n3 in nums3:
for n4 in nums4:
c=ht[-n3 - n4]
ans +=c
return ans | 4sum-ii | Python 3 (500ms) | N^2 Approach | Easy to Understand | MrShobhit | 3 | 111 | 4sum ii | 454 | 0.573 | Medium | 8,071 |
https://leetcode.com/problems/4sum-ii/discuss/2056287/Easy-O(n2)-python-solution-with-explanation | class Solution:
def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
n=len(nums1)
res=0
d1=defaultdict(int)
d2=defaultdict(int)
for i in range(n):
for j in range(n):
d1[nums1[i]+nums2[j]]+=1
for i in range(n):
for j in range(n):
d2[nums3[i]+nums4[j]]+=1
for key in d1:
res+=(d1[key]*d2[-key])
return res
# Please upvote if you find this solution useful :) | 4sum-ii | Easy O(n^2) python solution with explanation | pbhuvaneshwar | 1 | 156 | 4sum ii | 454 | 0.573 | Medium | 8,072 |
https://leetcode.com/problems/4sum-ii/discuss/1742391/Python-oror-o(n**2)-Solution-oror-93-Fast-oror-using-dictionary | class Solution:
def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
d = {}
res = 0
for i in nums1:
for j in nums2:
temp = i + j
try:
d[temp] += 1
except:
d[temp] = 1
for k in nums3:
for l in nums4:
temp = -(k + l)
try:
res += d[temp]
except:
pass
return res | 4sum-ii | Python || o(n**2) Solution || 93% Fast || using dictionary | naveenrathore | 1 | 48 | 4sum ii | 454 | 0.573 | Medium | 8,073 |
https://leetcode.com/problems/4sum-ii/discuss/2762694/beats-96 | class Solution:
def fourSumCount(self, A: List[int], B: List[int], C: List[int], D: List[int]) -> int:
m = {}
ans = 0
for i in range(0,len(A)):
x = A[i]
for j in range(0,len(B)):
y = B[j]
if(x+y not in m):
m[x+y] = 0
m[x+y]+=1
for i in range(0,len(C)):
x = C[i]
for j in range(0,len(D)):
y = D[j]
target = -(x+y)
if(target in m):
ans+=m[target]
return ans | 4sum-ii | beats 96% | sanjeevpathak | 0 | 3 | 4sum ii | 454 | 0.573 | Medium | 8,074 |
https://leetcode.com/problems/4sum-ii/discuss/2762664/using-dict()-easy-solution!! | class Solution:
def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
h = dict()
for a in nums1:
for b in nums2:
p = -(a+b)
if p in h:
h[p]+=1
else:
h[p]=1
count=0
for c in nums3:
for d in nums4:
p = c+d
if p in h:
count+=h[p]
return count | 4sum-ii | using dict() easy solution!! | sanjeevpathak | 0 | 1 | 4sum ii | 454 | 0.573 | Medium | 8,075 |
https://leetcode.com/problems/4sum-ii/discuss/2491654/Python3-solution%3A-faster-than-most-submissions | class Solution:
def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
n1n2 = defaultdict(int)
for n1 in nums1:
for n2 in nums2:
n1n2[n1+n2] += 1
n3n4 = defaultdict(int)
for n3 in nums3:
for n4 in nums4:
n3n4[n3+n4] += 1
ans = 0
for s in n1n2:
ans += n1n2[s] * n3n4[-s]
return ans | 4sum-ii | ✔️ Python3 solution: faster than most submissions | explusar | 0 | 26 | 4sum ii | 454 | 0.573 | Medium | 8,076 |
https://leetcode.com/problems/4sum-ii/discuss/1984149/Python-easy-understand-O(n2)-solution-with-comment | class Solution:
def fourSumCount(self, num1: List[int], num2: List[int], num3: List[int], num4: List[int]) -> int:
res = 0
num1, num2, num3, num4 = Counter(num1), Counter(num2), Counter(num3), Counter(num4) # Using Counter to simplify duplicates
num12 = defaultdict(int) # num12 record: (sum of num1 and num2): times
for i in num1:
for j in num2:
num12[i+j] += num1[i] * num2[j]
for k in num3:
for l in num4:
target = -(k+l)
res += num12[target] * num3[k] * num4[l] # add the multi of the 4 nums' appear times to res
return res | 4sum-ii | Python easy-understand O(n^2) solution with comment | byroncharly3 | 0 | 97 | 4sum ii | 454 | 0.573 | Medium | 8,077 |
https://leetcode.com/problems/4sum-ii/discuss/1836165/Python-easy-to-read-and-understand-or-hashmap | class Solution:
def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
d = {}
ans = 0
for i in nums1:
for j in nums2:
d[(i+j)] = d.get((i+j), 0) + 1
for i in nums3:
for j in nums4:
ans += d.get(-(i+j), 0)
return ans | 4sum-ii | Python easy to read and understand | hashmap | sanial2001 | 0 | 96 | 4sum ii | 454 | 0.573 | Medium | 8,078 |
https://leetcode.com/problems/4sum-ii/discuss/1798996/Easy-to-Understand-Python3-Solution-O(N2) | class Solution:
def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
first_half = [n1+n2 for n1 in nums1 for n2 in nums2]
second_half = [n3+n4 for n3 in nums3 for n4 in nums4]
second_half_map = {}
for part_2 in second_half:
second_half_map[part_2] = second_half_map.get(part_2, 0) + 1
count = 0
for part_1 in first_half:
count += second_half_map.get(-part_1, 0)
return count | 4sum-ii | Easy to Understand Python3 Solution - O(N^2) | schedutron | 0 | 34 | 4sum ii | 454 | 0.573 | Medium | 8,079 |
https://leetcode.com/problems/4sum-ii/discuss/1743596/Python-2-easy-solutions-or-2-liner-and-detailed | class Solution:
def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
n=len(nums1)
dict_sum={}
cnt=0
for i in nums1:
for j in nums2:
temp=i+j
dict_sum[temp]=dict_sum.get(temp,0)+1
for k in nums3:
for l in nums4:
temp=(k+l)*(-1)
cnt+= dict_sum.get(temp,0)
return cnt | 4sum-ii | Python 2 easy solutions | 2 liner and detailed | shandilayasujay | 0 | 50 | 4sum ii | 454 | 0.573 | Medium | 8,080 |
https://leetcode.com/problems/4sum-ii/discuss/1743596/Python-2-easy-solutions-or-2-liner-and-detailed | class Solution:
def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
cntr= Counter([(i+j) for i in nums1 for j in nums2])
return(sum([cntr.get(-(k+l),0) for k in nums3 for l in nums4])) | 4sum-ii | Python 2 easy solutions | 2 liner and detailed | shandilayasujay | 0 | 50 | 4sum ii | 454 | 0.573 | Medium | 8,081 |
https://leetcode.com/problems/4sum-ii/discuss/1742560/Python-Solution-4-Sum-II | class Solution:
def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
def create_dict(arr1,arr2):
d = {}
for i in arr1:
for j in arr2:
val = i+j
if val not in d:
d[val] = 1
else:
d[val] += 1
return d
count = 0
d1 = create_dict(nums1,nums2)
d2 = create_dict(nums3,nums4)
for key in d1.keys():
rev_key = -key
if rev_key in d2:
count = count + (d1[key]*d2[rev_key])
del d2[rev_key]
return count | 4sum-ii | [Python Solution] - 4 Sum II | SaSha59 | 0 | 20 | 4sum ii | 454 | 0.573 | Medium | 8,082 |
https://leetcode.com/problems/4sum-ii/discuss/1742495/Python3-Solution-with-O(n2)-time-complexity | class Solution:
def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
d = collections.defaultdict(int)
for num3 in nums3:
for num4 in nums4:
d[num3 + num4] += 1
res = 0
for num1 in nums1:
for num2 in nums2:
if -num1 - num2 in d:
res += d[-num1 - num2]
return res | 4sum-ii | [Python3] Solution with O(n^2) time complexity | maosipov11 | 0 | 12 | 4sum ii | 454 | 0.573 | Medium | 8,083 |
https://leetcode.com/problems/4sum-ii/discuss/1742083/python-easy-solution | class Solution:
def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
ht = {}
count = 0
for i,item1 in enumerate(nums1):
for j , item2 in enumerate(nums2):
if item1+item2 in ht:
ht[item1+item2].append([i,j])
else:
ht[item1 + item2] = [[i,j]]
for i,item1 in enumerate(nums3):
for j , item2 in enumerate(nums4):
if -1*(item1+item2) in ht:
count+=len(ht[-1*(item1+item2)])
return count | 4sum-ii | python easy solution | abhiGamez | 0 | 81 | 4sum ii | 454 | 0.573 | Medium | 8,084 |
https://leetcode.com/problems/4sum-ii/discuss/1741673/Easiest-Python-Solution-Using-Dictionary | class Solution:
def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
d=defaultdict(int)
res=0
for i in nums1:
for j in nums2:
d[i+j]+=1
for k in nums3:
for l in nums4:
res+=d[-(k+l)]
return res | 4sum-ii | 📍Easiest Python Solution Using Dictionary | AdityaTrivedi88 | 0 | 14 | 4sum ii | 454 | 0.573 | Medium | 8,085 |
https://leetcode.com/problems/4sum-ii/discuss/1741408/Python-or-Time-Complexity-%3A-O(n2)-or-Space-Complexity-%3A-O(n%2Bm) | class Solution:
def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
set1 = dict()
for index1 in range(len(nums1)):
for index2 in range(len(nums2)):
if nums1[index1]+nums2[index2] not in set1:
set1[nums1[index1]+nums2[index2]] = 1
else:
set1[nums1[index1]+nums2[index2]] += 1
set2 = dict()
for index3 in range(len(nums3)):
for index4 in range(len(nums4)):
if nums3[index3]+nums4[index4] not in set2:
set2[nums3[index3]+nums4[index4]] = 1
else:
set2[nums3[index3]+nums4[index4]] += 1
ans = 0
for value, count in set1.items():
if -value in set2:
ans += set2[-value] * count
return ans | 4sum-ii | Python | Time Complexity : O(n^2) | Space Complexity : O(n+m) | Call-Me-AJ | 0 | 19 | 4sum ii | 454 | 0.573 | Medium | 8,086 |
https://leetcode.com/problems/4sum-ii/discuss/1741090/Python-3-oror-O(N2)-oror-2-line-solution | class Solution:
def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
d = Counter([i + j for i in nums1 for j in nums2])
return sum([d[-i-j] for i in nums3 for j in nums4]) | 4sum-ii | [Python 3] || O(N^2) || 2-line solution | BrijGwala | 0 | 16 | 4sum ii | 454 | 0.573 | Medium | 8,087 |
https://leetcode.com/problems/4sum-ii/discuss/1740929/Python-simple-to-understand-faster-than-99.45-less-than-98.30 | class Solution:
def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
ht = defaultdict(int)
for n1 in nums1:
for n2 in nums2:
ht[n1 + n2] += 1
ans = 0
for n3 in nums3:
for n4 in nums4:
ans += ht[-n3 - n4]
return ans | 4sum-ii | Python, simple to understand, faster than 99.45%, less than 98.30% | MihailP | 0 | 37 | 4sum ii | 454 | 0.573 | Medium | 8,088 |
https://leetcode.com/problems/4sum-ii/discuss/1740687/Python-Simple-Python-Solution-Using-Dictionary-!!-TWO-Approach | class Solution:
def fourSumCount(self, A: List[int], B: List[int], C: List[int], D: List[int]) -> int:
new1={}
for i in range(len(A)):
for j in range(len(B)):
t=A[i]+B[j]
if t not in new1:
new1[t]=1
else:
new1[t]+=1
ans=0
for i in range(len(C)):
for j in range(len(D)):
if -(C[i]+D[j]) in new1:
ans=ans+new1[-(C[i]+D[j])]
return ans | 4sum-ii | [ Python ] ✔✔ Simple Python Solution Using Dictionary !! TWO Approach 🔥🔥✌ | ASHOK_KUMAR_MEGHVANSHI | 0 | 53 | 4sum ii | 454 | 0.573 | Medium | 8,089 |
https://leetcode.com/problems/4sum-ii/discuss/1740687/Python-Simple-Python-Solution-Using-Dictionary-!!-TWO-Approach | class Solution:
def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
l1={}
for i in nums1:
for j in nums2:
s=i+j
if s not in l1:
l1[s]=1
else:
l1[s]=l1[s]+1
l2={}
for i in nums3:
for j in nums4:
s=i+j
if s not in l2:
l2[s]=1
else:
l2[s]=l2[s]+1
ans=0
for i in l1.keys():
if -i in l2.keys():
ans=ans+l1[i]*l2[-i]
return ans | 4sum-ii | [ Python ] ✔✔ Simple Python Solution Using Dictionary !! TWO Approach 🔥🔥✌ | ASHOK_KUMAR_MEGHVANSHI | 0 | 53 | 4sum ii | 454 | 0.573 | Medium | 8,090 |
https://leetcode.com/problems/4sum-ii/discuss/1659190/faster-than-98.99-of-Python3-oror-Easy-to-understand-oror-hashmap | class Solution:
def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
lookup = collections.defaultdict(int)
res = 0
for a in nums1:
for b in nums2:
lookup[a+b] += 1
for c in nums3:
for d in nums4:
res += lookup[-(c + d)]
return res | 4sum-ii | faster than 98.99% of Python3 || Easy to understand || hashmap | zixin123 | 0 | 138 | 4sum ii | 454 | 0.573 | Medium | 8,091 |
https://leetcode.com/problems/4sum-ii/discuss/1383752/Python-Approach-2%3A-Hashmap-explained | class Solution:
def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
mp = {}
count = 0
# nested loop 1
for uno in nums1:
for dos in nums2:
# get = value for the key, value if you don't get it
# if uno+dos exists in hashmap, increment value
# else: increment with value 1
mp[uno + dos] = mp.get(uno + dos, 0) + 1
# nested loop 2
for tres in nums3:
for quatro in nums4:
# get(value for key, value if you don't get it)
# getting hashmap value if the added number already exists in hashmap
# if there is no complimentary value in the hashmap -> return 0 -> doesn't change count
count += mp.get(-(tres + quatro), 0)
# return mp
return count | 4sum-ii | Python, Approach 2: Hashmap explained | bdanny | 0 | 158 | 4sum ii | 454 | 0.573 | Medium | 8,092 |
https://leetcode.com/problems/4sum-ii/discuss/976242/4Sum-II-Python3-one-liner | class Solution:
def fourSumCount(self, A: List[int], B: List[int], C: List[int], D: List[int]) -> int:
return sum(xcount * cdcounts[-x]
for cdcounts in [Counter(x+y for x in C for y in D)]
for x, xcount in Counter(x+y for x in A for y in B).items()
if -x in cdcounts) | 4sum-ii | 4Sum II Python3 one-liner | leetavenger | 0 | 46 | 4sum ii | 454 | 0.573 | Medium | 8,093 |
https://leetcode.com/problems/4sum-ii/discuss/975281/Simple-solution-in-python3-by-grouping-any-two-lists-together-and-using-idea-of-two-sum | class Solution:
def fourSumCount(self, A: List[int], B: List[int], C: List[int], D: List[int]) -> int:
hashmap = dict()
for i in A:
for j in C:
if i + j in hashmap:
hashmap[i + j] += 1
else:
hashmap[i + j] = 1
ans = 0
for i in B:
for j in D:
compl = -1 * (i + j)
ans += hashmap.get(compl, 0)
return ans | 4sum-ii | Simple solution in python3 by grouping any two lists together and using idea of two sum | amoghrajesh1999 | 0 | 60 | 4sum ii | 454 | 0.573 | Medium | 8,094 |
https://leetcode.com/problems/4sum-ii/discuss/860387/Dictionary-solution-Python | class Solution:
def fourSumCount(self, A: List[int], B: List[int], C: List[int], D: List[int]) -> int:
lastTwoSums = {}
firstTwoSums = {}
res = 0
for lilC in C:
for lilD in D:
if lilC + lilD in lastTwoSums:
lastTwoSums[lilC + lilD] += 1
else:
lastTwoSums[lilC + lilD] = 1
for lilA in A:
for lilB in B:
if lilA + lilB in firstTwoSums:
firstTwoSums[lilA + lilB] += 1
else:
firstTwoSums[lilA + lilB] = 1
for first in firstTwoSums:
if -first in lastTwoSums:
res += firstTwoSums[first] * lastTwoSums[-first]
return res | 4sum-ii | Dictionary solution [Python] | Sadie98 | 0 | 106 | 4sum ii | 454 | 0.573 | Medium | 8,095 |
https://leetcode.com/problems/4sum-ii/discuss/848502/Python3-freq-table | class Solution:
def fourSumCount(self, A: List[int], B: List[int], C: List[int], D: List[int]) -> int:
freq = {}
for x, y in product(A, B):
freq[x+y] = 1 + freq.get(x+y, 0)
return sum(freq.get(-x-y, 0) for x, y in product(C, D)) | 4sum-ii | [Python3] freq table | ye15 | 0 | 120 | 4sum ii | 454 | 0.573 | Medium | 8,096 |
https://leetcode.com/problems/4sum-ii/discuss/848502/Python3-freq-table | class Solution:
def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
freq = Counter(x+y for x in nums1 for y in nums2)
return sum(freq[-x-y] for x in nums3 for y in nums4) | 4sum-ii | [Python3] freq table | ye15 | 0 | 120 | 4sum ii | 454 | 0.573 | Medium | 8,097 |
https://leetcode.com/problems/4sum-ii/discuss/735836/Python-clear-solution-with-O(n2) | class Solution:
def fourSumCount(self, A: List[int], B: List[int], C: List[int], D: List[int]) -> int:
AB = [a+b for a in A for b in B]
CD = [c+d for c in C for d in D]
# Two sum from AB and CD
counts = 0
CD_count = collections.Counter(CD)
for num in AB:
counts += CD_count.get(-num, 0)
return counts | 4sum-ii | Python clear solution with O(n^2) | cnzero | 0 | 266 | 4sum ii | 454 | 0.573 | Medium | 8,098 |
https://leetcode.com/problems/assign-cookies/discuss/1334075/Python-Solution-or-Two-Pointers-or-O(nlogn) | class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
g.sort() # O(nlogn)
s.sort() # O(nlogn)
child_point = 0
cookie_point = 0
counter = 0
# O(n)
while child_point < len(g) and cookie_point < len(s):
if g[child_point] <= s[cookie_point]:
counter += 1
child_point += 1
cookie_point += 1
else:
cookie_point += 1
return counter | assign-cookies | Python Solution | Two Pointers | O(nlogn) | peatear-anthony | 2 | 267 | assign cookies | 455 | 0.505 | Easy | 8,099 |
Subsets and Splits