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-candies-allocated-to-k-children/discuss/1929691/2-Python-Solutions-oror-Binary-Search | class Solution:
def maximumCandies(self, C: List[int], k: int) -> int:
lo=0 ; hi=sum(C)//k
while lo<hi:
mid=(lo+hi)//2+1
if sum(c//mid for c in C)>=k: lo=mid
else: hi=mid-1
return lo | maximum-candies-allocated-to-k-children | 2 Python Solutions || Binary Search | Taha-C | 1 | 138 | maximum candies allocated to k children | 2,226 | 0.361 | Medium | 30,900 |
https://leetcode.com/problems/maximum-candies-allocated-to-k-children/discuss/1929691/2-Python-Solutions-oror-Binary-Search | class Solution:
def maximumCandies(self, C: List[int], k: int) -> int:
return bisect_left(range(1,sum(C)//k+1), True, key=lambda x:sum(c//x for c in C)<k) | maximum-candies-allocated-to-k-children | 2 Python Solutions || Binary Search | Taha-C | 1 | 138 | maximum candies allocated to k children | 2,226 | 0.361 | Medium | 30,901 |
https://leetcode.com/problems/maximum-candies-allocated-to-k-children/discuss/1908845/Easy-Python-Binary-Search | class Solution:
def maximumCandies(self, candies: List[int], k: int) -> int:
l, r = 1, max(candies)
while l <= r:
m = (l + r)//2
if self.countPile(candies, m) >= k:
if self.countPile(candies, m + 1) < k: return m
l = m + 1
else:
r = m - 1
return 0
def countPile(self, candies, pileSize):
return sum(candy//pileSize for candy in candies) | maximum-candies-allocated-to-k-children | Easy Python Binary Search | trungnguyen276 | 1 | 91 | maximum candies allocated to k children | 2,226 | 0.361 | Medium | 30,902 |
https://leetcode.com/problems/maximum-candies-allocated-to-k-children/discuss/1908729/Python-Solution-with-Binary-Search-Explained | class Solution:
def maximumCandies(self, candies: List[int], k: int) -> int:
# The lower bound is 1 and higher bound is maximum value from candies.
lo, hi = 1, max(candies)
# This higher bound is not generally possible except for cases like candies = [5,5,5,5] & k = 4
res = 0 # Current maximum result
if sum(candies) < k: # If true then we cannot give even 1 candy to each child thus return 0
return 0
def cal_num_of_piles(pile_size): # Criterion function
count = 0
for c in candies:
count += c // pile_size
return count >= k
while lo <= hi: # Binary Search Algorithm
mid = (lo + hi + 1) // 2 # Expected answer
if cal_num_of_piles(mid): # Check if mid is a possible answer.
res = mid # Update the current maximum answer
lo = mid + 1 # Check ahead of mid
else:
hi = mid - 1 # Check below mid
return res | maximum-candies-allocated-to-k-children | ⭐Python Solution with Binary Search Explained | anCoderr | 1 | 76 | maximum candies allocated to k children | 2,226 | 0.361 | Medium | 30,903 |
https://leetcode.com/problems/maximum-candies-allocated-to-k-children/discuss/2826632/Python-Binary-Search%3A-Optimal-and-Clean-with-explanation-O(nlog(max(candies)))-time-%3A-O(1)-space | class Solution:
# Hint: very similar to 875. Koko Eating Bananas. binary search the solution space. left = 0, right = max(candies)
# Given a fixed number of candies each child can get, is easy to check if it is possible to allocate k piles. If possible, set left = mid. Otherwise set right = mid-1.
# O(nlog(max(candies))) time : O(1) space
def maximumCandies(self, candies: List[int], k: int) -> int:
def check(mid):
return sum(c // mid for c in candies) >= k
left, right = 0, max(candies)
while left < right:
mid = ceil(left + (right-left)/2)
if check(mid):
left = mid
else:
right = mid-1
return left | maximum-candies-allocated-to-k-children | Python Binary Search: Optimal and Clean with explanation - O(nlog(max(candies))) time : O(1) space | topswe | 0 | 4 | maximum candies allocated to k children | 2,226 | 0.361 | Medium | 30,904 |
https://leetcode.com/problems/maximum-candies-allocated-to-k-children/discuss/2766371/Python-easy-to-read-and-understand-or-binary-search | class Solution:
def split(self, candies, mid, k):
res = 0
for i in candies:
res += i//mid
return res
def maximumCandies(self, candies: List[int], k: int) -> int:
lo, hi = 1, 10**7
res = 0
while lo <= hi:
mid = (lo+hi) // 2
split = self.split(candies, mid, k)
#print(split)
if split >= k:
res = mid
lo = mid+1
else:
hi = mid-1
return res | maximum-candies-allocated-to-k-children | Python easy to read and understand | binary-search | sanial2001 | 0 | 2 | maximum candies allocated to k children | 2,226 | 0.361 | Medium | 30,905 |
https://leetcode.com/problems/maximum-candies-allocated-to-k-children/discuss/2511723/Python-Binary-Search-With-explanation | class Solution:
def maximumCandies(self, candies: List[int], k: int) -> int:
''' Each Child Can get max - max(candies) number of candies.
So we create a range of number between 1 and n.
Now Use Binary Search to pickup any number from this range and check if we
can evenly distribute it among k students.
'''
start = 1
end = max(candies)
res = 0
while start <= end:
mid = (start + end ) // 2
children = 0
for c in candies:
children += c // mid # so c can be distribute among c // mid nunber of kids.Now check the entire Array and add it up.
if children >= k: # This Means we can evenly distribute mid candies among K students. So now we should check for higher numbers
res = max(res, mid)
start = mid + 1
else:
end = mid - 1 # So the Result can't be higher. Check of the left hand side.
return res | maximum-candies-allocated-to-k-children | Python Binary Search With explanation | theReal007 | 0 | 25 | maximum candies allocated to k children | 2,226 | 0.361 | Medium | 30,906 |
https://leetcode.com/problems/maximum-candies-allocated-to-k-children/discuss/1961763/Python3-binary-search | class Solution:
def maximumCandies(self, candies: List[int], k: int) -> int:
lo, hi = 0, sum(candies)//k
while lo < hi:
mid = lo + hi + 1 >> 1
if sum(x//mid for x in candies) >= k: lo = mid
else: hi = mid - 1
return lo | maximum-candies-allocated-to-k-children | [Python3] binary search | ye15 | 0 | 57 | maximum candies allocated to k children | 2,226 | 0.361 | Medium | 30,907 |
https://leetcode.com/problems/maximum-candies-allocated-to-k-children/discuss/1915569/Python-Binary-Search | class Solution:
def maximumCandies(self, candies: List[int], k: int) -> int:
def helper(x):
ans = 0
for i in range(len(candies)):
ans+=candies[i]//x
return ans>=k
low , high = 0,max(candies)
while low<high:
mid = high-(high-low)//2
if helper(mid):
low = mid
else:
high = mid-1
return low | maximum-candies-allocated-to-k-children | Python Binary Search | Brillianttyagi | 0 | 35 | maximum candies allocated to k children | 2,226 | 0.361 | Medium | 30,908 |
https://leetcode.com/problems/maximum-candies-allocated-to-k-children/discuss/1909199/Python3-Easy-BinarySearch-Solution | class Solution:
def maximumCandies(self, candies: List[int], k: int) -> int:
total = sum(candies)
if total // k == 0:
return 0
l, r = 1, total//k
def check(mid):
cnt = 0
for x in candies:
cnt += x//mid
return cnt >= k
while l <= r:
mid = (l+r)//2
if check(mid):
l = mid + 1
else:
r = mid - 1
return r | maximum-candies-allocated-to-k-children | [Python3] Easy BinarySearch Solution | nightybear | 0 | 24 | maximum candies allocated to k children | 2,226 | 0.361 | Medium | 30,909 |
https://leetcode.com/problems/maximum-candies-allocated-to-k-children/discuss/1909124/Binarysearch-or-With-Explaination | class Solution:
def maximumCandies(self, candies: List[int], k: int) -> int:
def isPossible(m):
cnt = 0
for cand in candies:
cnt += cand // limit
return cnt >= k
lo, hi = 1, max(candies)
best = 0
while lo <= hi:
mi = (lo + hi) >> 1
if isPossible(mi):
best = mi
lo = mi + 1
else:
hi = mi - 1
return best | maximum-candies-allocated-to-k-children | Binarysearch | With Explaination | mrunankmistry52 | 0 | 25 | maximum candies allocated to k children | 2,226 | 0.361 | Medium | 30,910 |
https://leetcode.com/problems/maximum-candies-allocated-to-k-children/discuss/1908843/Python-or-Easy-Binary-Search | class Solution:
def maximumCandies(self, candies: List[int], k: int) -> int:
s = sum(candies)
n = len(candies)
if k > s:
return 0
if k == s:
return 1
max_candies = s // k
left = 1
right = max_candies
answer = 0
while left <= right:
num = 0
mid = left + (right - left) // 2
for candy in candies:
num += candy // mid
if num >= k:
answer = max(answer, mid)
left = mid + 1
elif num < k:
right = mid -1
return answer | maximum-candies-allocated-to-k-children | Python | Easy Binary Search | Mikey98 | 0 | 19 | maximum candies allocated to k children | 2,226 | 0.361 | Medium | 30,911 |
https://leetcode.com/problems/maximum-candies-allocated-to-k-children/discuss/1908757/Python-binary-search-with-comment | class Solution:
def maximumCandies(self, candies: List[int], k: int) -> int:
if sum(candies) < k:
return 0
hi = sum(candies) // k
lo = 1 # Because sum(candies) >= k, kids can gain at least 1 candy
def can_allo(candies, num, k): # To determine whether candies can be allocate to at least k piles when pile == num
count = 0
for c in candies:
count += c // num
return count >= k
while hi > lo: # binary search until hi == lo
mid = (hi + lo) // 2
if can_allo(candies, mid, k):
lo = mid + 1
else:
hi = mid
if can_allo(candies, hi, k): # if hi can be allocated: just return hi
return hi
else:
return hi - 1 # else: it must be hi - 1 | maximum-candies-allocated-to-k-children | Python binary search with comment | byroncharly3 | 0 | 19 | maximum candies allocated to k children | 2,226 | 0.361 | Medium | 30,912 |
https://leetcode.com/problems/largest-number-after-digit-swaps-by-parity/discuss/1931017/Python-Solution-using-Sorting | class Solution:
def largestInteger(self, num: int):
n = len(str(num))
arr = [int(i) for i in str(num)]
odd, even = [], []
for i in arr:
if i % 2 == 0:
even.append(i)
else:
odd.append(i)
odd.sort()
even.sort()
res = 0
for i in range(n):
if arr[i] % 2 == 0:
res = res*10 + even.pop()
else:
res = res*10 + odd.pop()
return res | largest-number-after-digit-swaps-by-parity | Python Solution using Sorting | anCoderr | 17 | 1,500 | largest number after digit swaps by parity | 2,231 | 0.605 | Easy | 30,913 |
https://leetcode.com/problems/largest-number-after-digit-swaps-by-parity/discuss/1979472/Python-3-greater-Easy-to-understand-code | class Solution:
def largestInteger(self, num: int) -> int:
oddHeap = []
evenHeap = []
evenParity = []
while num>0:
rem = num % 10
num = num // 10
if rem%2 == 0:
heapq.heappush(evenHeap, -rem)
evenParity.append(True)
else:
heapq.heappush(oddHeap, -rem)
evenParity.append(False)
return self.constructNum(evenHeap, oddHeap, reversed(evenParity))
def constructNum(self, evenHeap, oddHeap, evenParity):
result = 0
for parity in evenParity:
if parity:
result = result * 10 + (-heapq.heappop(evenHeap))
else:
result = result * 10 + (-heapq.heappop(oddHeap))
return result | largest-number-after-digit-swaps-by-parity | Python 3 -> Easy to understand code | mybuddy29 | 1 | 91 | largest number after digit swaps by parity | 2,231 | 0.605 | Easy | 30,914 |
https://leetcode.com/problems/largest-number-after-digit-swaps-by-parity/discuss/1934822/Python-or-Sort-or-4-lines | class Solution:
def largestInteger(self, num: int) -> int:
digits = list(map(int, str(num)))
evens = sorted(x for x in digits if x % 2 == 0)
odds = sorted(x for x in digits if x % 2 == 1)
return ''.join(str(odds.pop() if x&1 else evens.pop()) for x in digits) | largest-number-after-digit-swaps-by-parity | Python | Sort | 4 lines | leeteatsleep | 1 | 121 | largest number after digit swaps by parity | 2,231 | 0.605 | Easy | 30,915 |
https://leetcode.com/problems/largest-number-after-digit-swaps-by-parity/discuss/2842795/Python-or-clean-or-sort | class Solution:
def largestInteger(self, num: int) -> int:
lst = [int(i) for i in str(num)]
p = [[], []]
for i, v in enumerate(lst):
j = v & 1
p[j].append(v)
lst[i] = j
for i in p:
i.sort()
ret = 0
for j in lst:
ret = ret * 10 + p[j].pop()
return ret | largest-number-after-digit-swaps-by-parity | Python | clean | sort | Aaron1991 | 0 | 1 | largest number after digit swaps by parity | 2,231 | 0.605 | Easy | 30,916 |
https://leetcode.com/problems/largest-number-after-digit-swaps-by-parity/discuss/2779608/python-heap | class Solution:
def largestInteger(self, num: int) -> int:
heap_odd, heap_even, res = [], [], []
for n in str(num):
heappush(heap_even, -int(n)) if int(n) % 2 == 0 else heappush(heap_odd, -int(n))
for n in str(num):
res.append(str(-heappop(heap_even))) if int(n) % 2 == 0 else res.append(str(-heappop(heap_odd)))
return int(''.join(res)) | largest-number-after-digit-swaps-by-parity | python heap | JasonDecode | 0 | 2 | largest number after digit swaps by parity | 2,231 | 0.605 | Easy | 30,917 |
https://leetcode.com/problems/largest-number-after-digit-swaps-by-parity/discuss/2311126/Python3-sort-and-reconstruct | class Solution:
def largestInteger(self, num: int) -> int:
odd = []
even = []
for x in map(int, str(num)):
if x & 1: odd.append(x)
else: even.append(x)
odd.sort()
even.sort()
ans = 0
for x in map(int, str(num)):
if x & 1: ans = 10*ans + odd.pop()
else: ans = 10*ans + even.pop()
return ans | largest-number-after-digit-swaps-by-parity | [Python3] sort & reconstruct | ye15 | 0 | 39 | largest number after digit swaps by parity | 2,231 | 0.605 | Easy | 30,918 |
https://leetcode.com/problems/largest-number-after-digit-swaps-by-parity/discuss/2127779/Python3-in-place-Solution-easily-explained. | class Solution:
def largestInteger(self, num: int) -> int:
# so first we identify even and odd digits and store them in lists even[] & odd[]
# then we sort even & odd lists so the largest even/odd digit is at the last [-1]the index
# then we go through our given num(which we typecast into list) and see if the digit is
# even, we swap that digit by poping the last largest digit from even list and we do the
# same when we see a odd digit. Lastly we join each element into a str and return the
# int object of num. That's it.
odd = []
even = []
num = str(num)
for n in num:
if int(n)%2 == 0:
even.append(n)
else:
odd.append(n)
even.sort()
odd.sort()
num = list(num)
for i in range(len(num)):
if int(num[i])%2 == 0:
num[i] = even.pop()
else:
num[i] = odd.pop()
return int("".join(num)) | largest-number-after-digit-swaps-by-parity | Python3 in-place Solution, easily explained. | shubhamdraj | 0 | 158 | largest number after digit swaps by parity | 2,231 | 0.605 | Easy | 30,919 |
https://leetcode.com/problems/largest-number-after-digit-swaps-by-parity/discuss/2120146/Python-oror-Easy-Approach | class Solution:
def largestInteger(self, num: int) -> int:
numlst = list(map(int, str(num)))
print(numlst)
length_num = len(str(num)) - 1
index_even = []
value_even = []
index_odd = []
value_odd = []
for i, val in enumerate(numlst):
if val%2 == 0:
print(val%2)
index_even.append(length_num - i)
value_even.append(val)
else:
index_odd.append(length_num - i)
value_odd.append(val)
index_even.sort(reverse=True)
value_even.sort(reverse=True)
index_odd.sort(reverse=True)
value_odd.sort(reverse=True)
print(index_even)
print(value_even)
print(index_odd)
print(value_odd)
sum = 0
for i in range(len(index_odd)):
sum += pow(10, index_odd[i]) * value_odd[i]
for i in range(len(index_even)):
sum += pow(10, index_even[i]) * value_even[i]
return sum | largest-number-after-digit-swaps-by-parity | ✅Python || Easy Approach | chuhonghao01 | 0 | 62 | largest number after digit swaps by parity | 2,231 | 0.605 | Easy | 30,920 |
https://leetcode.com/problems/largest-number-after-digit-swaps-by-parity/discuss/2025144/self-explained-Python-Solution%3A-O(NlogN) | class Solution:
def largestInteger(self, num: int) -> int:
is_odd = lambda char:int(char)%2
s = str(num)
odd = sorted([x for x in s if is_odd(x)])
even = sorted([x for x in s if not is_odd(x)])
res = [odd.pop() if is_odd(char) else even.pop() for char in s]
return int(''.join(res)) | largest-number-after-digit-swaps-by-parity | self-explained Python Solution: O(NlogN) | XiangyangShi | 0 | 71 | largest number after digit swaps by parity | 2,231 | 0.605 | Easy | 30,921 |
https://leetcode.com/problems/largest-number-after-digit-swaps-by-parity/discuss/1950650/Python-Fast-Solution-Memory-Less-Than-99.16 | class Solution:
def largestInteger(self, num: int) -> int:
num, even, odd, s = str(num), [], [], ""
for i in num:
if int(i) & 1:
odd.append(str(i))
else:
even.append(str(i))
even.sort(reverse = True)
odd.sort(reverse = True)
i, j = 0, 0
for e in num:
if int(e) & 1:
s += odd[i]
i += 1
else:
s += even[j]
j += 1
return int(s) | largest-number-after-digit-swaps-by-parity | Python Fast Solution, Memory Less Than 99.16% | Hejita | 0 | 119 | largest number after digit swaps by parity | 2,231 | 0.605 | Easy | 30,922 |
https://leetcode.com/problems/largest-number-after-digit-swaps-by-parity/discuss/1950548/Python3-code | class Solution:
def largestInteger(self, num: int) -> int:
# converting into string given num
s = str(num)
odd_arr = [] # List for storing odd value
even_arr = [] # List for storing even value
for ele in s:
temp = int(ele) # converting each element into int
if temp%2 == 0:
even_arr.append(temp)
else:
odd_arr.append(temp)
odd_arr.sort() # sorting of odd_arr
odd_arr.reverse() # reversing of odd_arr
even_arr.sort() # sorting of even_arr
even_arr.reverse() # reversing of even_arr
i = 0
j = 0
ans = ''
for k in range(len(s)):
temp = int(s[k]) # converting of string into int
if temp%2:
ans = ans + str(odd_arr[i])
i += 1
else:
ans = ans + str(even_arr[j])
j += 1
return int(ans) | largest-number-after-digit-swaps-by-parity | Python3 code | COEIT_1903480130037 | 0 | 37 | largest number after digit swaps by parity | 2,231 | 0.605 | Easy | 30,923 |
https://leetcode.com/problems/largest-number-after-digit-swaps-by-parity/discuss/1938805/Easy-Python-Solution-oror-99-Faster-oror-Memory-less-than-80 | class Solution:
def largestInteger(self, num: int) -> int:
num=str(num) ; e=0 ; o=0
evens=sorted([d for d in num if int(d)%2==0], reverse=True)
odds= sorted([d for d in num if int(d)%2==1], reverse=True)
for i in range(len(num)):
if int(num[i])%2==0: num=num[:i]+evens[e]+num[i+1:] ; e+=1
else: num=num[:i]+odds[o]+num[i+1:] ; o+=1
return num | largest-number-after-digit-swaps-by-parity | Easy Python Solution || 99% Faster || Memory less than 80% | Taha-C | 0 | 41 | largest number after digit swaps by parity | 2,231 | 0.605 | Easy | 30,924 |
https://leetcode.com/problems/largest-number-after-digit-swaps-by-parity/discuss/1938805/Easy-Python-Solution-oror-99-Faster-oror-Memory-less-than-80 | class Solution:
def largestInteger(self, num: int) -> int:
num=list(map(int, str(num)))
evens=sorted([d for d in num if not d%2]) ; odds= sorted([d for d in num if d%2])
return ''.join(str(odds.pop() if d%2 else evens.pop()) for d in num) | largest-number-after-digit-swaps-by-parity | Easy Python Solution || 99% Faster || Memory less than 80% | Taha-C | 0 | 41 | largest number after digit swaps by parity | 2,231 | 0.605 | Easy | 30,925 |
https://leetcode.com/problems/largest-number-after-digit-swaps-by-parity/discuss/1932998/Python3-solution-using-sorting-O(nlogn) | class Solution:
def largestInteger(self, num: int) -> int:
# convert the number to list to make it easy to work with.
num = list(map(int, str(num)))
# init two arrays to separate even and odd digits
# the space for this is limited by number of digits so we can also replace it with count array
evens = []
odds = []
for x in num:
if x & 1:
odds.append(x)
else:
evens.append(x)
# sort both the arrays
odds.sort()
evens.sort()
# create the new number
res = 0
for x in num:
if x & 1:
res = res * 10 + odds.pop()
else:
res = res * 10 + evens.pop()
return res | largest-number-after-digit-swaps-by-parity | Python3 solution using sorting - O(nlogn) | constantine786 | 0 | 17 | largest number after digit swaps by parity | 2,231 | 0.605 | Easy | 30,926 |
https://leetcode.com/problems/largest-number-after-digit-swaps-by-parity/discuss/1931364/Python-*NO-SORTING*.-Time%3A-O(log-num)-Space%3A-O(1) | class Solution:
def largestInteger(self, num: int) -> int:
count = [0] * 10
n = num
while n:
n, d = divmod(n, 10)
count[d] += 1
n = num
result = 0
even = 0
odd = 1
factor = 1
while n:
n, d = divmod(n, 10)
idx = odd if d % 2 else even
while count[idx] == 0:
idx += 2
result += factor*idx
count[idx] -= 1
factor *= 10
return result | largest-number-after-digit-swaps-by-parity | Python, *NO SORTING*. Time: O(log num), Space: O(1) | blue_sky5 | 0 | 26 | largest number after digit swaps by parity | 2,231 | 0.605 | Easy | 30,927 |
https://leetcode.com/problems/largest-number-after-digit-swaps-by-parity/discuss/1931311/python-%3A-using-sort-odd-and-even | class Solution:
def largestInteger(self, num: int) -> int:
index = 0
odd = []
even = []
eachIsEven = []
n = num
while True:
r = n % 10
if r % 2 == 0 :
eachIsEven.append(1)
even.append(r)
else :
eachIsEven.append(0)
odd.append(r)
# print(n)
if n < 10:
break
n = n // 10
# print(eachIsEven)
even.sort()
odd.sort()
# print(even)
# print(odd)
ansList = []
s = 0
for v in reversed(eachIsEven):
# print(v)
if v == 1 : # even
s = s*10 + even.pop()
else :
s = s*10 + odd.pop()
return s | largest-number-after-digit-swaps-by-parity | python : using sort odd and even | cheoljoo | 0 | 20 | largest number after digit swaps by parity | 2,231 | 0.605 | Easy | 30,928 |
https://leetcode.com/problems/largest-number-after-digit-swaps-by-parity/discuss/1931057/Python-or-Easy-Understanding | class Solution:
def largestInteger(self, num: int) -> int:
arr = [n for n in str(num)]
n = len(arr)
for i in range(n):
for j in range(i+1, n):
if int(arr[i]) % 2 == 0 and int(arr[j]) % 2 == 0 and int(arr[j]) > int(arr[i]):
arr[i], arr[j] = arr[j], arr[i]
elif int(arr[i]) % 2 == 1 and int(arr[j]) % 2 == 1 and int(arr[j]) > int(arr[i]):
arr[i], arr[j] = arr[j], arr[i]
return int("".join(arr)) | largest-number-after-digit-swaps-by-parity | Python | Easy Understanding | Mikey98 | 0 | 39 | largest number after digit swaps by parity | 2,231 | 0.605 | Easy | 30,929 |
https://leetcode.com/problems/minimize-result-by-adding-parentheses-to-expression/discuss/1931004/Python-Solution-using-2-Pointers-Brute-Force | class Solution:
def minimizeResult(self, expression: str) -> str:
plus_index, n, ans = expression.find('+'), len(expression), [float(inf),expression]
def evaluate(exps: str):
return eval(exps.replace('(','*(').replace(')', ')*').lstrip('*').rstrip('*'))
for l in range(plus_index):
for r in range(plus_index+1, n):
exps = f'{expression[:l]}({expression[l:plus_index]}+{expression[plus_index+1:r+1]}){expression[r+1:n]}'
res = evaluate(exps)
if ans[0] > res:
ans[0], ans[1] = res, exps
return ans[1] | minimize-result-by-adding-parentheses-to-expression | Python Solution using 2 Pointers Brute Force | anCoderr | 12 | 1,500 | minimize result by adding parentheses to expression | 2,232 | 0.651 | Medium | 30,930 |
https://leetcode.com/problems/minimize-result-by-adding-parentheses-to-expression/discuss/2808647/Python-Brute-Force | class Solution:
def minimizeResult(self, expression: str) -> str:
nums = expression.split('+')
m, n = len(nums[0]), len(nums[1])
min_val = math.inf
for i in range(m):
for j in range(1, n+1):
left = int(nums[0][:m-1-i]) if m-1-i > 0 else 1
right = int(nums[1][j:]) if j < n else 1
val = (int(nums[0][m-1-i:]) + int(nums[1][:j])) * left * right
if val < min_val:
res = nums[0][:m-1-i] + '(' + nums[0][m-1-i:] + '+' + nums[1][:j] + ')' + nums[1][j:]
min_val = val
return res | minimize-result-by-adding-parentheses-to-expression | Python Brute Force | satoshinakamoto2 | 0 | 6 | minimize result by adding parentheses to expression | 2,232 | 0.651 | Medium | 30,931 |
https://leetcode.com/problems/minimize-result-by-adding-parentheses-to-expression/discuss/2805247/Python-Straightforward-Beats-70 | class Solution:
def minimizeResult(self, expression: str) -> str:
[num1, num2] = expression.split('+')
min_exp, min_val = '', float('inf')
for i in range(len(num1)):
for j in range(1,len(num2)+1):
new_exp = num1[:i] + '(' + num1[i:] + '+' + num2[:j] + ')' + num2[j:]
new_val = 1
if len(num1[:i])>0:
new_val = int(num1[:i])
new_val = new_val * (int(num1[i:]) + int(num2[:j]))
if len(num2[j:])>0:
new_val = new_val * int(num2[j:])
if new_val < min_val:
min_val = new_val
min_exp = new_exp
return min_exp | minimize-result-by-adding-parentheses-to-expression | Python - Straightforward - Beats 70% | zahrash | 0 | 17 | minimize result by adding parentheses to expression | 2,232 | 0.651 | Medium | 30,932 |
https://leetcode.com/problems/minimize-result-by-adding-parentheses-to-expression/discuss/2791337/Very-simple-Python-solution. | class Solution:
def minimizeResult(self, expression: str) -> str:
plusIndex = expression.find("+")
mn = int(expression[0:plusIndex]) + int(expression[plusIndex + 1:])
ans = "(" + expression + ")"
for leftIndex in range(0, plusIndex):
for rightIndex in range(plusIndex + 1, len(expression)):
midVal = int(expression[leftIndex: plusIndex]) + int(expression[plusIndex + 1: rightIndex + 1])
leftVal = int(expression[0: leftIndex]) if leftIndex > 0 else 1
rightVal = int(expression[rightIndex+1:]) if rightIndex + 1 < len(expression) else 1
if leftVal * midVal * rightVal < mn:
mn = leftVal * midVal * rightVal
ans = expression[0:leftIndex] + "(" + expression[leftIndex: rightIndex + 1] + ")" + expression[rightIndex+1: ]
return ans | minimize-result-by-adding-parentheses-to-expression | Very simple Python solution. | ananth360 | 0 | 12 | minimize result by adding parentheses to expression | 2,232 | 0.651 | Medium | 30,933 |
https://leetcode.com/problems/minimize-result-by-adding-parentheses-to-expression/discuss/2495977/Best-Python3-implementation-(Top-98.8)-oror-Easy-to-understand | class Solution:
def minimizeResult(self, expression: str) -> str:
plus_index, n, ans = expression.find('+'), len(expression), [float(inf),expression]
def evaluate(exps: str):
return eval(exps.replace('(','*(').replace(')', ')*').lstrip('*').rstrip('*'))
for l in range(plus_index):
for r in range(plus_index+1, n):
exps = f'{expression[:l]}({expression[l:plus_index]}+{expression[plus_index+1:r+1]}){expression[r+1:n]}'
res = evaluate(exps)
if ans[0] > res:
ans[0], ans[1] = res, exps
return ans[1] | minimize-result-by-adding-parentheses-to-expression | ✔️ Best Python3 implementation (Top 98.8%) || Easy to understand | explusar | 0 | 86 | minimize result by adding parentheses to expression | 2,232 | 0.651 | Medium | 30,934 |
https://leetcode.com/problems/minimize-result-by-adding-parentheses-to-expression/discuss/2353007/Python3-brute-force | class Solution:
# Splits expression into four numeric components (as strings)
def splitExpr(self, expression, i, j, idx):
return expression[:i], expression[i:idx], expression[idx+1:j+1], expression[j+1:]
# Given expression components as strings, return val of expression
def getExprVal(self, a, b, c, d):
a,b,c,d = map(lambda x: 1 if not x else int(x), [a,b,c,d])
return a*(b+c)*d
# Build result string given expression components
def buildStr(self, a, b, c, d):
return ''.join([a,'(',b,'+',c,')',d])
# Enumerate all possible parantheses combinations and return min
def minimizeResult(self, expression: str) -> str:
idx, min_, res = expression.find('+'), float('inf'), ''
for i in range(idx):
for j in range(idx+1, len(expression)):
a,b,c,d = self.splitExpr(expression, i, j, idx)
cur = self.getExprVal(a,b,c,d)
if cur < min_:
min_ = cur
res = self.buildStr(a,b,c,d)
return res | minimize-result-by-adding-parentheses-to-expression | Python3 brute force | mxmb | 0 | 51 | minimize result by adding parentheses to expression | 2,232 | 0.651 | Medium | 30,935 |
https://leetcode.com/problems/minimize-result-by-adding-parentheses-to-expression/discuss/2311193/Python3-brute-force | class Solution:
def minimizeResult(self, expression: str) -> str:
k = expression.find('+')
ans = "inf"
for i in range(k):
for j in range(k+1, len(expression)):
cand = f'{expression[:i]}({expression[i:k]}+{expression[k+1:j+1]}){expression[j+1:]}'
ans = min(ans, cand, key=lambda x: eval(x.replace('(', '*(').replace(')', ')*').strip('*')))
return ans | minimize-result-by-adding-parentheses-to-expression | [Python3] brute-force | ye15 | 0 | 36 | minimize result by adding parentheses to expression | 2,232 | 0.651 | Medium | 30,936 |
https://leetcode.com/problems/minimize-result-by-adding-parentheses-to-expression/discuss/1939412/Two-loops-to-generate-4-values-77-speed | class Solution:
def minimizeResult(self, expression: str) -> str:
left, right = expression.split("+")
min_val = int(left) + int(right)
min_exp = f"({left}+{right})"
len_left, len_right1 = len(left), len(right) + 1
for i in range(len_left):
a, b = left[:i], left[i:]
val_a = int(a) if a else 1
val_b = int(b)
for j in range(1, len_right1):
c, d = right[:j], right[j:]
val_c = int(c)
val_d = int(d) if d else 1
val = val_a * (val_b + val_c) * val_d
if val < min_val:
min_val = val
min_exp = f"{a}({b}+{c}){d}"
return min_exp | minimize-result-by-adding-parentheses-to-expression | Two loops to generate 4 values, 77% speed | EvgenySH | 0 | 43 | minimize result by adding parentheses to expression | 2,232 | 0.651 | Medium | 30,937 |
https://leetcode.com/problems/minimize-result-by-adding-parentheses-to-expression/discuss/1939253/7-Lines-Python-Solution-oror-99-Faster-oror-Memory-less-than-85 | class Solution:
def minimizeResult(self, E: str) -> str:
idx=E.index('+') ; L=E[:idx] ; R=E[idx+1:] ; ans=[]
for i in range(len(L)):
for j in range(1,len(R)+1):
sm=(int(L[:i]) if L[:i] else 1)*((int(L[i:]) if L[i:] else 0)+(int(R[:j]) if R[:j] else 0))*(int(R[j:]) if R[j:] else 1)
exp=L[:i]+'('+L[i:]+'+'+R[:j]+')'+R[j:]
ans.append([sm, exp])
return sorted(ans, key=lambda x:x[0])[0][1] | minimize-result-by-adding-parentheses-to-expression | 7-Lines Python Solution || 99% Faster || Memory less than 85% | Taha-C | 0 | 81 | minimize result by adding parentheses to expression | 2,232 | 0.651 | Medium | 30,938 |
https://leetcode.com/problems/minimize-result-by-adding-parentheses-to-expression/discuss/1939253/7-Lines-Python-Solution-oror-99-Faster-oror-Memory-less-than-85 | class Solution:
def minimizeResult(self, E: str) -> str:
idx=E.index('+') ; L=E[:idx] ; R=E[idx+1:] ; ans=[float(inf),E]
for i in range(len(L)):
for j in range(1,len(R)+1):
sm=(int(L[:i]) if L[:i] else 1)*((int(L[i:]) if L[i:] else 0)+(int(R[:j]) if R[:j] else 0))*(int(R[j:]) if R[j:] else 1)
exp=L[:i]+'('+L[i:]+'+'+R[:j]+')'+R[j:]
if sm<ans[0]: ans[0],ans[1]=sm,exp
return ans[1] | minimize-result-by-adding-parentheses-to-expression | 7-Lines Python Solution || 99% Faster || Memory less than 85% | Taha-C | 0 | 81 | minimize result by adding parentheses to expression | 2,232 | 0.651 | Medium | 30,939 |
https://leetcode.com/problems/minimize-result-by-adding-parentheses-to-expression/discuss/1936150/Python3-oror-Solution-using-precalculated-combinations-(Beats-~90) | class Solution:
def minimizeResult(self, expression: str) -> str:
mid = expression.index('+')
length = len(expression)
# calculate combinations for first and second number - O(n)
num1_pairs = [(expression[:i], expression[i:mid]) for i in range(mid)]
num2_pairs = [(expression[mid + 1:i], expression[i:]) for i in range(length, mid + 1, -1)]
# define a variable to track the minimum and its associated indices for combinations
minimum = (float('inf'), 0, length - 1)
# go through all combinations - O(n ** 2)
for i, num1_pair in enumerate(num1_pairs):
for j, num2_pair in enumerate(num2_pairs):
res = (1 if i == 0 else int(num1_pair[0])) * (int(num1_pair[1]) + int(num2_pair[0])) * (
1 if j == 0 else int(num2_pair[1]))
if res < minimum[0]:
minimum = (res, i, j)
# retrieve the indices for combinations with minimum result
i = minimum[1]
j = minimum[2]
return num1_pairs[i][0] + '(' + num1_pairs[i][1] + '+' + num2_pairs[j][0] + ')' + num2_pairs[j][1] | minimize-result-by-adding-parentheses-to-expression | Python3 || Solution using precalculated combinations (Beats ~90%) | constantine786 | 0 | 28 | minimize result by adding parentheses to expression | 2,232 | 0.651 | Medium | 30,940 |
https://leetcode.com/problems/minimize-result-by-adding-parentheses-to-expression/discuss/1936014/Python-3-or-stack-solution-runtime-36ms-(beat-90) | class Solution:
def minimizeResult(self, expression: str) -> str:
res = {}
addPos = expression.index('+')
for i in range(len(expression)):
if i >= addPos: break
for j in range(i+1, len(expression)):
if j <= addPos: continue
newEx = expression[:i]+'('+expression[i:j+1]+')'+expression[j+1:]
ans = self.calculate(newEx)
res[ans] = newEx
return res[min(res)]
def str2int(self, arr):
return int(''.join([str(ch) for ch in arr]))
def calculate(self, ex):
digits = []
mulStack = []
addStack = []
i = 0
L = len(ex)
while i < L:
c = ex[i]
if c.isdigit():
digits.append(c)
else:
if c == '(':
if digits:
mulStack.append(self.str2int(digits))
digits = []
subAddStack = []
subDigits = []
j = i+1
while ex[j] != ')':
if ex[j].isdigit():
subDigits.append(ex[j])
else: # +
thisNum = self.str2int(subDigits)
subAddStack.append(thisNum)
subDigits = []
j += 1
if subDigits:
subAddStack.append(self.str2int(subDigits))
num = sum(subAddStack)
mulStack.append(num)
i = j
elif c == '+':
num = 1
if digits:
num = self.str2int(digits)
digits = []
if mulStack:
for p in mulStack:
num *= p
mulStack = []
addStack.append(num)
i += 1
if not digits and not mulStack: return sum(addStack)
num = 1
if digits:
num = self.str2int(digits)
digits = []
if mulStack:
for p in mulStack:
num *= p
mulStack = []
addStack.append(num)
return sum(addStack) | minimize-result-by-adding-parentheses-to-expression | Python 3 | stack solution, runtime 36ms (beat 90%) | elainefaith0314 | 0 | 38 | minimize result by adding parentheses to expression | 2,232 | 0.651 | Medium | 30,941 |
https://leetcode.com/problems/minimize-result-by-adding-parentheses-to-expression/discuss/1932268/python3-Recursion-solution-for-reference | class Solution:
def minimizeResult(self, expression: str) -> str:
ans = float('inf')
retvalue = ""
def backtrack(left, exp, right):
nonlocal retvalue
nonlocal ans
if exp[0] == '+' or exp[-1] == '+':
return 0
op = exp.split('+')
value = (left if left else 1)*(right if right else 1)*(int(op[0]) + int(op[1]))
if value < ans:
retvalue = (str(left) if left else "") + '(' + exp + ')' + (str(right) if right else "")
ans = value
backtrack((left*10)+int(exp[0]), exp[1:], right)
backtrack(left, exp[:-1], (int(exp[-1])*(10**(len(str(right))))+right) if right else int(exp[-1]))
backtrack(0, expression, 0)
return retvalue | minimize-result-by-adding-parentheses-to-expression | [python3] Recursion solution for reference | vadhri_venkat | 0 | 27 | minimize result by adding parentheses to expression | 2,232 | 0.651 | Medium | 30,942 |
https://leetcode.com/problems/minimize-result-by-adding-parentheses-to-expression/discuss/1932255/PYTHON-easy-to-understand-with-comments | class Solution:
def minimizeResult(self, expression: str) -> str:
#find the idx of "+"
pivot = None
for i in range(len(expression)):
if expression[i] == "+":
pivot = i
#calculate separately.
# "1(2+3)4": part1, part2 = 1, 2+3)4
# part3, part4 = 2+3, 4
def calculator(s):
part1, part2 = s.split("(")[0], s.split("(")[1]
part3, part4 = part2.split(")")[0], part2.split(")")[1]
num1, num2 = part3.split("+")
res = int(num1) + int(num2)
res *= int(part1) if part1 != "" else 1
res *= int(part4) if part4 != "" else 1
return res
#create all possible expressions with "()"
minvalue = inf
n = len(expression)
res = ''
for i in range(pivot):
for j in range(pivot+2, n+1):
curexp = expression[:i] + "(" + expression[i:pivot+1]
curexp += (expression[pivot+1:j] + ")" + expression[j:])
value = calculator(curexp)
if minvalue > value:
res = curexp
minvalue = value
return res | minimize-result-by-adding-parentheses-to-expression | [PYTHON] easy to understand with comments | lru_Iris | 0 | 23 | minimize result by adding parentheses to expression | 2,232 | 0.651 | Medium | 30,943 |
https://leetcode.com/problems/minimize-result-by-adding-parentheses-to-expression/discuss/1931812/Python-3-Recursion-oror-String-Manipulation | class Solution:
def minimizeResult(self, expression: str) -> str:
pos = {} #hashmap to store products
n = len(expression)
def helper(start, end, plus, n):
#base cases, 'end' can be maximum n as closing parentheses could be at the end
if start < 0 or end >= n + 1:
return
firstNum = int(expression[start : plus]) #extract first num before '+'
secondNum = int(expression[plus + 1 : end]) # extract second num after '+'
s = firstNum + secondNum #add them because they would be inside the parenthesis
a = int(expression[ : start]) if expression[ : start] != "" else 1 #extract number before opening parentheses
c = int(expression[end : ]) if expression[end : ] != "" else 1 #extract number after closing parentheses
prod = a * s * c #multiply
pos[prod] = (start, end) #store the result with index values
helper(start - 1, end, plus, n) #recur for (start - 1, end)
helper(start, end + 1, plus, n) #recur for (start + 1, end)
#finding the '+' sign in the string
i = 0
for i in range(len(expression)):
if expression[i] == '+':
break
k = i # storing index of '+' in k
helper(k - 1, k + 2, k, n) # start = k - 1 because opening parentheses will be just before k - 1 index element initally,
#end = k + 2 because closing parentheses is just before k + 2 index element initally
start, end = pos[min(pos)]
expression = expression[ : start] + '(' + expression[start : end] + ')' + expression[end : ]
return expression | minimize-result-by-adding-parentheses-to-expression | [Python 3] Recursion || String Manipulation | Aditya380 | 0 | 33 | minimize result by adding parentheses to expression | 2,232 | 0.651 | Medium | 30,944 |
https://leetcode.com/problems/minimize-result-by-adding-parentheses-to-expression/discuss/1931397/python-Runtime%3A-35-ms-(left-part-of-parenthese-right-part-of-parenthese-first-1-or-not) | class Solution:
def minimizeResult(self, expression: str) -> str:
a = expression.split('+')
# print(a)
l = int(a[0])
r = int(a[1])
ll = [(1,l,1)]
start = 1
remain = 1
origin = l
while l :
remain = origin % (10**start)
l = origin // (10**start)
if l == 0:
break
ll.append((l,remain,0))
start += 1
# print(ll)
rr = [(r,1,1)]
start = 1
remain = 1
origin = r
while r :
remain = origin % (10**start)
r = origin // (10**start)
start += 1
if r == 0:
break
rr.append((r,remain,0))
# print(rr)
mn = math.inf
s = ""
for (vll,vlr,lstart) in ll:
for (vrl,vrr,rstart) in rr:
n = vll * (vlr + vrl) * vrr
if mn > n :
mn = n
s = ""
if lstart != 1:
s += str(vll)
s += "(" + str(vlr) + "+" + str(vrl) + ")"
if rstart != 1:
s += str(vrr)
return s | minimize-result-by-adding-parentheses-to-expression | python Runtime: 35 ms - (left part of parenthese , right part of parenthese , first 1 or not) | cheoljoo | 0 | 31 | minimize result by adding parentheses to expression | 2,232 | 0.651 | Medium | 30,945 |
https://leetcode.com/problems/minimize-result-by-adding-parentheses-to-expression/discuss/1931073/Python-or-Easy-to-understand | class Solution:
def minimizeResult(self, expression: str) -> str:
int1, int2 = expression.split('+')
arr1, tmp1 = [char for char in int1], [char for char in int1]
arr2, tmp2 = [char for char in int2], [char for char in int2]
min_res = int(int1) + int(int2)
res = '(' + expression + ')'
first_limit = len(int1)
sec_limit = len(int2)
for i in range(0, first_limit):
for j in range(1, sec_limit + 1):
if i == 0 and j != sec_limit:
cur_res = (int(int1[i:]) + int(int2[:j])) * int(int2[j:])
elif i != 0 and j == sec_limit:
cur_res = int(int1[:i]) * (int(int1[i:]) + int(int2[:j]))
elif i == 0 and j == sec_limit:
continue
else:
cur_res = int(int1[:i]) * (int(int1[i:]) + int(int2[:j])) * int(int2[j:])
if cur_res < min_res:
min_res = cur_res
arr1.insert(i, '(')
arr2.insert(j, ')')
res = "".join(arr1) + '+' + "".join(arr2)
arr1 = tmp1[:]
arr2 = tmp2[:]
return res | minimize-result-by-adding-parentheses-to-expression | Python | Easy to understand | Mikey98 | 0 | 59 | minimize result by adding parentheses to expression | 2,232 | 0.651 | Medium | 30,946 |
https://leetcode.com/problems/maximum-product-after-k-increments/discuss/1930986/Python-Solution-using-Min-Heap | class Solution:
def maximumProduct(self, nums: List[int], k: int) -> int:
heap = nums.copy()
heapify(heap)
for i in range(k):
t = heappop(heap)
heappush(heap, t + 1)
ans = 1
mod = 1000000007
for i in heap:
ans = (ans*i) % mod
return ans | maximum-product-after-k-increments | ➡️Python Solution using Min Heap | anCoderr | 2 | 150 | maximum product after k increments | 2,233 | 0.413 | Medium | 30,947 |
https://leetcode.com/problems/maximum-product-after-k-increments/discuss/2311224/Python3-semi-math-greedy-solution | class Solution:
def maximumProduct(self, nums: List[int], k: int) -> int:
mod = 1_000_000_007
nums.sort()
for i, x in enumerate(nums):
target = nums[i+1] if i+1 < len(nums) else inf
diff = (target-x) * (i+1)
if diff <= k: k -= diff
else: break
q, r = divmod(k, i+1)
ans = pow(x+q+1, r, mod) * pow(x+q, i+1-r, mod) % mod
for ii in range(i+1, len(nums)):
ans = ans * nums[ii] % mod
return ans | maximum-product-after-k-increments | [Python3] semi-math greedy solution | ye15 | 1 | 11 | maximum product after k increments | 2,233 | 0.413 | Medium | 30,948 |
https://leetcode.com/problems/maximum-product-after-k-increments/discuss/1931079/Python-3-Using-SortedList-or-Priority-Queue | class Solution:
def maximumProduct(self, nums: List[int], k: int) -> int:
from sortedcontainers import SortedList
if len(nums) == 1:
return nums[0]+k
arr = SortedList(nums)
while k > 0:
el = arr[0]
arr.discard(el)
arr.add(el+1)
k -= 1
product = 1
for num in arr:
product *= num
product = product%(10**9+7)
return product%(10**9+7) | maximum-product-after-k-increments | [Python 3] - ✅✅ Using SortedList or Priority Queue | hari19041 | 1 | 86 | maximum product after k increments | 2,233 | 0.413 | Medium | 30,949 |
https://leetcode.com/problems/maximum-product-after-k-increments/discuss/2798146/Python-or-O(N)-linear-or-independent-of-k-or-Explanation | class Solution:
def maximumProduct(self, nums: List[int], k: int) -> int:
nums = sorted(nums)
cum_sum = 0
i = 0
n = len(nums)
# iterate from smallest to largest nums and stop when the void until that point can hold k units of water
while True:
cum_sum += nums[i]
if i + 1 < n:
# v = max water supported | nums[i + 1] * (i + 1) = volume | cum_sum is volume already taken
v = nums[i + 1] * (i + 1) - cum_sum
if k <= v: # water can fill in the available space
break
else: # case where water fills up over the max num
v = nums[i] * (i + 1) - cum_sum
break
i += 1
mod = int(10**9) + 7
op = 1
# since here we add discrete units of water, we must have a base water level and residual can be added over few bins
min_val = (cum_sum + k) // (i + 1)
residual = (cum_sum + k) % (i + 1)
# compute product for water sections
for j in range(i + 1):
op = (op * (min_val + (j < residual))) % mod
# compute product for remaining sections
if k <= v:
for j in range(i + 1, n):
op = (op * nums[j]) % mod
return op | maximum-product-after-k-increments | Python | O(N) - linear | independent of k | Explanation | g_priya | 0 | 15 | maximum product after k increments | 2,233 | 0.413 | Medium | 30,950 |
https://leetcode.com/problems/maximum-product-after-k-increments/discuss/2345359/Python-easy-to-read-and-understand-or-heap | class Solution:
def maximumProduct(self, nums: List[int], k: int) -> int:
pq = []
for num in nums:
heapq.heappush(pq, num)
while k > 0:
val = heapq.heappop(pq)
heapq.heappush(pq, val+1)
k -= 1
ans = 1
while pq:
ans = ans*heapq.heappop(pq) % (10**9 + 7)
return ans | maximum-product-after-k-increments | Python easy to read and understand | heap | sanial2001 | 0 | 47 | maximum product after k increments | 2,233 | 0.413 | Medium | 30,951 |
https://leetcode.com/problems/maximum-product-after-k-increments/discuss/1947938/python-3-oror-simple-heap-solution | class Solution:
def maximumProduct(self, nums: List[int], k: int) -> int:
heapq.heapify(nums)
for _ in range(k):
heapq.heappush(nums, heapq.heappop(nums) + 1)
product = 1
MOD = 10 ** 9 + 7
for num in nums:
product = (product * num) % MOD
return product | maximum-product-after-k-increments | python 3 || simple heap solution | dereky4 | 0 | 66 | maximum product after k increments | 2,233 | 0.413 | Medium | 30,952 |
https://leetcode.com/problems/maximum-product-after-k-increments/discuss/1940075/4-Lines-Python-Solution-oror-80-Faster-oror-Memory-less-than-50 | class Solution:
def maximumProduct(self, nums: List[int], k: int) -> int:
heapify(nums) ; ans=1
for _ in range(k): heappush(nums, heappop(nums)+1)
while len(nums)>0: x=heappop(nums) ; ans=(ans*x)%(10**9+7)
return ans | maximum-product-after-k-increments | 4-Lines Python Solution || 80% Faster || Memory less than 50% | Taha-C | 0 | 68 | maximum product after k increments | 2,233 | 0.413 | Medium | 30,953 |
https://leetcode.com/problems/maximum-product-after-k-increments/discuss/1939649/Counter-and-heap-on-the-keys-97-speed | class Solution:
def maximumProduct(self, nums: List[int], k: int) -> int:
cnt = Counter(nums)
lst = list(cnt.keys())
heapify(lst)
while k:
min_key = heappop(lst)
n_min_key = cnt[min_key]
min_increase = min(n_min_key, k)
cnt.pop(min_key)
if min_key + 1 in cnt:
cnt[min_key + 1] += min_increase
else:
cnt[min_key + 1] = min_increase
heappush(lst, min_key + 1)
if min_increase < n_min_key:
cnt[min_key] = n_min_key - min_increase
heappush(lst, min_key)
k -= min_increase
ans = 1
for key, n in cnt.items():
for _ in range(n):
ans *= key
ans %= 1_000_000_007
return ans | maximum-product-after-k-increments | Counter and heap on the keys, 97% speed | EvgenySH | 0 | 24 | maximum product after k increments | 2,233 | 0.413 | Medium | 30,954 |
https://leetcode.com/problems/maximum-product-after-k-increments/discuss/1933035/Python3-oror-Solution-using-Min-Heap | class Solution:
def maximumProduct(self, nums: List[int], k: int) -> int:
heapq.heapify(nums)
MOD = 10 ** 9 + 7 # just to fix the overflow and get the desired output
while k:
popped = heapq.heappop(nums)
popped +=1
k -=1
heapq.heappush(nums, popped)
return reduce(lambda x,y:( x * y) % MOD, nums) | maximum-product-after-k-increments | Python3 || Solution using Min-Heap | constantine786 | 0 | 18 | maximum product after k increments | 2,233 | 0.413 | Medium | 30,955 |
https://leetcode.com/problems/maximum-product-after-k-increments/discuss/1936744/2-Sols-oror-O(n)-and-O(n-log-n)-oror-Beginner-Friendly | class Solution:
def maximumProduct(self, nums: List[int], k: int) -> int:
heapify(nums) #heapify the nums
m=1000000007
p=1
while k:
a=heappop(nums) # pop the smallest element
heappush(nums, a+1) # increase the smallest number by 1 and push it in heap
k-=1 # decrease k by 1
while nums:
p=p*heappop(nums)%m # use modulus here to avoid TLE
return p | maximum-product-after-k-increments | 2 Sols || O(n) and O(n log n) || Beginner Friendly | ashu_py22 | -1 | 13 | maximum product after k increments | 2,233 | 0.413 | Medium | 30,956 |
https://leetcode.com/problems/maximum-product-after-k-increments/discuss/1936744/2-Sols-oror-O(n)-and-O(n-log-n)-oror-Beginner-Friendly | class Solution:
def maximumProduct(self, nums: List[int], k: int) -> int:
count=Counter(nums) # Get the frequencies of each element
a=min(count.keys()) # Start with minimum key
m=1000000007
p=1 # To store the answer
while k:
c=count[a]
if c<=k:
count[a]-=c # Reduce it by the number of times the smallest element is encountered
count[a+1]+=c # Inrease the count by the same magnitude
if count[a]==0: # Check if current numbers count reduces to zero
a+=1 # If yes then move onto next minimum number
k-=c # reduce k
continue
if c>k: # if count of the smallest element is greater than the number of operations k then
count[a]-=k # reduce the count of the smallest number by k
count[a+1]+=k # increase the count of smallest_num+1 by k
k=0 # and reduce k to zero
for key, val in count.items():
if val: # if val of keys is greater than 0 then use them in result
p=p*(key**val)%m #Use modulus to reduce the run time
return p | maximum-product-after-k-increments | 2 Sols || O(n) and O(n log n) || Beginner Friendly | ashu_py22 | -1 | 13 | maximum product after k increments | 2,233 | 0.413 | Medium | 30,957 |
https://leetcode.com/problems/maximum-total-beauty-of-the-gardens/discuss/2313576/Python3-2-pointer | class Solution:
def maximumBeauty(self, flowers: List[int], newFlowers: int, target: int, full: int, partial: int) -> int:
flowers = sorted(min(target, x) for x in flowers)
prefix = [0]
ii = -1
for i in range(len(flowers)):
if flowers[i] < target: ii = i
if i: prefix.append(prefix[-1] + (flowers[i]-flowers[i-1])*i)
ans = 0
for k in range(len(flowers)+1):
if k: newFlowers -= target - flowers[-k]
if newFlowers >= 0:
while 0 <= ii and (ii+k >= len(flowers) or prefix[ii] > newFlowers): ii -= 1
if 0 <= ii: kk = min(target-1, flowers[ii] + (newFlowers - prefix[ii])//(ii+1))
else: kk = 0
ans = max(ans, k*full + kk*partial)
return ans | maximum-total-beauty-of-the-gardens | [Python3] 2-pointer | ye15 | 1 | 61 | maximum total beauty of the gardens | 2,234 | 0.283 | Hard | 30,958 |
https://leetcode.com/problems/maximum-total-beauty-of-the-gardens/discuss/1934186/Python-3-Avoid-using-python-built-in-accumulate-function! | class Solution:
def maximumBeauty(self, flowers: List[int], newFlowers: int, target: int, full: int, partial: int) -> int:
q, q_acc = [], [0] #eligible gardens < target and its prefix sum
full_need_acc = [0] #diff to target prefix sum
ans = 0
n = len(flowers)
flowers.sort()
for f in flowers:
if f >= target:
ans += full
continue
q.append(f)
q_acc.append(q_acc[-1] + f)
for f in flowers[::-1]:
if f >= target: continue
full_need_acc.append(full_need_acc[-1] + max(0, target - f))
res = 0
for i, x in enumerate(full_need_acc):
if x > newFlowers: break
if i == len(full_need_acc) - 1:
res = max(res, i * full)
continue
l, h = flowers[0], target - 1
while l < h:
mid = l + (h - l + 1) // 2
loc = bisect.bisect_left(q, mid, lo=0, hi=len(q)-i)
if mid * loc - q_acc[loc] <= newFlowers - x:
l = mid
else:
h = mid - 1
res = max(res, i * full + l * partial)
return ans + res
``` | maximum-total-beauty-of-the-gardens | [Python 3] Avoid using python built-in accumulate function! | chestnut890123 | 0 | 30 | maximum total beauty of the gardens | 2,234 | 0.283 | Hard | 30,959 |
https://leetcode.com/problems/maximum-total-beauty-of-the-gardens/discuss/1931353/Python-Greedy-without-Binary-Search-(amortized-O(n)-after-sort) | class Solution:
def maximumBeauty(self, flowers: List[int], newFlowers: int, target: int, full: int, partial: int) -> int:
totf = 0
for i,f in enumerate(flowers):
if f>target:
flowers[i] = target
totf += min(f,target)
flowers.sort(reverse=True)
# if newFlowers can make all garden 'full'
n = len(flowers)
if n*target - totf<=newFlowers:
maxscore = n*full # score if all garden 'full'
if flowers[-1]<target: # score if all garden but one 'full'
maxscore = max(maxscore,(n-1)*full+(target-1)*partial)
return maxscore
# if newFlowers can not make all garden 'full'
tofill = 0 # no garden full, n gardens to fill
level = (totf+newFlowers) // (n-tofill) # try fill all n garden
while level<flowers[tofill]: # not plausible
totf -= flowers[tofill] # exclude the next garden
tofill += 1
level = (totf+newFlowers) // (n-tofill) # try again
maxscore = level*partial # score if no garden 'full'
for i in range(len(flowers)): # (i+1) 'garden full'
newFlowers -= target - flowers[i]
if newFlowers<0: # cannot fill any more garden
break
score = (i+1)*full # score from (i+1) 'full' garden
if tofill==i:
totf -= flowers[i]
tofill = i+1
level = (totf+newFlowers) // (n-tofill) # try fill the rest of the gardens
while level<flowers[tofill]: # not plausible
totf -= flowers[tofill] # exclude the next garden
tofill += 1
level = (totf+newFlowers) // (n-tofill)
score = score + level * partial # score from partial gardens
if score>maxscore:
maxscore = score
return maxscore | maximum-total-beauty-of-the-gardens | [Python] Greedy without Binary Search (amortized O(n) after sort) | wssx349 | 0 | 74 | maximum total beauty of the gardens | 2,234 | 0.283 | Hard | 30,960 |
https://leetcode.com/problems/add-two-integers/discuss/2670517/Solutions-in-Every-Language-*on-leetcode*-or-One-Liner | class Solution:
def sum(self, num1: int, num2: int) -> int:
return num1 + num2 | add-two-integers | Solutions in Every Language *on leetcode* | One-Liner ✅ | qing306037 | 5 | 465 | add two integers | 2,235 | 0.894 | Easy | 30,961 |
https://leetcode.com/problems/add-two-integers/discuss/2406300/or-python3-or-ONE-LINE-or-FASTER-THAN-90-or | class Solution:
def sum(self, num1: int, num2: int) -> int:
return num1+num2 | add-two-integers | ✅ | python3 | ONE LINE | FASTER THAN 90% | 🔥💪 | sahelriaz | 5 | 587 | add two integers | 2,235 | 0.894 | Easy | 30,962 |
https://leetcode.com/problems/add-two-integers/discuss/2266174/Python-Simplest-Solution-With-Explanation-or-Beg-to-adv-or-Math | class Solution:
def sum(self, num1: int, num2: int) -> int:
return num1 + num2 # as they are two intergers, we can directly use "+" operator | add-two-integers | Python Simplest Solution With Explanation | Beg to adv | Math | rlakshay14 | 4 | 674 | add two integers | 2,235 | 0.894 | Easy | 30,963 |
https://leetcode.com/problems/add-two-integers/discuss/2177301/2235.-Add-Two-Integers-Faster-than-every-solution-on-earth | class Solution:
def sum(self, num1: int, num2: int) -> int:
return num1.__add__(num2) | add-two-integers | 2235. Add Two Integers Faster than every solution on earth | anudeep_tadikamalla | 4 | 582 | add two integers | 2,235 | 0.894 | Easy | 30,964 |
https://leetcode.com/problems/add-two-integers/discuss/1986057/Java-and-Python3-oror-Bit-Manipulation-oror-beats-100 | class Solution:
def sum(self, num1: int, num2: int) -> int:
mask = 0xFFFFFFFF
if num2 == 0:
return num1 if num1 < 0x80000000 else ~(num1 ^ mask)
carry = ((num1 & num2) << 1) & mask
non_carry = (num1 ^ num2) & mask
return self.sum(non_carry,carry) | add-two-integers | Java and Python3 || Bit Manipulation || beats 100% | Sarah_Lene | 4 | 347 | add two integers | 2,235 | 0.894 | Easy | 30,965 |
https://leetcode.com/problems/add-two-integers/discuss/2157969/Python-Simple-Python-Solution | class Solution:
def sum(self, num1: int, num2: int) -> int:
return num1+num2 | add-two-integers | [ Python ] ✅✅ Simple Python Solution 🥳✌👍 | ASHOK_KUMAR_MEGHVANSHI | 2 | 580 | add two integers | 2,235 | 0.894 | Easy | 30,966 |
https://leetcode.com/problems/add-two-integers/discuss/2509792/Python-easy-way | class Solution:
def sum(self, num1: int, num2: int) -> int:
return num1 + num2 | add-two-integers | Python - easy way | xfuxad00 | 1 | 248 | add two integers | 2,235 | 0.894 | Easy | 30,967 |
https://leetcode.com/problems/add-two-integers/discuss/2115851/Difficult-solution-%3A( | class Solution:
def sum(self, num1: int, num2: int) -> int:
return num1+num2
# space O(1)
# time O(1) | add-two-integers | Difficult solution :( | mananiac | 1 | 284 | add two integers | 2,235 | 0.894 | Easy | 30,968 |
https://leetcode.com/problems/add-two-integers/discuss/1962791/Python-one-liner-%3AP | class Solution:
def sum(self, num1: int, num2: int) -> int:
return num1 + num2 | add-two-integers | Python one liner :P | alishak1999 | 1 | 265 | add two integers | 2,235 | 0.894 | Easy | 30,969 |
https://leetcode.com/problems/add-two-integers/discuss/2823686/Easy-O(1)-python-solution | class Solution:
def sum(self, num1: int, num2: int) -> int:
## Easy solution
ans = num1 + num2
return ans | add-two-integers | Easy O(1) python solution | syedsajjad62 | 0 | 6 | add two integers | 2,235 | 0.894 | Easy | 30,970 |
https://leetcode.com/problems/add-two-integers/discuss/2820475/BEST-SOLOUTIONAS-IN-LEETCODE-!!11!1!-FOR-ADVANCED-USERS | class Solution:
def sum(self, num1: int, num2: int) -> int:
arr = [num1, num2]
res = 0
for i in range(len(arr)):
res += arr[i]
return res | add-two-integers | BEST SOLOUTIONAS IN LEETCODE !!11!1! FOR ADVANCED USERS | M0ls | 0 | 4 | add two integers | 2,235 | 0.894 | Easy | 30,971 |
https://leetcode.com/problems/add-two-integers/discuss/2815403/Fastest-and-Simplest-Solution-Python-(One-Liner-Code) | class Solution:
def sum(self, num1: int, num2: int) -> int:
return num1 + num2 | add-two-integers | Fastest and Simplest Solution - Python (One-Liner Code) | PranavBhatt | 0 | 11 | add two integers | 2,235 | 0.894 | Easy | 30,972 |
https://leetcode.com/problems/add-two-integers/discuss/2795561/python-solution | class Solution:
def sum(self, num1: int, num2: int) -> int:
return num1+num2 | add-two-integers | python solution | sindhu_300 | 0 | 10 | add two integers | 2,235 | 0.894 | Easy | 30,973 |
https://leetcode.com/problems/add-two-integers/discuss/2777081/I-am-posting-my-starting-new-solution | class Solution:
def sum(self, num1: int, num2: int) -> int:
return num1+num2 | add-two-integers | I am posting my starting new solution | udaykumarkadiri933 | 0 | 5 | add two integers | 2,235 | 0.894 | Easy | 30,974 |
https://leetcode.com/problems/add-two-integers/discuss/2738806/99-decided-otherwise.-Reverse-solution | class Solution:
def sum(self, num1: int, num2: int) -> int:
return num2 + num1 | add-two-integers | 99% decided otherwise. Reverse solution 🤓 | mzv100 | 0 | 8 | add two integers | 2,235 | 0.894 | Easy | 30,975 |
https://leetcode.com/problems/add-two-integers/discuss/2624975/Python-solution-one-line | class Solution:
def sum(self, num1: int, num2: int) -> int:
return num1 + num2 | add-two-integers | Python solution one line | samanehghafouri | 0 | 108 | add two integers | 2,235 | 0.894 | Easy | 30,976 |
https://leetcode.com/problems/add-two-integers/discuss/2484085/Simple-python-code | class Solution:
def sum(self, num1: int, num2: int) -> int:
#return the sum of two numbers using + sign
return num1 + num2 | add-two-integers | Simple python code | thomanani | 0 | 217 | add two integers | 2,235 | 0.894 | Easy | 30,977 |
https://leetcode.com/problems/add-two-integers/discuss/2484085/Simple-python-code | class Solution:
def sum(self, num1: int, num2: int) -> int:
#return the sum of two numbers using sum keyword
return sum([num1,num2]) | add-two-integers | Simple python code | thomanani | 0 | 217 | add two integers | 2,235 | 0.894 | Easy | 30,978 |
https://leetcode.com/problems/add-two-integers/discuss/2465576/Python3-oror-Easy-Solution | class Solution:
def sum(self, num1: int, num2: int) -> int:
return num1+num2 | add-two-integers | Python3 || Easy Solution✔ | keertika27 | 0 | 158 | add two integers | 2,235 | 0.894 | Easy | 30,979 |
https://leetcode.com/problems/add-two-integers/discuss/2380177/Simple-Python-Solution-Faster-Than-at-Least-1 | class Solution:
def sum(self, num1: int, num2: int) -> int:
#create an array with 2 given numbers
arr = [num1,num2]
#create and fill a hashmap
woo = dict()
for i in range(len(arr)) :
woo[i] = arr[i]
#combine the array with the hasmap
result = arr + list(woo.values())
#removes duplicate items because there might be some that we dont need
result = list(dict.fromkeys(result))
#add two integers
sum = max(result) + min(result)
#return
return sum | add-two-integers | Simple Python Solution Faster Than at Least 1% | xemah | 0 | 84 | add two integers | 2,235 | 0.894 | Easy | 30,980 |
https://leetcode.com/problems/add-two-integers/discuss/2366374/Python3-solution | class Solution:
def sum(self, num1: int, num2: int) -> int:
return(num1 + num2) | add-two-integers | Python3 solution | raviair | 0 | 121 | add two integers | 2,235 | 0.894 | Easy | 30,981 |
https://leetcode.com/problems/add-two-integers/discuss/2346698/Easy-Python-One-liner | class Solution:
def sum(self, num1: int, num2: int) -> int:
return num1 + num2 | add-two-integers | ✅ Easy Python One-liner ✅ 🐍 | qing306037 | 0 | 156 | add two integers | 2,235 | 0.894 | Easy | 30,982 |
https://leetcode.com/problems/root-equals-sum-of-children/discuss/2178260/Python-oneliner | class Solution:
def checkTree(self, root: Optional[TreeNode]) -> bool:
return root.left.val+root.right.val == root.val | root-equals-sum-of-children | Python oneliner | StikS32 | 5 | 322 | root equals sum of children | 2,236 | 0.869 | Easy | 30,983 |
https://leetcode.com/problems/root-equals-sum-of-children/discuss/1938094/Python-simple-solution | class Solution:
def checkTree(self, root: Optional[TreeNode]) -> bool:
return root.val == root.left.val + root.right.val | root-equals-sum-of-children | Python simple solution | byuns9334 | 2 | 246 | root equals sum of children | 2,236 | 0.869 | Easy | 30,984 |
https://leetcode.com/problems/root-equals-sum-of-children/discuss/2260335/Python-Easy-Solution | class Solution:
def checkTree(self, root: Optional[TreeNode]) -> bool:
if root.right.val + root.left.val == root.val:
return True
else:
return False | root-equals-sum-of-children | ✅Python Easy Solution | Skiper228 | 1 | 224 | root equals sum of children | 2,236 | 0.869 | Easy | 30,985 |
https://leetcode.com/problems/root-equals-sum-of-children/discuss/2154788/Python-Easy-Beginner-Answer | class Solution:
def checkTree(self, root: Optional[TreeNode]) -> bool:
if (root.left.val + root.right.val) == root.val:
return True
return False | root-equals-sum-of-children | Python Easy Beginner Answer | itsmeparag14 | 1 | 115 | root equals sum of children | 2,236 | 0.869 | Easy | 30,986 |
https://leetcode.com/problems/root-equals-sum-of-children/discuss/1936133/Python3-One-Line-Solution | class Solution:
def checkTree(self, root: Optional[TreeNode]) -> bool:
return root.val == root.left.val + root.right.val | root-equals-sum-of-children | [Python3] One-Line Solution | terrencetang | 1 | 141 | root equals sum of children | 2,236 | 0.869 | Easy | 30,987 |
https://leetcode.com/problems/root-equals-sum-of-children/discuss/2755142/Python-Simple-Python-Solution | class Solution:
def checkTree(self, root: Optional[TreeNode]) -> bool:
if root != None:
if root.val == root.left.val + root.right.val:
return True
else:
return False
else:
return False | root-equals-sum-of-children | [ Python ] ✅✅ Simple Python Solution 🥳✌👍 | ASHOK_KUMAR_MEGHVANSHI | 0 | 37 | root equals sum of children | 2,236 | 0.869 | Easy | 30,988 |
https://leetcode.com/problems/root-equals-sum-of-children/discuss/2732522/Simple-python-code-with-explanation | class Solution:
def checkTree(self, root):
#if the value of root is equal to sum of values of it's children
if root.val == root.left.val + root.right.val:
#then return true
return True
#if not
else:
#return false
return False | root-equals-sum-of-children | Simple python code with explanation | thomanani | 0 | 2 | root equals sum of children | 2,236 | 0.869 | Easy | 30,989 |
https://leetcode.com/problems/root-equals-sum-of-children/discuss/2732494/Python-Simple-Solution-in-3-Lines-of-Code | class Solution:
def checkTree(self, root: Optional[TreeNode]) -> bool:
if root.val == root.left.val + root.right.val:
return True
return False | root-equals-sum-of-children | Python Simple Solution in 3 Lines of Code | RenKiro | 0 | 2 | root equals sum of children | 2,236 | 0.869 | Easy | 30,990 |
https://leetcode.com/problems/root-equals-sum-of-children/discuss/2668850/easy-solution | class Solution:
def checkTree(self, root: Optional[TreeNode]) -> bool:
if root.val == root.left.val+root.right.val:
return True
return False | root-equals-sum-of-children | easy solution | MaryLuz | 0 | 7 | root equals sum of children | 2,236 | 0.869 | Easy | 30,991 |
https://leetcode.com/problems/root-equals-sum-of-children/discuss/2643255/Easy-python-solution | class Solution:
def checkTree(self, root: Optional[TreeNode]) -> bool:
if not root or (not root.left and not root.right):
return True
elif root.val != (root.left.val if root.left else 0) + (root.right.val if root.right else 0):
return False
return self.checkTree(root.left) and self.checkTree(root.right) | root-equals-sum-of-children | Easy python solution | namanxk | 0 | 31 | root equals sum of children | 2,236 | 0.869 | Easy | 30,992 |
https://leetcode.com/problems/root-equals-sum-of-children/discuss/2555127/simple-python-solution | class Solution:
def checkTree(self, root: Optional[TreeNode]) -> bool:
if root.left.val + root.right.val == root.val:
return True
else:
return False | root-equals-sum-of-children | simple python solution | maschwartz5006 | 0 | 33 | root equals sum of children | 2,236 | 0.869 | Easy | 30,993 |
https://leetcode.com/problems/root-equals-sum-of-children/discuss/2498910/Python-oror-Very-easy-solution | class Solution:
def checkTree(self, root: Optional[TreeNode]) -> bool:
if root.left.val + root.right.val == root.val:
return True
return False | root-equals-sum-of-children | Python || Very easy solution | gourav14051992 | 0 | 47 | root equals sum of children | 2,236 | 0.869 | Easy | 30,994 |
https://leetcode.com/problems/root-equals-sum-of-children/discuss/2334966/Python-O(1)-solution. | class Solution:
def checkTree(self, root: Optional[TreeNode]) -> bool:
if root.left.val+root.right.val==root.val:
return True
return False | root-equals-sum-of-children | Python O(1) solution. | guneet100 | 0 | 142 | root equals sum of children | 2,236 | 0.869 | Easy | 30,995 |
https://leetcode.com/problems/root-equals-sum-of-children/discuss/2116025/Python-Easy-solution-with-complexity | class Solution:
def checkTree(self, root: Optional[TreeNode]) -> bool:
if root.left.val + root.right.val == root.val:
return True
else:
return False
# time O(1)
# space O(1) | root-equals-sum-of-children | [Python] Easy solution with complexity | mananiac | 0 | 116 | root equals sum of children | 2,236 | 0.869 | Easy | 30,996 |
https://leetcode.com/problems/root-equals-sum-of-children/discuss/2116025/Python-Easy-solution-with-complexity | class Solution:
def checkTree(self, root: Optional[TreeNode]) -> bool:
return (root.left.val + root.right.val) == root.val
# time O(1)
# space O(1) | root-equals-sum-of-children | [Python] Easy solution with complexity | mananiac | 0 | 116 | root equals sum of children | 2,236 | 0.869 | Easy | 30,997 |
https://leetcode.com/problems/find-closest-number-to-zero/discuss/1959624/Python-dollarolution | class Solution:
def findClosestNumber(self, nums: List[int]) -> int:
m = 10 ** 6
for i in nums:
x = abs(i-0)
if x < m:
m = x
val = i
elif x == m and val < i:
val = i
return val | find-closest-number-to-zero | Python $olution | AakRay | 2 | 180 | find closest number to zero | 2,239 | 0.458 | Easy | 30,998 |
https://leetcode.com/problems/find-closest-number-to-zero/discuss/2192384/Python-Solution-2-solutions | class Solution:
def findClosestNumber(self, nums: List[int]) -> int:
num=float('inf')
nums.sort()
for i in nums:
if abs(i)<=num:
num=abs(i)
c=i
return c | find-closest-number-to-zero | Python Solution 2 solutions | SakshiMore22 | 1 | 88 | find closest number to zero | 2,239 | 0.458 | Easy | 30,999 |
Subsets and Splits