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/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/discuss/2228394/Python3-oror-Greedy-Approach | class Solution:
def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int:
horizontalCuts += [0,h]
verticalCuts += [0,w]
verticalCuts.sort()
horizontalCuts.sort()
vmax = 0
for i in range(len(verticalCuts)-1, 0, -1):
vmax = max(vmax, verticalCuts[i] - verticalCuts[i-1])
hmax = 0
for i in range(len(horizontalCuts)-1, 0, -1):
hmax = max(hmax, horizontalCuts[i] - horizontalCuts[i-1])
return (vmax * hmax)%(10**9 + 7) | maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts | Python3 || Greedy Approach | umesh_malik | 0 | 7 | maximum area of a piece of cake after horizontal and vertical cuts | 1,465 | 0.409 | Medium | 21,900 |
https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/discuss/2228213/Very-Easy-Python-Solution | class Solution:
def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int:
harr = horizontalCuts
harr.append(h)
harr.append(0)
harr.sort()
wrr = verticalCuts
wrr.append(w)
wrr.append(0)
wrr.sort()
# print(harr)
# print(wrr)
t1 = 0
for i in range(len(harr) -1):
if harr[i+1] - harr[i] > t1:
t1 = harr[i+1] - harr[i]
# print("t1 :", t1)
t2 = 0
for j in range(len(wrr) -1):
if wrr[j+1] - wrr[j] > t2:
t2 = wrr[j+1] - wrr[j]
# print("t2: ", t2)
return t1*t2%1000000007 | maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts | Very Easy Python Solution | vaibhav0077 | 0 | 11 | maximum area of a piece of cake after horizontal and vertical cuts | 1,465 | 0.409 | Medium | 21,901 |
https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/discuss/2227976/Simple-Python-solution | class Solution:
def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int:
horizontalCuts.sort()
verticalCuts.sort()
horizontalCuts = [0] + horizontalCuts + [h]
verticalCuts = [0] + verticalCuts + [w]
hor_max = ver_max = 0
for i in range(len(horizontalCuts)-1):
hor_max = max(hor_max, abs(horizontalCuts[i]-horizontalCuts[i+1]))
for j in range(len(verticalCuts)-1):
ver_max = max(ver_max, abs(verticalCuts[j]-verticalCuts[j+1]))
return (ver_max*hor_max)%(10**9 + 7) | maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts | Simple Python solution | bandavyagowra | 0 | 7 | maximum area of a piece of cake after horizontal and vertical cuts | 1,465 | 0.409 | Medium | 21,902 |
https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/discuss/2227825/Python-Easy-solution-in-constant-space | class Solution:
MODULO = 10**9 + 7
def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int:
horizontalCuts.insert(0, 0)
verticalCuts.insert(0, 0)
horizontalCuts.append(h)
verticalCuts.append(w)
horizontalCuts.sort()
verticalCuts.sort()
max_horizontal_distance = self._get_max_distance(horizontalCuts)
max_vertical_distance = self._get_max_distance(verticalCuts)
return (max_horizontal_distance * max_vertical_distance) % Solution.MODULO
@staticmethod
def _get_max_distance(cuts):
return max(cuts[i+1] - cuts[i] for i in range(len(cuts) - 1)) | maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts | [Python] Easy solution in constant space | julenn | 0 | 2 | maximum area of a piece of cake after horizontal and vertical cuts | 1,465 | 0.409 | Medium | 21,903 |
https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/discuss/2227479/Simple-Solution-Python | class Solution:
def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int:
if horizontalCuts[-1] != h:
horizontalCuts.append(h)
if verticalCuts != w:
verticalCuts.append(w)
horizontalCuts.sort()
verticalCuts.sort()
h_list =[horizontalCuts[0]]
v_list =[verticalCuts[0]]
for x in range(len(horizontalCuts)-1):
h_list.append(horizontalCuts[x+1] -horizontalCuts[x])
for y in range(len(verticalCuts) - 1):
v_list.append(verticalCuts[y+1] - verticalCuts[y])
return max(h_list) * max(v_list) %(10**9+7) | maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts | Simple Solution [Python] | salsabilelgharably | 0 | 2 | maximum area of a piece of cake after horizontal and vertical cuts | 1,465 | 0.409 | Medium | 21,904 |
https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/discuss/2226706/Python-Simple-Python-Solution-Using-Difference-of-Consecutive-Elements | class Solution:
def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int:
consecutive_difference_Hori = []
consecutive_difference_Vert = []
horizontalCuts = sorted(horizontalCuts+[0,h])
verticalCuts = sorted(verticalCuts+[0,w])
for i in range(len(horizontalCuts)-1):
diff = horizontalCuts[i+1] - horizontalCuts[i]
consecutive_difference_Hori.append(diff)
for j in range(len(verticalCuts)-1):
diff = verticalCuts[j+1] - verticalCuts[j]
consecutive_difference_Vert.append(diff)
return (max(consecutive_difference_Hori) * max(consecutive_difference_Vert) ) % ((10**9)+7) | maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts | [ Python ] ✅✅ Simple Python Solution Using Difference of Consecutive Elements🥳✌👍 | ASHOK_KUMAR_MEGHVANSHI | 0 | 15 | maximum area of a piece of cake after horizontal and vertical cuts | 1,465 | 0.409 | Medium | 21,905 |
https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/discuss/2226423/Easy-Clean-Explanation-With-An-Image-94.92 | class Solution:
def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int:
horizontalCuts.sort()
verticalCuts.sort()
maxHori = horizontalCuts[0] # First horizontal gap
maxVerti = verticalCuts[0] # First vertical gap
for i in range(1, len(horizontalCuts)):
maxHori = max(maxHori, horizontalCuts[i] - horizontalCuts[i - 1])
maxHori = max(maxHori, h - horizontalCuts[-1]) # Last horizontal gap
for i in range(1, len(verticalCuts)):
maxVerti = max(maxVerti, verticalCuts[i] - verticalCuts[i - 1])
maxVerti = max(maxVerti, (w - verticalCuts[-1])) # Last vertical gap
return maxHori * maxVerti % (10**9 + 7) | maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts | ✅ Easy Clean Explanation With An Image 94.92% | user3899k | 0 | 17 | maximum area of a piece of cake after horizontal and vertical cuts | 1,465 | 0.409 | Medium | 21,906 |
https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/discuss/2226367/java-python-easy-sorting-solution | class Solution:
def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int:
horizontalCuts.sort()
verticalCuts.sort()
dh = max(horizontalCuts[0], h - horizontalCuts[-1])
dw = max(verticalCuts[0], w - verticalCuts[-1])
i = 1
while i != len(horizontalCuts):
dh = max(dh, horizontalCuts[i] - horizontalCuts[i-1])
i += 1
i = 1
while i != len(verticalCuts):
dw = max(dw, verticalCuts[i] - verticalCuts[i-1])
i += 1
return dh * dw % 1000000007 | maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts | java, python - easy sorting solution | ZX007java | 0 | 14 | maximum area of a piece of cake after horizontal and vertical cuts | 1,465 | 0.409 | Medium | 21,907 |
https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/discuss/2226288/Easy-and-Simple-Approach-oror-Sorting | class Solution:
def maxArea(self, h: int, w: int, horizantalCuts: List[int], verticalCuts: List[int]) -> int:
horizantalCuts.append(0)
horizantalCuts.append(h)
verticalCuts.append(0)
verticalCuts.append(w)
mod = 10**9 + 7
horizantalCuts = sorted(horizantalCuts)
verticalCuts = sorted(verticalCuts)
maxHorizantalGap = float('-inf')
maxVerticalGap = float('-inf')
for i in range(1, len(horizantalCuts)):
maxHorizantalGap = max(maxHorizantalGap, horizantalCuts[i] - horizantalCuts[i - 1])
for i in range(1, len(verticalCuts)):
maxVerticalGap = max(maxVerticalGap, verticalCuts[i] - verticalCuts[i - 1])
return (maxHorizantalGap * maxVerticalGap) % mod | maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts | Easy and Simple Approach || Sorting | Vaibhav7860 | 0 | 5 | maximum area of a piece of cake after horizontal and vertical cuts | 1,465 | 0.409 | Medium | 21,908 |
https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/discuss/2226283/Python-Easy-Solution-Only-9-lines | class Solution:
def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int:
verticalCuts.sort()
horizontalCuts.sort()
maxw =max(verticalCuts[0],w - verticalCuts[-1])
for i in range(1,len(verticalCuts)):
maxw = max(maxw,verticalCuts[i] - verticalCuts[i-1])
maxh = max( horizontalCuts[0], h - horizontalCuts[-1] )
for i in range(1,len(horizontalCuts)):
maxh = max(maxh,horizontalCuts[i] - horizontalCuts[i-1])
return (maxw*maxh)%(pow(10,9) + 7) | maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts | Python Easy Solution - Only 9 lines | hackerbb | 0 | 9 | maximum area of a piece of cake after horizontal and vertical cuts | 1,465 | 0.409 | Medium | 21,909 |
https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/discuss/2226074/Easiest-Solution-Python | class Solution:
def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int:
horizontalCuts.sort()
verticalCuts.sort()
horizontalCuts.insert(0,0)
verticalCuts.insert(0,0)
horizontalCuts.append(h)
verticalCuts.append(w)
print(horizontalCuts,verticalCuts)
max_val = 0
for i in range(1,len(horizontalCuts)):
max_val = max(max_val, horizontalCuts[i]-horizontalCuts[i-1])
max_val2 = 0
for i in range(1,len(verticalCuts)):
max_val2 = max(max_val2, verticalCuts[i]-verticalCuts[i-1])
return (max_val*max_val2)%(10**9+7) | maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts | Easiest Solution Python | Abhi_009 | 0 | 10 | maximum area of a piece of cake after horizontal and vertical cuts | 1,465 | 0.409 | Medium | 21,910 |
https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/discuss/2225809/Python3-Solution-with-using-sorting | class Solution:
def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int:
horizontalCuts.sort()
verticalCuts.sort()
mod = 10**9 + 7
max_h = max(horizontalCuts[0] - 0, h - horizontalCuts[-1]) # choosing the maximum piece of cake: from begin of cake to first cut or last cut and end of cake (horizontal axis)
for i in range(len(horizontalCuts) - 1):
if horizontalCuts[i + 1] > h: # do not consider cuts after height cake
break
max_h = max(max_h, horizontalCuts[i + 1] - horizontalCuts[i])
max_w = max(verticalCuts[0] - 0, w - verticalCuts[-1]) # choosing the maximum piece of cake: from begin of cake to first cut or last cut and end of cake (vertical axis)
for i in range(len(verticalCuts) - 1):
if verticalCuts[i + 1] > w: # do not consider cuts after width cake
break
max_w = max(max_w, verticalCuts[i + 1] - verticalCuts[i])
return max_h * max_w % mod | maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts | [Python3] Solution with using sorting | maosipov11 | 0 | 10 | maximum area of a piece of cake after horizontal and vertical cuts | 1,465 | 0.409 | Medium | 21,911 |
https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/discuss/2225756/Python-solution-or-Maximum-Area-of-a-Piece-of-Cake-After-Horizontal-and-Vertical-Cuts | class Solution:
def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int:
horizontalLen, verticalLen = len(horizontalCuts), len(verticalCuts)
horizontalCuts.sort()
verticalCuts.sort()
maxHeight = max(horizontalCuts[0], h - horizontalCuts[horizontalLen-1])
for i in range(horizontalLen):
horizontalWidth = horizontalCuts[i] - horizontalCuts[i-1]
maxHeight = max(maxHeight,horizontalWidth)
maxWidth = max(verticalCuts[0], w - verticalCuts[verticalLen-1])
for j in range(verticalLen):
verticalHeight = verticalCuts[j] - verticalCuts[j-1]
maxWidth = max(maxWidth,verticalHeight)
return int((maxHeight * maxWidth) % 1000000007) | maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts | Python solution | Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts | nishanrahman1994 | 0 | 15 | maximum area of a piece of cake after horizontal and vertical cuts | 1,465 | 0.409 | Medium | 21,912 |
https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/discuss/2225297/Python3-solution | class Solution:
def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int:
hcuts = [0] + sorted(horizontalCuts) + [h]
vcuts = [0] + sorted(verticalCuts) + [w]
return max(c-p for p,c in zip(hcuts[:-1], hcuts[1:])) *\
max(c-p for p,c in zip(vcuts[:-1], vcuts[1:])) % (1_000_000_007) | maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts | Python3 solution | dalechoi | 0 | 10 | maximum area of a piece of cake after horizontal and vertical cuts | 1,465 | 0.409 | Medium | 21,913 |
https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/discuss/2225118/Python-oror-TC-O(NLogN)-oror-SC-O(1)-oror-Sort-ororGreedy | class Solution:
def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int:
horizontalCuts.append(h)
horizontalCuts.append(0)
verticalCuts.append(w)
verticalCuts.append(0)
horizontalCuts.sort()
verticalCuts.sort()
verDiff = -1
#verDiff = max(verDiff, verticalCuts[i]-verticalCuts[i-1])
for i in range(1,len(verticalCuts)):
verDiff = max(verDiff, verticalCuts[i]-verticalCuts[i-1])
horDiff = -1
for i in range(1,len(horizontalCuts)):
horDiff = max(horDiff, horizontalCuts[i]-horizontalCuts[i-1])
return (horDiff*verDiff)% 1000000007 | maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts | Python || TC O(NLogN) || SC O(1) || Sort ||Greedy | shamsahad48 | 0 | 3 | maximum area of a piece of cake after horizontal and vertical cuts | 1,465 | 0.409 | Medium | 21,914 |
https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/discuss/2225066/python3-code-and-readability | class Solution:
def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int:
mod = 10**9 + 7
return (self.max_height(h, horizontalCuts) * self.max_width(w, verticalCuts)) % mod
def max_height(self, h: int, horizontal_cuts: List[int]) -> int:
return self.get_max(horizontal_cuts, h)
def max_width(self, w: int, vertical_cuts: List[int]) -> int:
return self.get_max(vertical_cuts, w)
def get_max(self, cuts: List[int], direction: int) -> int:
if not cuts:
return -1
cuts.sort()
max_size = 0
for i, cut in enumerate(cuts):
if i == 0:
max_size = max(max_size, cut)
else:
max_size = max(max_size, cuts[i] - cuts[i-1])
# check the width and height from the last cut
max_size = max(max_size, direction - cuts[-1])
return max_size | maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts | python3 code and readability | notJoon | 0 | 12 | maximum area of a piece of cake after horizontal and vertical cuts | 1,465 | 0.409 | Medium | 21,915 |
https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/discuss/2224948/Python-or-Easy-to-Understand-or-With-Explanation | class Solution:
def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int:
# sort then find the maximum difference in both two directions
horizontalCuts.sort()
verticalCuts.sort()
max_height_diff = max(horizontalCuts[0], h - horizontalCuts[-1])
max_width_diff = max(verticalCuts[0], w - verticalCuts[-1])
for i in range(0, len(horizontalCuts) -1):
max_height_diff = max(max_height_diff, horizontalCuts[i+1] - horizontalCuts[i])
for i in range(0, len(verticalCuts) -1):
max_width_diff = max(max_width_diff, verticalCuts[i+1] - verticalCuts[i])
return (max_width_diff * max_height_diff) % (10 ** 9 + 7) | maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts | Python | Easy to Understand | With Explanation | Mikey98 | 0 | 13 | maximum area of a piece of cake after horizontal and vertical cuts | 1,465 | 0.409 | Medium | 21,916 |
https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/discuss/2224932/Easy-Python-solution | class Solution:
def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int:
horizontalCuts.sort()
verticalCuts.sort()
max_w = 0
max_h = 0
hs = []
verticalCuts = [0] + verticalCuts + [w]
horizontalCuts = [0] + horizontalCuts + [h]
for i in range(len(verticalCuts) - 1):
max_w = max(max_w, abs(verticalCuts[i] - verticalCuts[i+1]))
for i in range(len(horizontalCuts) - 1):
max_h = max(max_h, abs(horizontalCuts[i] - horizontalCuts[i+1]))
return max_w * max_h % (10**9 + 7) | maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts | Easy Python solution | knishiji | 0 | 16 | maximum area of a piece of cake after horizontal and vertical cuts | 1,465 | 0.409 | Medium | 21,917 |
https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/discuss/2224889/Python-two-maximums | class Solution:
def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int:
def getMaxGap(d, cuts):
max_ = cuts[0]
for i in range(1, len(cuts)):
max_ = max(max_, cuts[i] - cuts[i-1])
return max(max_, d - cuts[-1])
max_h = getMaxGap(h, sorted(horizontalCuts))
max_w = getMaxGap(w, sorted(verticalCuts))
return max_h * max_w % (10**9 + 7) | maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts | Python, two maximums | blue_sky5 | 0 | 11 | maximum area of a piece of cake after horizontal and vertical cuts | 1,465 | 0.409 | Medium | 21,918 |
https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/discuss/2145391/python-3-oror-simple-sorting-solution | class Solution:
def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int:
horizontalCuts.append(0)
horizontalCuts.sort()
horizontalCuts.append(h)
maxHorizontalGap = max(horizontalCuts[i] - horizontalCuts[i - 1]
for i in range(1, len(horizontalCuts)))
verticalCuts.append(0)
verticalCuts.sort()
verticalCuts.append(w)
maxVerticalGap = max(verticalCuts[i] - verticalCuts[i - 1]
for i in range(1, len(verticalCuts)))
return (maxHorizontalGap * maxVerticalGap) % (10 ** 9 + 7) | maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts | python 3 || simple sorting solution | dereky4 | 0 | 35 | maximum area of a piece of cake after horizontal and vertical cuts | 1,465 | 0.409 | Medium | 21,919 |
https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/discuss/1535785/Python3maxWidth-*-maxHeight | class Solution:
def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int:
verticalCuts.sort()
horizontalCuts.sort()
maxWidth = self.findMaxDistance(w, verticalCuts)
maxHeight = self.findMaxDistance(h, horizontalCuts)
return maxWidth * maxHeight % (1000000007)
def findMaxDistance(self,last, cut):
maxDistance = 0
n = len(cut)
for i in range(n):
if i == 0:
curDistance = cut[i] - 0
else:
curDistance = cut[i] - cut[i - 1]
maxDistance = max(maxDistance, curDistance)
maxDistance = max(maxDistance, last - cut[-1])
return maxDistance | maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts | [Python3]maxWidth * maxHeight | zhanweiting | 0 | 115 | maximum area of a piece of cake after horizontal and vertical cuts | 1,465 | 0.409 | Medium | 21,920 |
https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/discuss/1447027/Python3Python-Simple-solution-w-comments | class Solution:
def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int:
# Init
numHorizontalCuts = len(horizontalCuts)
numVerticalCuts = len(verticalCuts)
horizontalgaps = []
verticalgaps = []
# Sort the cuts
horizontalCuts = sorted(horizontalCuts)
verticalCuts = sorted(verticalCuts)
# Calc horizontal gaps
for i in range(0,numHorizontalCuts+1):
if i == 0:
horizontalgaps.append(horizontalCuts[i]-0)
elif i == numHorizontalCuts:
horizontalgaps.append(h-horizontalCuts[i-1])
else:
horizontalgaps.append(horizontalCuts[i]-horizontalCuts[i-1])
# Calc vertical gaps
for i in range(0,numVerticalCuts+1):
if i == 0:
verticalgaps.append(verticalCuts[i]-0)
elif i == numVerticalCuts:
verticalgaps.append(w-verticalCuts[i-1])
else:
verticalgaps.append(verticalCuts[i]-verticalCuts[i-1])
# return max-area % 10^9+7
return (max(horizontalgaps)*max(verticalgaps)) % ((10**9)+7) | maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts | [Python3/Python] Simple solution w/ comments | ssshukla26 | 0 | 172 | maximum area of a piece of cake after horizontal and vertical cuts | 1,465 | 0.409 | Medium | 21,921 |
https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/discuss/1249174/Python-O(mlogm-%2B-nlogn)-solution-using-sorting | class Solution:
def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int:
m, n, l, b = len(horizontalCuts), len(verticalCuts), 0, 0
horizontalCuts.sort()
verticalCuts.sort()
l, b = max(horizontalCuts[0], h - horizontalCuts[m - 1]), max(verticalCuts[0], w - verticalCuts[n - 1])
for i in range(1,m):
l = max(l, horizontalCuts[i] - horizontalCuts[i - 1])
for i in range(1,n):
b = max(b, verticalCuts[i] - verticalCuts[i - 1])
return (l * b) %(10**9 + 7) | maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts | Python O(mlogm + nlogn) solution using sorting | m0biu5 | 0 | 43 | maximum area of a piece of cake after horizontal and vertical cuts | 1,465 | 0.409 | Medium | 21,922 |
https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/discuss/1248579/Simple-Python-Code | class Solution:
def maxArea(self, h: int, w: int, hc: List[int], vc: List[int]) -> int:
hs = [0] + sorted(hc) + [h]
vs = [0] + sorted(vc) + [w]
mw = max([hs[i + 1] - he[i] for i in range(len(hs) - 1)])
mh = max([vs[i + 1] - vs[i] for i in range(len(vs) - 1)])
return (mw * mh) % ((10 ** 9) + 7) | maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts | Simple Python Code🐍 | Khacker | 0 | 108 | maximum area of a piece of cake after horizontal and vertical cuts | 1,465 | 0.409 | Medium | 21,923 |
https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/discuss/1248543/Python-3-%2B-Explanation-ororMaximum-Area-of-a-Piece-of-Cake-After-Horizontal-and-Vertical-Cuts | class Solution:
def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int:
horizontalCuts.sort()
verticalCuts.sort()
max_height=max(horizontalCuts[0],h-horizontalCuts[-1])
for i in range(1,len(horizontalCuts)):
max_height=max(max_height,horizontalCuts[i]-horizontalCuts[i-1])
max_width=max(verticalCuts[0],w-verticalCuts[-1])
for i in range(1,len(verticalCuts)):
max_width=max(max_width,verticalCuts[i]-verticalCuts[i-1])
return (max_width*max_height)%(10**9+7) | maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts | Python 3 + Explanation ||Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts | jaipoo | 0 | 58 | maximum area of a piece of cake after horizontal and vertical cuts | 1,465 | 0.409 | Medium | 21,924 |
https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/discuss/1248529/Maximum-Area-of-a-Piece-of-Cake-or-Super-Simple-Code-or-2-liner-or-Python | class Solution:
def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int:
horizontalCuts.sort()
verticalCuts.sort()
maxHorizontalArea = max(horizontalCuts[0], h - horizontalCuts[-1])
maxVerticalArea = max(verticalCuts[0], w - verticalCuts[-1])
for i in range(0, len(horizontalCuts) - 1):
maxHorizontalArea = max(maxHorizontalArea, horizontalCuts[i + 1] - horizontalCuts[i])
for i in range(0, len(verticalCuts) - 1):
maxVerticalArea = max(maxVerticalArea, verticalCuts[i + 1] - verticalCuts[i])
return (maxHorizontalArea * maxVerticalArea) % int(1e9 + 7) | maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts | Maximum Area of a Piece of Cake | Super Simple Code | 2 liner | Python | shubh_027 | 0 | 43 | maximum area of a piece of cake after horizontal and vertical cuts | 1,465 | 0.409 | Medium | 21,925 |
https://leetcode.com/problems/reorder-routes-to-make-all-paths-lead-to-the-city-zero/discuss/1071235/Pythonor-Easy-and-fast-or-Beats-99 | class Solution:
def minReorder(self, n: int, connections: List[List[int]]) -> int:
cmap = {0}
count = 0
dq = deque(connections)
while dq:
u, v = dq.popleft()
if v in cmap:
cmap.add(u)
elif u in cmap:
cmap.add(v)
count += 1
else:
dq.append([u, v])
return count | reorder-routes-to-make-all-paths-lead-to-the-city-zero | Python| Easy and fast | Beats 99% | SlavaHerasymov | 8 | 406 | reorder routes to make all paths lead to the city zero | 1,466 | 0.618 | Medium | 21,926 |
https://leetcode.com/problems/reorder-routes-to-make-all-paths-lead-to-the-city-zero/discuss/2738991/Simple-python-solution-using-BFS-traversal | class Solution:
def minReorder(self, n: int, connections: List[List[int]]) -> int:
visited=[0]*n
indegree=[[] for _ in range(n)]
outdegree=[[] for _ in range(n)]
for frm,to in connections:
indegree[to].append(frm)
outdegree[frm].append(to)
lst=[0]
visited[0]=1
ct=0
while lst:
x=lst.pop(0)
for i in indegree[x]:
if visited[i]==0:
lst.append(i)
visited[i]=1
for i in outdegree[x]:
if visited[i]==0:
lst.append(i)
visited[i]=1
# here we have to change the direction of edge
ct+=1
return ct | reorder-routes-to-make-all-paths-lead-to-the-city-zero | Simple python solution using BFS traversal | beneath_ocean | 3 | 176 | reorder routes to make all paths lead to the city zero | 1,466 | 0.618 | Medium | 21,927 |
https://leetcode.com/problems/reorder-routes-to-make-all-paths-lead-to-the-city-zero/discuss/2643633/Python-3-95-speed | class Solution:
def minReorder(self, n: int, connections: List[List[int]]) -> int:
graph = defaultdict(set)
for a, b in connections:
graph[a].add((b, True))
graph[b].add((a, False))
queue = deque([(0, False)])
ans = 0
visited = set()
while queue:
city, needs_flipped = queue.popleft()
visited.add(city)
if needs_flipped:
ans += 1
for neighbour in graph[city]:
if neighbour[0] not in visited:
queue.append(neighbour)
return ans | reorder-routes-to-make-all-paths-lead-to-the-city-zero | Python 3 95% speed | very_drole | 1 | 85 | reorder routes to make all paths lead to the city zero | 1,466 | 0.618 | Medium | 21,928 |
https://leetcode.com/problems/reorder-routes-to-make-all-paths-lead-to-the-city-zero/discuss/1636479/Python3-Solution-with-using-dfs-with-comments | class Solution:
def __init__(self):
self.res = 0 # number of changed edges
def dfs(self, g, v, visited):
visited[v] = 1 # v is visited
for neigb in g[v]:
if visited[neigb[0]] == 0: # if neigb[0] (v) is not visited
if neigb[1] == 1: # if weight = 1, then wee need change edge (we moving from root (from 0))
self.res += 1
self.dfs(g, neigb[0], visited)
def minReorder(self, n: int, connections: List[List[int]]) -> int:
g = collections.defaultdict(list)
visited = [0] * n
for conn in connections:
"""
[conn[1], 1] - conn[1] - v and 1 - weight (1 means that v has output edge)
[conn[0], -1] - conn[0] - v and -1 - weight (-1 means that v has input edge))
"""
g[conn[0]].append([conn[1], 1])
g[conn[1]].append([conn[0], -1])
self.dfs(g, 0, visited)
return self.res | reorder-routes-to-make-all-paths-lead-to-the-city-zero | [Python3] Solution with using dfs with comments | maosipov11 | 1 | 111 | reorder routes to make all paths lead to the city zero | 1,466 | 0.618 | Medium | 21,929 |
https://leetcode.com/problems/reorder-routes-to-make-all-paths-lead-to-the-city-zero/discuss/661811/Python3-dfs-to-count-in-and-out-degrees | class Solution:
def minReorder(self, n: int, connections: List[List[int]]) -> int:
in_, out = dict(), dict()
for u, v in connections:
out.setdefault(u, []).append(v)
in_.setdefault(v, []).append(u)
def dfs(n):
"""Return required number of reverses"""
seen[n] = True
ans = sum(not seen[x] for x in out.get(n, []))
for nn in in_.get(n, []) + out.get(n, []):
if not seen[nn]: ans += dfs(nn)
return ans
seen = [False]*n
return dfs(0) | reorder-routes-to-make-all-paths-lead-to-the-city-zero | [Python3] dfs to count in & out degrees | ye15 | 1 | 72 | reorder routes to make all paths lead to the city zero | 1,466 | 0.618 | Medium | 21,930 |
https://leetcode.com/problems/reorder-routes-to-make-all-paths-lead-to-the-city-zero/discuss/2698329/Python3-oror-easy-oror-memory-efficient-oror-intuitive-solution | class Solution:
def minReorder(self, n: int, connections: List[List[int]]) -> int:
incoming={}
outgoing={}
for n1,n2 in connections:
if outgoing.get(n1):
outgoing[n1].append(n2)
else:
outgoing[n1]=[n2]
if incoming.get(n2):
incoming[n2].append(n1)
else:
incoming[n2]=[n1]
q=collections.deque()
q.append(0)
res=0
visited=set()
while q:
node=q.popleft()
if incoming.get(node) :
for i in incoming[node]:
if i is not 0 and i not in visited:
q.append(i)
if outgoing.get(node):
for o in outgoing[node]:
if o is not 0 and o not in visited:
q.append(o)
res+=1
visited.add(node)
return res | reorder-routes-to-make-all-paths-lead-to-the-city-zero | Python3 || easy || memory efficient || intuitive solution | _soninirav | 0 | 14 | reorder routes to make all paths lead to the city zero | 1,466 | 0.618 | Medium | 21,931 |
https://leetcode.com/problems/reorder-routes-to-make-all-paths-lead-to-the-city-zero/discuss/2539709/Python-Commented-DFS-solution | class Solution:
def minReorder(self, n: int, connections: List[List[int]]) -> int:
# get the connections (undirectoed)
# but keep track of the direction
cn = collections.defaultdict(list)
for start, stop in connections:
cn[start].append((stop, False))
cn[stop].append((start, True))
# traverse from the zero node
val = dfs(0, cn, -1)
return val
def dfs(node, cn, previous):
# go through all connected nodes
# but make sure not to go back
# to the node we are coming from!
value = 0
for conn, right_dir in cn[node]:
if not conn == previous:
# check whether connection is in the false direction
if not right_dir:
value += 1
# go deeper and add the edges
value += dfs(conn, cn, node)
return value | reorder-routes-to-make-all-paths-lead-to-the-city-zero | [Python] - Commented DFS solution | Lucew | 0 | 40 | reorder routes to make all paths lead to the city zero | 1,466 | 0.618 | Medium | 21,932 |
https://leetcode.com/problems/reorder-routes-to-make-all-paths-lead-to-the-city-zero/discuss/2526421/python-dfs-with-O(2n)-dict | class Solution:
def minReorder(self, n: int, connections: List[List[int]]) -> int:
ans = 0
edges = {x:{} for x in range(n)}
for e in connections:
edges[e[0]][e[1]] = 1
edges[e[1]][e[0]] = 0
return self.dfs(0, edges)
def dfs(self, root, edges):
if not edges[root]: return 0
ans = 0
for k,v in edges[root].items():
if v!=-1:
ans+=v
edges[root][k] = -1
edges[k][root] = -1
ans+=self.dfs(k,edges)
return ans | reorder-routes-to-make-all-paths-lead-to-the-city-zero | python dfs with O(2n) dict | li87o | 0 | 27 | reorder routes to make all paths lead to the city zero | 1,466 | 0.618 | Medium | 21,933 |
https://leetcode.com/problems/reorder-routes-to-make-all-paths-lead-to-the-city-zero/discuss/2125980/Python-or-BFS-or-Faster-than-98-or-Memory-97 | class Solution:
def minReorder(self, n: int, connections: List[List[int]]) -> int:
# Build the graph: (connected node, forward)
graph = [[] for _ in range(n)]
for c in connections:
graph[c[0]].append((c[1], True))
graph[c[1]].append((c[0], False))
seen = [False] * n
seen[0] = True
q = deque([0])
res = 0
while q:
cur = q.popleft()
for n, forward in graph[cur]:
if not seen[n]:
seen[n] = True
q.append(n)
if forward:
res += 1
return res | reorder-routes-to-make-all-paths-lead-to-the-city-zero | Python | BFS | Faster than 98% | Memory 97% | slbteam08 | 0 | 71 | reorder routes to make all paths lead to the city zero | 1,466 | 0.618 | Medium | 21,934 |
https://leetcode.com/problems/reorder-routes-to-make-all-paths-lead-to-the-city-zero/discuss/2076275/Python-Concise-solution | class Solution:
def minReorder(self, n: int, connections: List[List[int]]) -> int:
d1=defaultdict(list)
d2=defaultdict(list)# undirected
for i in connections:
d1[i[1]].append(i[0])
d2[i[1]].append(i[0])
d2[i[0]].append(i[1])
arr=[0]
c=0
visited=set()
while len(arr)>0:
p=arr.pop()
if p in visited:
continue
visited.add(p)
c+=len([x for x in d2[p] if x not in d1[p] and x not in visited])
arr.extend(d2[p])
return c | reorder-routes-to-make-all-paths-lead-to-the-city-zero | Python Concise solution | guankiro | 0 | 41 | reorder routes to make all paths lead to the city zero | 1,466 | 0.618 | Medium | 21,935 |
https://leetcode.com/problems/reorder-routes-to-make-all-paths-lead-to-the-city-zero/discuss/1899711/Python3-90-Success-Rate-or-DFS-or-Easy-To-Understand-Clean-Code | class Solution:
def minReorder(self, n: int, connections: List[List[int]]) -> int:
def dfs(u):
nonlocal c
vis[u] = True
for i,d in graph[u]:
if vis[i]:continue;
if d==1: # Check Whether it is usual direction or in Reversed
c+=1
dfs(i)
graph = {i:[] for i in range(n)}
vis = [False]*n
c = 0
for u,v in connections:
graph[u].append((v,1)) #mark node as Forward
graph[v].append((u,-1)) # mark node as Backward
dfs(0)
return c | reorder-routes-to-make-all-paths-lead-to-the-city-zero | [Python3] 90% Success Rate | DFS | Easy To Understand Clean Code | rstudy211 | 0 | 59 | reorder routes to make all paths lead to the city zero | 1,466 | 0.618 | Medium | 21,936 |
https://leetcode.com/problems/reorder-routes-to-make-all-paths-lead-to-the-city-zero/discuss/832114/Intuitive-approach-by-building-undirected-graph-and-then-use-BFS-to-explore-the-graph | class Solution:
def minReorder(self, n: int, connections: List[List[int]]) -> int:
class Node:
def __init__(self, n):
self.n = n
self.neighbors = []
self.is_visit = False
def neighbors_gen(self):
def gen(neighbors=self.neighbors):
for n in self.neighbors:
yield n
return gen()
dirt_set = set()
node_dict = {}
''' key as n; value as corresponding node obj'''
for s, e in connections:
if s not in node_dict:
node_dict[s] = Node(s)
if e not in node_dict:
node_dict[e] = Node(e)
node_dict[s].neighbors.append(node_dict[e])
node_dict[e].neighbors.append(node_dict[s])
dirt_set.add((s, e))
# BFS
ans = 0
znode = node_dict[0]
queue = [znode]
reverse_set = set()
while queue:
n = queue.pop(0)
if n.is_visit:
continue
n.is_visit = True
for nn in n.neighbors_gen():
if not nn.is_visit:
queue.append(nn)
path = (nn.n, n.n)
if path not in dirt_set and path not in reverse_set:
# print(f"Path found: {path}")
ans += 1
reverse_set.add(path)
return ans | reorder-routes-to-make-all-paths-lead-to-the-city-zero | Intuitive approach by building undirected graph and then use BFS to explore the graph | puremonkey2001 | 0 | 44 | reorder routes to make all paths lead to the city zero | 1,466 | 0.618 | Medium | 21,937 |
https://leetcode.com/problems/reorder-routes-to-make-all-paths-lead-to-the-city-zero/discuss/664966/Python3-Iterative-Solution-DFS-and-BFS-with-explanation | class Solution:
def minReorder(self, n: int, connections: List[List[int]]) -> int:
visited = set()
inDegree = collections.defaultdict(list)
outDegree = collections.defaultdict(set)
for con in connections:
outDegree[con[0]].add(con[1])
inDegree[con[1]].append(con[0])
cnt = 0
stack = [0]
while stack:
city = stack.pop()
if city in visited:
continue
visited.add(city)
stack.extend(inDegree[city])
for c in outDegree[city]:
if c not in visited:
cnt += 1
stack.append(c)
return cnt | reorder-routes-to-make-all-paths-lead-to-the-city-zero | [Python3] Iterative Solution [DFS & BFS] with explanation | q463746583 | 0 | 55 | reorder routes to make all paths lead to the city zero | 1,466 | 0.618 | Medium | 21,938 |
https://leetcode.com/problems/probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/discuss/1214891/Python3-top-down-dp | class Solution:
def getProbability(self, balls: List[int]) -> float:
n = sum(balls)//2
@cache
def fn(i, s0, s1, c0, c1):
"""Return number of ways to distribute boxes successfully (w/o considering relative order)."""
if s0 > n or s1 > n: return 0 # impossible
if i == len(balls): return int(c0 == c1)
ans = 0
for x in range(balls[i]+1):
ans += fn(i+1, s0+x, s1+balls[i]-x, c0+(x > 0), c1+(x < balls[i])) * comb(balls[i], x)
return ans
return fn(0, 0, 0, 0, 0) / comb(2*n, n) | probability-of-a-two-boxes-having-the-same-number-of-distinct-balls | [Python3] top-down dp | ye15 | 0 | 130 | probability of a two boxes having the same number of distinct balls | 1,467 | 0.611 | Hard | 21,939 |
https://leetcode.com/problems/shuffle-the-array/discuss/941189/Simple-Python-Solution | class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
l=[]
for i in range(n):
l.append(nums[i])
l.append(nums[n+i])
return l | shuffle-the-array | Simple Python Solution | lokeshsenthilkumar | 10 | 947 | shuffle the array | 1,470 | 0.885 | Easy | 21,940 |
https://leetcode.com/problems/shuffle-the-array/discuss/941189/Simple-Python-Solution | class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
l=[]
for i in range(n):
l.extend([nums[i],nums[i+1]])
return l | shuffle-the-array | Simple Python Solution | lokeshsenthilkumar | 10 | 947 | shuffle the array | 1,470 | 0.885 | Easy | 21,941 |
https://leetcode.com/problems/shuffle-the-array/discuss/729048/Python-In-place-Memory-usage-less-than-100 | class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
for i in range(n, 2*n):
nums[i] = (nums[i] << 10) | nums[i-n]
for i in range(n, 2*n):
nums[(i-n)*2] = nums[i] & (2 ** 10 - 1)
nums[(i-n)*2+1] = nums[i] >> 10
return nums | shuffle-the-array | Python - In place - Memory usage less than 100% | mmbhatk | 6 | 1,100 | shuffle the array | 1,470 | 0.885 | Easy | 21,942 |
https://leetcode.com/problems/shuffle-the-array/discuss/1697309/Python-code%3A-Shuffle-the-Array | class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
c=[]
for i in range(n):
c.append(nums[i])
c.append(nums[n+i])
return c | shuffle-the-array | Python code: Shuffle the Array | Anilchouhan181 | 5 | 137 | shuffle the array | 1,470 | 0.885 | Easy | 21,943 |
https://leetcode.com/problems/shuffle-the-array/discuss/2406866/Simple-python-code-with-explanation | class Solution:
#two pointers approach
def shuffle(self, nums: List[int], n: int) -> List[int]:
#initialise the l pointer to 0th index
l = 0
#initialise the r pointer to middle index
r = len(nums)//2
#create the new list (res)
res = []
#condition breaks when l pointer reaches middle index
#and r pointer reaches the last index
while l < len(nums)//2 and r < len(nums):
#add the element at l pointer to res -->list
res.append(nums[l])
#after adding increase the l pointer by 1
l = l + 1
#add the element at r pointer to res-->list
res.append(nums[r])
#after adding increase the r pointer by 1
r = r +1
#after breaking while loop return res--> list
return res | shuffle-the-array | Simple python code with explanation | thomanani | 3 | 155 | shuffle the array | 1,470 | 0.885 | Easy | 21,944 |
https://leetcode.com/problems/shuffle-the-array/discuss/2282692/Python-Simple-List-Comprehension-One-Liner-with-Modulo-for-Indexing | class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
return [nums[i//2 + n*(i%2)] for i in range(0,2*n,1)] | shuffle-the-array | Python, Simple List Comprehension One-Liner with Modulo for Indexing | boris17 | 2 | 54 | shuffle the array | 1,470 | 0.885 | Easy | 21,945 |
https://leetcode.com/problems/shuffle-the-array/discuss/2250249/Python3-O(n)-oror-O(n)-Runtime%3A-51ms-99.70-memory%3A-14.2mb-40.91 | class Solution:
# O(n) || O(n)
# Runtime: 51ms 99.70% memory: 14.2mb 40.91%
def shuffle(self, nums: List[int], n: int) -> List[int]:
new_arr = [0] * len(nums)
count = 0
oddIndex = 0
while count <= n-1:
new_arr[oddIndex] = nums[count]
oddIndex+= 2
count += 1
difference = len(nums) - count
i = 1
evenIndex = 1
while count <= len(nums):
new_arr[evenIndex] = nums[count]
count += 1
evenIndex += 2
if i == difference:
break
i+=1
return new_arr | shuffle-the-array | Python3 # O(n) || O(n) # Runtime: 51ms 99.70% memory: 14.2mb 40.91% | arshergon | 2 | 64 | shuffle the array | 1,470 | 0.885 | Easy | 21,946 |
https://leetcode.com/problems/shuffle-the-array/discuss/742009/Python-3-In-place-shuffle | class Solution(object):
def shuffle(self, nums, n):
"""
:type nums: List[int]
:type n: int
:rtype: List[int]
"""
def swappairs(i,j):
while(i<j):
swap(i,i+1)
i+=2
def swap(i,j):
tmp = nums[i]
nums[i] = nums[j]
nums[j] = tmp
for i in range(n-1):
swappairs(n-1-i,n+i)
return nums | shuffle-the-array | [Python 3] In place shuffle | yazido | 2 | 307 | shuffle the array | 1,470 | 0.885 | Easy | 21,947 |
https://leetcode.com/problems/shuffle-the-array/discuss/2757660/Python-Easy-Solution-90 | class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
f = []
for i in range(len(nums) - n):
f.append(nums[i])
f.append(nums[i+n])
return f | shuffle-the-array | Python Easy Solution 90% | Jashan6 | 1 | 53 | shuffle the array | 1,470 | 0.885 | Easy | 21,948 |
https://leetcode.com/problems/shuffle-the-array/discuss/2749600/Python-Beginner-Solution | class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
f=nums[:n]
s=nums[n:]
ans=[]
for i in range(len(f)):
ans.append(f[i])
ans.append(s[i])
return ans | shuffle-the-array | Python Beginner Solution | beingab329 | 1 | 29 | shuffle the array | 1,470 | 0.885 | Easy | 21,949 |
https://leetcode.com/problems/shuffle-the-array/discuss/2667718/Python-Roblox-VO-Preparation%3A-In-Place-Solution-No-Bitwise-Cheating-No-Fancy-Sh!ts | class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
# use in-place array technique
# no additional space usage allowed
index = n
for i in range(2 * n):
if i % 2 == 0:
nums = nums[:i+1] + nums[index:index+1] + nums[i+1:index] + nums[index+1:]
index += 1
return nums | shuffle-the-array | [Python] Roblox VO Preparation: In-Place Solution, No Bitwise Cheating, No Fancy Sh!ts | bbshark | 1 | 412 | shuffle the array | 1,470 | 0.885 | Easy | 21,950 |
https://leetcode.com/problems/shuffle-the-array/discuss/2314603/easy-python-basic-solution | class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
ans=[]
for i in range(n):
ans.append(nums[i])
ans.append(nums[n+i])
return ans | shuffle-the-array | easy python basic solution | kaartikN | 1 | 82 | shuffle the array | 1,470 | 0.885 | Easy | 21,951 |
https://leetcode.com/problems/shuffle-the-array/discuss/2299330/The-3-lists-method-%2B-slicing-(easy-for-beginners) | class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
l1, l2 = nums[0:n], nums[n:]
ans = list()
for i in range(n):
ans.append(l1[i])
ans.append(l2[i])
return ans | shuffle-the-array | The 3 lists method + slicing (easy for beginners) | arimanyus | 1 | 51 | shuffle the array | 1,470 | 0.885 | Easy | 21,952 |
https://leetcode.com/problems/shuffle-the-array/discuss/2005609/Python-Solution | class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
new_nums = []
for i in range(len(nums)//2):
new_nums.extend([nums[i],nums[i+n]])
return new_nums | shuffle-the-array | 🔴 Python Solution 🔴 | alekskram | 1 | 77 | shuffle the array | 1,470 | 0.885 | Easy | 21,953 |
https://leetcode.com/problems/shuffle-the-array/discuss/1866967/Python-O(n)-simle-solution | class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
result = []
index = 0
while index < n:
result.extend([nums[index], nums[n + index]])
index = index + 1
return result | shuffle-the-array | Python O(n) simle solution | hardik097 | 1 | 67 | shuffle the array | 1,470 | 0.885 | Easy | 21,954 |
https://leetcode.com/problems/shuffle-the-array/discuss/1722651/1470-shuffle-array-or-Python-2-ways | class Solution(object):
def shuffle(self, nums, n):
shuffle_array = []
list1 = nums[:n]
list2 = nums[n:]
for i in range(0,n):
shuffle_array.extend([list1[i],list2[i]])
return shuffle_array | shuffle-the-array | 1470 - shuffle array | Python 2 ways | ankit61d | 1 | 106 | shuffle the array | 1,470 | 0.885 | Easy | 21,955 |
https://leetcode.com/problems/shuffle-the-array/discuss/1722651/1470-shuffle-array-or-Python-2-ways | class Solution(object):
def shuffle(self, nums, n):
shuffle_array = []
# 2*n is the total length
for i in range(0,n):
shuffle_array.append(nums[i])
shuffle_array.append(nums[n+i])
return shuffle_array | shuffle-the-array | 1470 - shuffle array | Python 2 ways | ankit61d | 1 | 106 | shuffle the array | 1,470 | 0.885 | Easy | 21,956 |
https://leetcode.com/problems/shuffle-the-array/discuss/1591553/python-simple-solution-56ms | class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
half1 = nums[:n]
half2 = nums[n:]
nums[::2] = half1
nums[1::2] = half2
return nums | shuffle-the-array | python simple solution 56ms | DTChi123 | 1 | 82 | shuffle the array | 1,470 | 0.885 | Easy | 21,957 |
https://leetcode.com/problems/shuffle-the-array/discuss/1515738/Python3-solution | class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
xlist = nums[:n]
ylist = nums[n:]
ans = []
for i in range(n):
ans.extend([xlist[i],ylist[i]])
return ans | shuffle-the-array | Python3 solution | whereismycodd | 1 | 76 | shuffle the array | 1,470 | 0.885 | Easy | 21,958 |
https://leetcode.com/problems/shuffle-the-array/discuss/1409689/Python3-or-Using-Zip | class Solution:
def shuffle(self, nums: list, n: int):
res = []
for i,j in zip(nums[:n],nums[n:]):
res+=[i,j]
return res
obj = Solution()
print(obj.shuffle(nums = [2, 5, 1, 3, 4, 7], n = 3)) | shuffle-the-array | Python3 🐍 | Using Zip | hritik5102 | 1 | 58 | shuffle the array | 1,470 | 0.885 | Easy | 21,959 |
https://leetcode.com/problems/shuffle-the-array/discuss/1273399/WEEB-DOES-PYTHON-in-O(n)-time | class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
result, i = [], 0
while n<len(nums):
result+= [nums[i]]
result+= [nums[n]]
i+=1
n+=1
return result | shuffle-the-array | WEEB DOES PYTHON in O(n) time | Skywalker5423 | 1 | 309 | shuffle the array | 1,470 | 0.885 | Easy | 21,960 |
https://leetcode.com/problems/shuffle-the-array/discuss/1214515/Simple-Python-Code | class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
k = []
for i in range (0,n):
k.append(nums[i])
k.append(nums[n+i])
return k
``` | shuffle-the-array | Simple Python Code | KaranVeerSingh | 1 | 151 | shuffle the array | 1,470 | 0.885 | Easy | 21,961 |
https://leetcode.com/problems/shuffle-the-array/discuss/1154520/Python-solution-looping-through-list | class Solution(object):
def shuffle(self, nums, n):
"""
:type nums: List[int]
:type n: int
:rtype: List[int]
"""
ret = []
for i in range(n):
ret.append(nums[i])
ret.append(nums[i+n])
return ret | shuffle-the-array | Python solution looping through list | 5tigerjelly | 1 | 168 | shuffle the array | 1,470 | 0.885 | Easy | 21,962 |
https://leetcode.com/problems/shuffle-the-array/discuss/1151125/Python3-Simple-Solution-With-Comments | class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
#Create An Empty Array To Store Results
arr = []
#Iterate Through First Half Of The Array(lenght of array divided by 2 or simply n)
for i in range(n):
#Add The ith element and the (n + i)th element as mentioned in problem
arr.extend([nums[i] , nums[n + i]])
#Return array
return arr | shuffle-the-array | [Python3] Simple Solution With Comments | Lolopola | 1 | 142 | shuffle the array | 1,470 | 0.885 | Easy | 21,963 |
https://leetcode.com/problems/shuffle-the-array/discuss/1137716/Python-1-line-pythonic-solution | class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
return [i for x in zip(nums[:n], nums[n:]) for i in x] | shuffle-the-array | [Python] 1 line, pythonic solution | cruim | 1 | 226 | shuffle the array | 1,470 | 0.885 | Easy | 21,964 |
https://leetcode.com/problems/shuffle-the-array/discuss/1121331/Python3-O(n)-Time-and-O(1)-Cyclic-Sort | class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
def translate (i, n):
'''
i: idx
n: elements n
Ret: new idx(new location) after shuffle
'''
if i < n:
return 2 * i
else:
return 2 * i - 2 *n + 1
if len(nums) <= 2:
return nums
for i in range (0,len(nums)):
j = i
while (nums[i] > 0):
j = translate (j,n)
# Mark the numbers that are at their right location negative
nums[i], nums[j] = nums[j], -nums[i]
i += 1
for i in range (0,len(nums)):
nums[i] = abs(nums[i])
return nums | shuffle-the-array | Python3 O(n) Time and O(1) Cyclic Sort | IsabelleWan | 1 | 282 | shuffle the array | 1,470 | 0.885 | Easy | 21,965 |
https://leetcode.com/problems/shuffle-the-array/discuss/739178/Python3-One-Line-Solution-%3A-Faster-than-99-Better-Memory-Usage-than-100 | class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
return [x for i,j in zip(nums[:n], nums[n:]) for x in (i,j)] | shuffle-the-array | [Python3] One Line Solution : Faster than 99% Better Memory Usage than 100% | mihirverma | 1 | 221 | shuffle the array | 1,470 | 0.885 | Easy | 21,966 |
https://leetcode.com/problems/shuffle-the-array/discuss/674424/Python3-1-line | class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
return sum([[nums[i], nums[n+i]] for i in range(n)], []) | shuffle-the-array | [Python3] 1-line | ye15 | 1 | 79 | shuffle the array | 1,470 | 0.885 | Easy | 21,967 |
https://leetcode.com/problems/shuffle-the-array/discuss/674406/PythonPython3-Shuffle-the-Array | class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
a = [nums[x] for x in range(n)] #O(n)
b = [nums[y] for y in range(n,2*n)] #O(n)
nums = []
for x,y in zip(a,b): #O(n)
nums.extend([x,y])
return nums | shuffle-the-array | [Python/Python3] Shuffle the Array | newborncoder | 1 | 394 | shuffle the array | 1,470 | 0.885 | Easy | 21,968 |
https://leetcode.com/problems/shuffle-the-array/discuss/674406/PythonPython3-Shuffle-the-Array | class Solution:
def shuffle(self, nums, n):
result = []
for x in range(n):
result.append(nums[x])
result.append(nums[x+n])
return result | shuffle-the-array | [Python/Python3] Shuffle the Array | newborncoder | 1 | 394 | shuffle the array | 1,470 | 0.885 | Easy | 21,969 |
https://leetcode.com/problems/shuffle-the-array/discuss/2839534/Solution | class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
ar1 = nums[0:n]
ar2 = nums[n:]
ar3 = []
for i in range(n):
ar3.append(ar1[i])
ar3.append(ar2[i])
return ar3
"""
for i ,j in zip(ar1,ar2):
ar3.append(i)
ar3.append(j)
""" | shuffle-the-array | Solution | N1xnonymous | 0 | 2 | shuffle the array | 1,470 | 0.885 | Easy | 21,970 |
https://leetcode.com/problems/shuffle-the-array/discuss/2806348/solution | class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
a=[]
for i in range(n):
a.append(nums[i])
a.append(nums[n+i])
return a | shuffle-the-array | solution | gowdavidwan2003 | 0 | 2 | shuffle the array | 1,470 | 0.885 | Easy | 21,971 |
https://leetcode.com/problems/shuffle-the-array/discuss/2800842/PYTHON3-BEST | class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
res = []
for i, j in zip(nums[:n],nums[n:]):
res += [i,j]
return res | shuffle-the-array | PYTHON3 BEST | Gurugubelli_Anil | 0 | 4 | shuffle the array | 1,470 | 0.885 | Easy | 21,972 |
https://leetcode.com/problems/shuffle-the-array/discuss/2800110/Python-Solution-using-2-pointer-approach | class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
x = 0
y = n
output_array = []
while x < len(nums) and y < len(nums):
output_array.append(nums[x])
output_array.append(nums[y])
x += 1
y += 1
return output_array | shuffle-the-array | Python Solution using 2 pointer approach | arvish_29 | 0 | 4 | shuffle the array | 1,470 | 0.885 | Easy | 21,973 |
https://leetcode.com/problems/shuffle-the-array/discuss/2782428/Python-in-place-solution%3A-no-binary-manipulation | class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
mask = 10000
for i in range(n, 2*n):
nums[i] = nums[i - n] * mask + nums[i]
j = n
for i in range(0, 2*n, 2):
nums[i] = nums[j] // mask
nums[i + 1] = nums[j] % mask
j += 1
return nums | shuffle-the-array | Python in-place solution: no binary manipulation | StacyAceIt | 0 | 5 | shuffle the array | 1,470 | 0.885 | Easy | 21,974 |
https://leetcode.com/problems/shuffle-the-array/discuss/2778738/Python-or-LeetCode-or-1470.-Shuffle-the-Array | class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
list1 = []
for i in range(n):
list1.append(nums[i])
list1.append(nums[i + n])
return list1 | shuffle-the-array | Python | LeetCode | 1470. Shuffle the Array | UzbekDasturchisiman | 0 | 6 | shuffle the array | 1,470 | 0.885 | Easy | 21,975 |
https://leetcode.com/problems/shuffle-the-array/discuss/2778738/Python-or-LeetCode-or-1470.-Shuffle-the-Array | class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
list1 = []
for i in range(n):
list1.extend([nums[i], nums[i + n]])
return list1 | shuffle-the-array | Python | LeetCode | 1470. Shuffle the Array | UzbekDasturchisiman | 0 | 6 | shuffle the array | 1,470 | 0.885 | Easy | 21,976 |
https://leetcode.com/problems/shuffle-the-array/discuss/2756920/PYTHON-oror-EASY-SOLUTION | class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
a=nums[:n]
b=nums[n:]
i=0
l=[]
while i<n:
l.append(a[i])
l.append(b[i])
i+=1
return l | shuffle-the-array | PYTHON || EASY SOLUTION | tush18 | 0 | 5 | shuffle the array | 1,470 | 0.885 | Easy | 21,977 |
https://leetcode.com/problems/shuffle-the-array/discuss/2737307/Python-One-Linear | class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
return sum([nums[i::n] for i in range(n)], []) | shuffle-the-array | Python One Linear | RogerGabeller-ml | 0 | 4 | shuffle the array | 1,470 | 0.885 | Easy | 21,978 |
https://leetcode.com/problems/shuffle-the-array/discuss/2732177/99.96-faster-and-very-easy-solution-using-python | class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
x = nums[0: n]
y = nums[n:]
res = []
for i in range(len(x)):
res += [x[i], y[i]]
return res | shuffle-the-array | 99.96% faster and very easy solution using python | ankurbhambri | 0 | 9 | shuffle the array | 1,470 | 0.885 | Easy | 21,979 |
https://leetcode.com/problems/shuffle-the-array/discuss/2729694/easy-approach-using-python | class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
l1=nums[:n]
l2=nums[n:]
nl=[]
for i in range(0,n):
nl.append(l1[i])
nl.append(l2[i])
return nl | shuffle-the-array | easy approach using python | sindhu_300 | 0 | 3 | shuffle the array | 1,470 | 0.885 | Easy | 21,980 |
https://leetcode.com/problems/shuffle-the-array/discuss/2663763/Python3-93-faster-with-explanation | class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
nNums = []
for i in range(int(len(nums)/2)):
nNums.append(nums[i])
nNums.append(nums[i+ n])
return nNums | shuffle-the-array | Python3, 93% faster with explanation | cvelazquez322 | 0 | 44 | shuffle the array | 1,470 | 0.885 | Easy | 21,981 |
https://leetcode.com/problems/shuffle-the-array/discuss/2625211/Python-solution-91.13-faster | class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
li = []
for i, j in zip(nums[:n], nums[n:]):
li.append(i)
li.append(j)
return li | shuffle-the-array | Python solution 91.13% faster | samanehghafouri | 0 | 22 | shuffle the array | 1,470 | 0.885 | Easy | 21,982 |
https://leetcode.com/problems/shuffle-the-array/discuss/2536067/Pyhton3-Solution-oror-Easy-and-Understandable-oror-Faster | class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
x = nums[0:n]
y = nums[n:]
final = []
for i in range(0,n):
final.append(x[i])
final.append(y[i])
return final | shuffle-the-array | Pyhton3 Solution || Easy & Understandable || Faster | shashank_shashi | 0 | 35 | shuffle the array | 1,470 | 0.885 | Easy | 21,983 |
https://leetcode.com/problems/shuffle-the-array/discuss/2452340/Python-or-itertools-or-One-liner | class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
return list(chain.from_iterable((nums[i], nums[i+n]) for i in range(n))) | shuffle-the-array | Python | itertools | One-liner | Wartem | 0 | 58 | shuffle the array | 1,470 | 0.885 | Easy | 21,984 |
https://leetcode.com/problems/shuffle-the-array/discuss/2441909/Two-Python3-Solutions-with-Explanations | class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
'''Time complexity: Olog(n / 2)'''
ret = []
# Split the list according to n
# Iterate through each element in each list with zip and append them to a new list
for x, y in zip(nums[:n], nums[n:]):
ret.extend([x , y])
return ret | shuffle-the-array | Two Python3 Solutions with Explanations | romejj | 0 | 88 | shuffle the array | 1,470 | 0.885 | Easy | 21,985 |
https://leetcode.com/problems/shuffle-the-array/discuss/2441909/Two-Python3-Solutions-with-Explanations | class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
'''Time complexity: Olog(n as specified in the arg), Space complexity: O(1)'''
# To manage space, we can work on the same variable (i.e. modifying in place)
# We can iterate n times, while popping the last element and inserting in its right position in the same list
for i in range(n, 0, -1):
nums.insert(i, nums.pop())
return nums | shuffle-the-array | Two Python3 Solutions with Explanations | romejj | 0 | 88 | shuffle the array | 1,470 | 0.885 | Easy | 21,986 |
https://leetcode.com/problems/the-k-strongest-values-in-an-array/discuss/2516738/easy-python-solution | class Solution:
def getStrongest(self, arr: List[int], k: int) -> List[int]:
new_arr = []
arr.sort()
med = arr[int((len(arr) - 1)//2)]
for num in arr :
new_arr.append([int(abs(num - med)), num])
new_arr = sorted(new_arr, key = lambda x : (x[0], x[1]))
output, counter = [], 0
for i in reversed(range(len(new_arr))) :
output.append(new_arr[i][1])
counter += 1
if counter == k :
return output
return output | the-k-strongest-values-in-an-array | easy python solution | sghorai | 0 | 15 | the k strongest values in an array | 1,471 | 0.602 | Medium | 21,987 |
https://leetcode.com/problems/the-k-strongest-values-in-an-array/discuss/2111379/python-3-oror-easy-two-pointer-solution | class Solution:
def getStrongest(self, arr: List[int], k: int) -> List[int]:
arr.sort()
n = len(arr)
median = arr[(n - 1) // 2]
res = []
left, right = 0, n - 1
for _ in range(k):
if median - arr[left] > arr[right] - median:
res.append(arr[left])
left += 1
else:
res.append(arr[right])
right -= 1
return res | the-k-strongest-values-in-an-array | python 3 || easy two pointer solution | dereky4 | 0 | 27 | the k strongest values in an array | 1,471 | 0.602 | Medium | 21,988 |
https://leetcode.com/problems/the-k-strongest-values-in-an-array/discuss/1441816/Python3-solution-O(NlogN) | class Solution:
def getStrongest(self, arr: List[int], k: int) -> List[int]:
z = sorted(arr)
n = len(arr)
median = (n-1)//2
i = 0
j = n-1
res = []
while len(res) != k:
if z[j]-z[median] > z[median]-z[i] or (z[j]-z[median] == z[median]-z[i] and z[j] >= z[i]):
res.append(z[j])
j -= 1
elif z[j]-z[median] < z[median]-z[i] or (z[j]-z[median] == z[median]-z[i] and z[j] < z[i]):
res.append(z[i])
i += 1
return res | the-k-strongest-values-in-an-array | Python3 solution O(NlogN) | EklavyaJoshi | 0 | 35 | the k strongest values in an array | 1,471 | 0.602 | Medium | 21,989 |
https://leetcode.com/problems/the-k-strongest-values-in-an-array/discuss/1008685/Intuitive-approach-by-sorting-tuple-(abs(e-m)-e) | class Solution:
def getStrongest(self, arr: List[int], k: int) -> List[int]:
arr, arr_len = sorted(arr), len(arr)
m = arr[int((arr_len-1)/2)]
# Pickup top k tuple
# arr = [1,2,3,4,5] -> ss_list = [(2, 5), (2, 1), (1, 4), (1, 2), (0, 3)]
# ss_list[:k] = [(2, 5), (2, 1)]
ss_list = list(sorted(map(lambda e: (abs(e-m), e), arr), reverse=True))[:k]
# Pickup the element
# ss_list -> [5, 1]
ss_list = list(map(lambda t: t[1], ss_list))
return ss_list | the-k-strongest-values-in-an-array | Intuitive approach by sorting tuple (abs(e-m), e) | puremonkey2001 | 0 | 35 | the k strongest values in an array | 1,471 | 0.602 | Medium | 21,990 |
https://leetcode.com/problems/the-k-strongest-values-in-an-array/discuss/676328/Python-Beat-Both-100-Two-pointers | class Solution:
def getStrongest(self, arr: List[int], k: int) -> List[int]:
list.sort(arr)
m = len(arr) // 2 if len(arr) % 2 == 1 else len(arr) // 2 - 1
mv = arr[m]
l = 0
r = 0
cnt = 0
ans = []
while cnt < k:
if abs(arr[-1-r] - mv) >= abs(arr[l] - mv):
ans.append(arr[-1-r])
r += 1
else:
ans.append(arr[l])
l += 1
cnt += 1
return ans | the-k-strongest-values-in-an-array | [Python Beat Both 100%] Two pointers | q463746583 | 0 | 27 | the k strongest values in an array | 1,471 | 0.602 | Medium | 21,991 |
https://leetcode.com/problems/the-k-strongest-values-in-an-array/discuss/674494/Python3-two-pointers | class Solution:
def getStrongest(self, arr: List[int], k: int) -> List[int]:
arr.sort()
m = arr[(len(arr)-1)//2]
ans, lo, hi = [], 0, len(arr)-1
while len(ans) < k:
if m - arr[lo] > arr[hi] - m:
ans.append(arr[lo])
lo += 1
else:
ans.append(arr[hi])
hi -= 1
return ans | the-k-strongest-values-in-an-array | [Python3] two pointers | ye15 | 0 | 14 | the k strongest values in an array | 1,471 | 0.602 | Medium | 21,992 |
https://leetcode.com/problems/the-k-strongest-values-in-an-array/discuss/1701639/Python-simple-O(n)-time-O(1)-extra-space-two-pointers-solution | class Solution:
def getStrongest(self, arr: List[int], k: int) -> List[int]:
n = len(arr)
if n == 1:
return arr[:k]
elif n == k:
return arr
arr.sort()
m = arr[(n-1)//2]
res = []
i, j = 0, n-1
while i < j:
if abs(arr[i]-m) > abs(arr[j]-m):
res.append(arr[i])
i += 1
elif abs(arr[i]-m) < abs(arr[j]-m):
res.append(arr[j])
j -= 1
else: # abs(arr[i]-m) == abs(arr[j]-m)
if arr[i] > arr[j]:
res.append(arr[i])
i += 1
elif arr[i] < arr[j]:
res.append(arr[j])
j -= 1
else:
res.append(arr[i])
i += 1
if len(res) == k:
return res | the-k-strongest-values-in-an-array | Python simple O(n) time, O(1) extra space two-pointers solution | byuns9334 | -1 | 70 | the k strongest values in an array | 1,471 | 0.602 | Medium | 21,993 |
https://leetcode.com/problems/paint-house-iii/discuss/1397505/Explained-Commented-Top-Down-greater-Bottom-Up-greater-Space-Optimized-Bottom-Up | class Solution:
def minCost1(self, houses: List[int], cost: List[List[int]], R: int, C: int, target: int) -> int:
# think as if we are traveling downward
# at any point, if switch our column then (target--)
@functools.cache
def dp(x,y,k): # O(100*20*100) time space
if x == R:
return 0 if k == 0 else math.inf
elif k <= 0:
return math.inf
# if this house is already colored, dont recolor!!
if houses[x] > 0 and houses[x] != y+1: return math.inf
cur_cost = 0 if houses[x] == y+1 else cost[x][y]
# now try all columns! O(20) time
res = math.inf
for c in range(C):
if c == y:
res = min(res, cur_cost + dp(x+1,c,k))
else:
res = min(res, cur_cost + dp(x+1,c,k-1))
# print('dp',x,y,k,'=',res)
return res
ans = min(dp(0,y,target) for y in range(C))
return -1 if ans == math.inf else ans | paint-house-iii | Explained Commented Top Down -> Bottom Up -> Space Optimized Bottom Up | yozaam | 3 | 257 | paint house iii | 1,473 | 0.619 | Hard | 21,994 |
https://leetcode.com/problems/paint-house-iii/discuss/697430/python3-bottom-up-dp-solution | class Solution:
def minCost(self, houses: List[int], cost: List[List[int]], m: int, n: int, target: int) -> int:
# dp_values[i][j][k] records the min costs that we have k+1 neighbors
# in the first i houses and the ith house is painted with j
dp_values = [[[float('inf')]*target for _ in range(n)] for _ in range(m)]
# initial values
if houses[0] != 0:
dp_values[0][houses[0]-1][0] = 0
else:
for i in range(n):
dp_values[0][i][0] = cost[0][i]
for i in range(1, m):
for j in range(n):
# houses[i] is painted. we only consider when j == houses[i]
if houses[i] != 0 and j != houses[i]-1:
continue
for k in range(target):
# for i houses, we can't have more than i neighbors
if k > i:
break
if houses[i-1] != 0:
if j == houses[i-1]-1:
dp_values[i][j][k] = dp_values[i-1][j][k]
else:
# if k == 0, it makes no sense to consider the case that current
# house color is different from the previous house's color.
if k > 0:
dp_values[i][j][k] = dp_values[i-1][houses[i-1]-1][k-1]
else:
min_with_diff_color = float('inf')
if k > 0:
for w in range(n):
if w == j:
continue
min_with_diff_color = min(min_with_diff_color, dp_values[i-1][w][k-1])
dp_values[i][j][k] = min(min_with_diff_color, dp_values[i-1][j][k])
# if the house is not painted, we need extra cost
if houses[i] == 0:
dp_values[i][j][k] += cost[i][j]
costs = float('inf')
for j in range(n):
costs = min(costs, dp_values[m-1][j][target-1])
return costs if costs != float('inf') else -1 | paint-house-iii | [python3] bottom up dp solution | ytb_algorithm | 2 | 150 | paint house iii | 1,473 | 0.619 | Hard | 21,995 |
https://leetcode.com/problems/paint-house-iii/discuss/675630/Python3-top-down-dp-with-comments | class Solution:
def minCost(self, houses: List[int], cost: List[List[int]], m: int, n: int, target: int) -> int:
@lru_cache(None)
def fn(i, j, k):
"""Return total cost of painting 0-ith house
j - (j+1)st color
k - k neighborhoods
"""
if i < 0: return 0 #$0 cost before painting any house
if k <= 0 or k > i+1: return inf #impossible to have neighborhoods <= 0 or more than houses
if houses[i] and houses[i] != j+1: return inf #invalid if houses[i] is already painted with a different color
prev = min(fn(i-1, j, k), min(fn(i-1, jj, k-1) for jj in range(n) if jj != j)) #cost of painting houses[:i]
return prev + (0 if houses[i] else cost[i][j]) #cost of painting houses[:i+1]
ans = min(fn(m-1, j, target) for j in range(n)) #minimum cost of painting houses[:m]
return ans if ans < inf else -1 | paint-house-iii | [Python3] top-down dp with comments | ye15 | 2 | 51 | paint house iii | 1,473 | 0.619 | Hard | 21,996 |
https://leetcode.com/problems/paint-house-iii/discuss/2256258/Cleanest-Python3-Solution-%2B-Explanation-%2B-Complexity-Analysis-Top-Down-DP | class Solution:
def minCost(self, houses: List[int], cost: List[List[int]], _: int, colors: int, target: int) -> int:
@cache
def dfs(index, last_color, neighborhoods):
if index == len(houses):
return 0 if neighborhoods == target else float('inf')
if neighborhoods > target:
return float('inf')
# this house needs to be painted
if houses[index] == 0:
result = float('inf')
for c in range(1, colors + 1):
result = min(result, dfs(index + 1, c, neighborhoods + (c != last_color)) + cost[index][c-1])
return result
# this house is already painted
return dfs(index + 1, houses[index], neighborhoods + (houses[index] != last_color))
result = dfs(0, 0, 0)
return result if result != float('inf') else -1 | paint-house-iii | Cleanest Python3 Solution + Explanation + Complexity Analysis / Top-Down DP | code-art | 1 | 67 | paint house iii | 1,473 | 0.619 | Hard | 21,997 |
https://leetcode.com/problems/paint-house-iii/discuss/2255762/Simple-Python-DP-solution | class Solution:
def minCost(self, houses: List[int], cost: List[List[int]], H: int, C: int, target: int) -> int:
dp={}
inf=math.inf
def finder(i,last_color,neigh):
if i==H:
if neigh==target:
return 0
return inf
if neigh>target:
return inf
if (i,last_color,neigh) in dp:
return dp[(i,last_color,neigh)]
if houses[i]==0:
ans=inf
for current_color in range(1,C+1):
if last_color==current_color:
ans= min(ans,finder(i+1,last_color,neigh)+cost[i][current_color-1])
else:
ans= min(ans,finder(i+1,current_color,neigh+1)+cost[i][current_color-1])
dp[(i,last_color,neigh)]=ans
return ans
else:
ans=None
if last_color==houses[i]:
ans= finder(i+1,last_color,neigh)
else:
ans= finder(i+1,houses[i],neigh+1)
dp[(i,last_color,neigh)]=ans
return ans
ans=finder(0,0,0)
if ans>=inf:
return -1
return ans | paint-house-iii | Simple Python DP solution | franzgoerlich | 1 | 105 | paint house iii | 1,473 | 0.619 | Hard | 21,998 |
https://leetcode.com/problems/paint-house-iii/discuss/1567950/python-solution-easy-recursive-with-memoization | class Solution:
def minCost(self, houses: List[int], cost: List[List[int]], m: int, n: int, target: int) -> int:
@lru_cache(None)
def rec(i, k, last):
if i == 0:
return int(k != 0) * 10**9
if k == -1 or i < k:
return 10**9
if houses[i-1] == 0:
temp = 10**9
for v in range(1, n+1):
if v == last:
temp = min(temp, rec(i-1, k, last) + cost[i-1][last-1])
else:
temp = min(temp, rec(i-1, k-1, v) + cost[i-1][v-1])
return temp
if last == houses[i-1]:
return rec(i-1, k, last)
return rec(i-1, k-1, houses[i-1])
z = rec(m, target, -1)
return -1 if z >= 10**9 else z | paint-house-iii | python solution easy recursive with memoization | ashish_chiks | 1 | 176 | paint house iii | 1,473 | 0.619 | Hard | 21,999 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.