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/replace-all-digits-with-characters/discuss/1661711/Python3-or-O(n)-time-complexity-or-Easy-to-Understand
|
class Solution:
def replaceDigits(self, s: str) -> str:
if not len(s):
return s
alpha_list = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
output_str = ""
for i in range(1,len(s),2): #iterate through odd number indices
output_str +=s[i-1] #get previous index ch and append to output string
curr_ch = int(s[i])
prev_ch_ind = alpha_list.index(s[i-1])
output_str += alpha_list[prev_ch_ind + curr_ch] #retrieve character by shifting previous index character by current index number
return output_str if not len(s)%2 else output_str+s[-1] #if length of string is odd, then add last chracter to output string
|
replace-all-digits-with-characters
|
Python3 | O(n) time complexity | Easy to Understand
|
Meow1303
| 0
| 78
|
replace all digits with characters
| 1,844
| 0.798
|
Easy
| 26,300
|
https://leetcode.com/problems/replace-all-digits-with-characters/discuss/1554196/EASY-AND-SIMPLE-SOLN-(faster-than-99)
|
class Solution:
def replaceDigits(self, s: str) -> str:
string,i,j = "abcdefghijklmnopqrstuvwxyz",0,1
L = list(s)
while j < len(s):
idx = string.index(s[i])
L[j] = string[idx+int(s[j])]
i += 2
j += 2
return "".join([i for i in L])
|
replace-all-digits-with-characters
|
EASY AND SIMPLE SOLN (faster than 99%)
|
anandanshul001
| 0
| 85
|
replace all digits with characters
| 1,844
| 0.798
|
Easy
| 26,301
|
https://leetcode.com/problems/replace-all-digits-with-characters/discuss/1487311/1-line-solution-in-Python
|
class Solution:
def replaceDigits(self, s: str) -> str:
return "".join(chr(ord(s[i - 1]) + int(s[i])) if i & 1 else s[i] for i in range(len(s)))
|
replace-all-digits-with-characters
|
1-line solution in Python
|
mousun224
| 0
| 94
|
replace all digits with characters
| 1,844
| 0.798
|
Easy
| 26,302
|
https://leetcode.com/problems/replace-all-digits-with-characters/discuss/1369024/Python3-ASCII-Solution
|
class Solution:
def replaceDigits(self, s: str) -> str:
retstring = ""
for i in range(0, len(s)):
if not s[i].isdigit():
retstring += s[i]
else:
prev_ascii = ord(s[i - 1])
new_ascii = prev_ascii + int(s[i])
to_letter = chr(new_ascii)
retstring += to_letter
return retstring
|
replace-all-digits-with-characters
|
Python3 ASCII Solution
|
RobertObrochta
| 0
| 120
|
replace all digits with characters
| 1,844
| 0.798
|
Easy
| 26,303
|
https://leetcode.com/problems/replace-all-digits-with-characters/discuss/1277278/Simple-Python-Solution-or-O(N)-time-or-O(N)-space
|
class Solution:
def replaceDigits(self, s: str) -> str:
def shift(d, n):
return chr(ord(d) + int(n))
answer = ""
for i in range(len(s)):
if i % 2 == 0: answer += s[i]
else: answer += shift(s[i - 1], s[i])
return answer
|
replace-all-digits-with-characters
|
Simple Python Solution | O(N) time | O(N) space
|
vanigupta20024
| 0
| 159
|
replace all digits with characters
| 1,844
| 0.798
|
Easy
| 26,304
|
https://leetcode.com/problems/replace-all-digits-with-characters/discuss/1241798/python-or-easy-solution
|
class Solution:
def replaceDigits(self, s: str) -> str:
u='abcdefghijklmnopqrstuvwxyz'
s=list(s)
for j in range(0,len(s),2):
if j+1<len(s):
s[j+1] = u[(u.index(s[j])+int(s[j+1]))%26]
return ''.join(s)
|
replace-all-digits-with-characters
|
python | easy solution
|
chikushen99
| 0
| 100
|
replace all digits with characters
| 1,844
| 0.798
|
Easy
| 26,305
|
https://leetcode.com/problems/replace-all-digits-with-characters/discuss/1236696/PYTHON-CONVERT-TO-ASCII-VALUE-AND-AGAIN-TO-CHARACTER
|
class Solution:
def replaceDigits(self, s: str) -> str:
res=""
for i in range(len(s)):
try:
j = int(s[i])
res+=chr(ord(s[i-1]) + j)
except:
print(s[i])
res+=s[i]
return res
|
replace-all-digits-with-characters
|
PYTHON -- CONVERT TO ASCII VALUE AND AGAIN TO CHARACTER
|
shubhamdec10
| 0
| 60
|
replace all digits with characters
| 1,844
| 0.798
|
Easy
| 26,306
|
https://leetcode.com/problems/replace-all-digits-with-characters/discuss/1191307/Python3-linear-sweep
|
class Solution:
def replaceDigits(self, s: str) -> str:
s = list(s)
for i in range(1, len(s), 2):
s[i] = chr(ord(s[i-1]) + int(s[i]))
return "".join(s)
|
replace-all-digits-with-characters
|
[Python3] linear sweep
|
ye15
| 0
| 76
|
replace all digits with characters
| 1,844
| 0.798
|
Easy
| 26,307
|
https://leetcode.com/problems/replace-all-digits-with-characters/discuss/1187880/Python3-simple-solution-beat-100-users
|
class Solution:
def replaceDigits(self, s: str) -> str:
x = ''
for i in range(len(s)):
if i % 2 == 0:
x += s[i]
else:
x += chr(ord(s[i-1]) + int(s[i]))
return x
|
replace-all-digits-with-characters
|
Python3 simple solution beat 100% users
|
EklavyaJoshi
| 0
| 46
|
replace all digits with characters
| 1,844
| 0.798
|
Easy
| 26,308
|
https://leetcode.com/problems/replace-all-digits-with-characters/discuss/1186767/Python3-100-simple-understandable-solution
|
class Solution:
def replaceDigits(self, s: str) -> str:
o=''
for i in range(0,len(s),2):
if i!= len(s)-1:
o+=s[i]+chr((ord(s[i])+int(s[i+1])))
else:
o+=s[i]
return o
|
replace-all-digits-with-characters
|
Python3 100% simple understandable solution
|
coderash1998
| 0
| 43
|
replace all digits with characters
| 1,844
| 0.798
|
Easy
| 26,309
|
https://leetcode.com/problems/maximum-element-after-decreasing-and-rearranging/discuss/1503918/Python-O(N)-Time-and-Space.-Easy-to-understand
|
class Solution:
def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int:
counter = collections.Counter(arr)
available = sum(n > len(arr) for n in arr)
i = ans = len(arr)
while i > 0:
# This number is not in arr
if not counter[i]:
# Use another number to fill in its place. If we cannot, we have to decrease our max
if available: available -= 1
else: ans -= 1
# Other occurences can be used for future.
else:
available += counter[i] - 1
i -= 1
return ans
|
maximum-element-after-decreasing-and-rearranging
|
[Python] O(N) Time and Space. Easy to understand
|
JummyEgg
| 1
| 205
|
maximum element after decreasing and rearranging
| 1,846
| 0.591
|
Medium
| 26,310
|
https://leetcode.com/problems/maximum-element-after-decreasing-and-rearranging/discuss/1185914/Pyhotn3-Sorting-Solution
|
class Solution:
def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int:
arr.sort()
arr[0] = 1
for i in range(1,len(arr)):
arr[i] = min(arr[i-1]+1,arr[i])
return max(arr)
|
maximum-element-after-decreasing-and-rearranging
|
Pyhotn3 Sorting Solution
|
swap2001
| 1
| 36
|
maximum element after decreasing and rearranging
| 1,846
| 0.591
|
Medium
| 26,311
|
https://leetcode.com/problems/maximum-element-after-decreasing-and-rearranging/discuss/2749012/python-using-sorting
|
class Solution:
def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int:
arr.sort()
c = 1
for i in range(0 , len(arr)):
if c <= arr[i]:
c += 1
return c - 1
|
maximum-element-after-decreasing-and-rearranging
|
python using sorting
|
akashp2001
| 0
| 5
|
maximum element after decreasing and rearranging
| 1,846
| 0.591
|
Medium
| 26,312
|
https://leetcode.com/problems/maximum-element-after-decreasing-and-rearranging/discuss/2321142/Only-Sort-or-Python-3
|
class Solution:
def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int:
arr.sort()
if arr[0]!= 1:
arr[0] = 1
maxi = arr[0]
print(arr)
for i in range(1,len(arr)):
if abs(arr[i]-arr[i-1])>1:
arr[i] = arr[i-1] +1
maxi = max(maxi,arr[i])
print(arr)
return maxi
|
maximum-element-after-decreasing-and-rearranging
|
Only Sort | Python 3
|
user7457RV
| 0
| 31
|
maximum element after decreasing and rearranging
| 1,846
| 0.591
|
Medium
| 26,313
|
https://leetcode.com/problems/maximum-element-after-decreasing-and-rearranging/discuss/1949481/Sorting-and-one-pass-98-speed
|
class Solution:
def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int:
arr.sort()
ans = 1
for n in arr[1:]:
if n > ans:
ans += 1
return ans
|
maximum-element-after-decreasing-and-rearranging
|
Sorting and one pass, 98% speed
|
EvgenySH
| 0
| 48
|
maximum element after decreasing and rearranging
| 1,846
| 0.591
|
Medium
| 26,314
|
https://leetcode.com/problems/maximum-element-after-decreasing-and-rearranging/discuss/1702367/Python-simple-sorting-solution
|
class Solution:
def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int:
arr.sort()
n = len(arr)
if n == 1:
return 1
arr[0] = 1
for i in range(n-1):
arr[i+1] = min(arr[i+1], arr[i]+1)
return arr[n-1]-(arr[0]-1)
|
maximum-element-after-decreasing-and-rearranging
|
Python simple sorting solution
|
byuns9334
| 0
| 60
|
maximum element after decreasing and rearranging
| 1,846
| 0.591
|
Medium
| 26,315
|
https://leetcode.com/problems/maximum-element-after-decreasing-and-rearranging/discuss/1346617/Python-simple-and-pythonic
|
class Solution:
def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int:
arr.sort()
arr[0] = 1
for index, value in enumerate(arr[1:], 1):
if 1 < (value - arr[index-1]):
arr[index] = arr[index-1] + 1
return arr[-1]
|
maximum-element-after-decreasing-and-rearranging
|
[Python] simple and pythonic
|
cruim
| 0
| 49
|
maximum element after decreasing and rearranging
| 1,846
| 0.591
|
Medium
| 26,316
|
https://leetcode.com/problems/maximum-element-after-decreasing-and-rearranging/discuss/1191310/Python3-greedy
|
class Solution:
def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int:
arr.sort()
ans = 0
for x in arr:
ans = min(ans+1, x)
return ans
|
maximum-element-after-decreasing-and-rearranging
|
[Python3] greedy
|
ye15
| 0
| 38
|
maximum element after decreasing and rearranging
| 1,846
| 0.591
|
Medium
| 26,317
|
https://leetcode.com/problems/maximum-element-after-decreasing-and-rearranging/discuss/1186935/Straightforward-Python3-solution-with-explanation
|
class Solution:
def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int:
#####################################################
# Two conditions required
# 1. the first element is 1
# 2. arr[i-1] <= arr[i] <= arr[i-1]+1
#####################################################
# To reach the maximum possible value,
# we increase the value wheneven we can
# e.g, if arr[i-1] is 2 and arr[i] is 4 (any value >=3),
# the maximum value after decreasing is 3
# e.g, if arr[i-1] is 2 and arr[i] is 2,
# arr[i] should remain as 2
#####################################################
arr = sorted(arr) # requiremnet 1
arr[0] = 1
for i in range(1, len(arr)):
if arr[i] >= arr[i-1] + 1:
arr[i] = arr[i-1] + 1 # requirement 2
return arr[-1]
|
maximum-element-after-decreasing-and-rearranging
|
Straightforward Python3 solution with explanation
|
tkuo-tkuo
| 0
| 25
|
maximum element after decreasing and rearranging
| 1,846
| 0.591
|
Medium
| 26,318
|
https://leetcode.com/problems/maximum-element-after-decreasing-and-rearranging/discuss/1186051/PythonPython3-Solution-with-explanation
|
class Solution:
def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int:
arr.sort() # sort the elements
if arr[0] == 1: # if arr[0] is 1 then simply give pass as it satisfies the 1st condition
pass
else: # else make arr[0] to 1 to satisfy condition 1
arr[0] = 1
for i in range(len(arr)-1): #run the loop upto length of the array -1 times
arr[i+1] = min(arr[i+1],arr[i]+1)# assign arr[i+1] to minimum value of arr[i+1], arr[i]+1
return arr[-1]#return max(arr)
|
maximum-element-after-decreasing-and-rearranging
|
Python/Python3 Solution with explanation
|
prasanthksp1009
| 0
| 49
|
maximum element after decreasing and rearranging
| 1,846
| 0.591
|
Medium
| 26,319
|
https://leetcode.com/problems/closest-room/discuss/1186155/Python-3-Aggregate-sorted-list-detailed-explanation-(2080-ms)
|
class Solution:
def closestRoom(self, rooms: List[List[int]], queries: List[List[int]]) -> List[int]:
ans = [0] * len(queries)
# sort queries to handle largest size queries first
q = deque(sorted([(size, room, i) for i, (room, size) in enumerate(queries)], key=lambda a: (-a[0], a[1], a[2])))
# sort rooms by descending size
rooms = deque(sorted(rooms, key=lambda x: -x[1]))
# current available room ids
cands = []
while q:
size, room, i = q.popleft()
# add room ids to candidates as long as top of room size meet the requirements
while rooms and rooms[0][1] >= size:
bisect.insort(cands, rooms.popleft()[0])
# if no room size available, return -1
if not cands: ans[i] = -1
# else use bisect to find optimal room ids
else:
loc = bisect.bisect_left(cands, room)
if loc == 0: ans[i] = cands[loc]
elif loc == len(cands): ans[i] = cands[-1]
else: ans[i] = cands[loc - 1] if room - cands[loc - 1] <= cands[loc] - room else cands[loc]
return ans
|
closest-room
|
[Python 3] Aggregate sorted list, detailed explanation (2080 ms)
|
chestnut890123
| 1
| 111
|
closest room
| 1,847
| 0.353
|
Hard
| 26,320
|
https://leetcode.com/problems/minimum-distance-to-the-target-element/discuss/1186862/Python3-linear-sweep
|
class Solution:
def getMinDistance(self, nums: List[int], target: int, start: int) -> int:
ans = inf
for i, x in enumerate(nums):
if x == target:
ans = min(ans, abs(i - start))
return ans
|
minimum-distance-to-the-target-element
|
[Python3] linear sweep
|
ye15
| 9
| 302
|
minimum distance to the target element
| 1,848
| 0.585
|
Easy
| 26,321
|
https://leetcode.com/problems/minimum-distance-to-the-target-element/discuss/1204659/Python3-simple-solution-beats-90-users
|
class Solution:
def getMinDistance(self, nums: List[int], target: int, start: int) -> int:
if nums[start] == target:return 0
i, j = start-1, start+1
while j < len(nums) or i > -1:
if i > -1:
if nums[i] == target:
return start-i
i -= 1
if j < len(nums):
if nums[j] == target:
return j-start
j += 1
|
minimum-distance-to-the-target-element
|
Python3 simple solution beats 90% users
|
EklavyaJoshi
| 2
| 135
|
minimum distance to the target element
| 1,848
| 0.585
|
Easy
| 26,322
|
https://leetcode.com/problems/minimum-distance-to-the-target-element/discuss/1584649/Python-sol-faster-than-99
|
class Solution:
def getMinDistance(self, nums: List[int], target: int, start: int) -> int:
if nums[start] == target:
return 0
i = start
j = start
left = 0
right = 0
while i < len(nums) or j > 0 :
if nums[i] == target :
return abs(i - start)
if nums[j] == target:
return abs(start - j)
if i != len(nums) - 1:
i += 1
if j != 0 :
j -= 1
return
|
minimum-distance-to-the-target-element
|
Python sol faster than 99%
|
elayan
| 1
| 109
|
minimum distance to the target element
| 1,848
| 0.585
|
Easy
| 26,323
|
https://leetcode.com/problems/minimum-distance-to-the-target-element/discuss/1187500/Python-3-simple-solution
|
class Solution:
def getMinDistance(self, nums: List[int], target: int, start: int) -> int:
n = len(nums)
f = start
b = start
idx = None
while f < n or b >= 0:
if f < n:
if nums[f] == target:
idx = f
break
f += 1
if b >= 0:
if nums[b] == target:
idx = b
break
b -= 1
return abs(idx-start)
|
minimum-distance-to-the-target-element
|
Python 3 simple solution
|
pankaj17n
| 1
| 59
|
minimum distance to the target element
| 1,848
| 0.585
|
Easy
| 26,324
|
https://leetcode.com/problems/minimum-distance-to-the-target-element/discuss/2781774/python-solution-Beats-97.33-And-memory-Beats-53.45
|
class Solution:
def getMinDistance(self, nums: List[int], target: int, start: int) -> int:
x = len(nums)+1;
for i in range(0 , len(nums)):
if(nums[i] == target):
x = min(x ,abs(start-i));
return x;
|
minimum-distance-to-the-target-element
|
python solution Beats 97.33% And memory Beats 53.45%
|
seifsoliman
| 0
| 3
|
minimum distance to the target element
| 1,848
| 0.585
|
Easy
| 26,325
|
https://leetcode.com/problems/minimum-distance-to-the-target-element/discuss/2699068/Python-or-Two-loops-with-early-exit
|
class Solution:
def getMinDistance(self, nums: List[int], target: int, start: int) -> int:
n = len(nums)
ans = float('inf')
i = start
while i < n and nums[i] != target:
i += 1
if i < n:
ans = i - start
i = start - 1
while i >= 0 and nums[i] != target:
i -= 1
if i >= 0:
ans = min (ans, start - i)
return ans
|
minimum-distance-to-the-target-element
|
Python | Two loops with early exit
|
on_danse_encore_on_rit_encore
| 0
| 5
|
minimum distance to the target element
| 1,848
| 0.585
|
Easy
| 26,326
|
https://leetcode.com/problems/minimum-distance-to-the-target-element/discuss/2660184/Optimized-Python-Approach-Without-Min-and-Abs-or-O(n)-time-O(1)-space
|
class Solution:
def getMinDistance(self, nums: List[int], target: int, start: int) -> int:
i, j = start, start + 1
while i >= 0 and j < len(nums):
if nums[i] == target:
return start - i
if nums[j] == target:
return j - start
i -= 1
j += 1
while i >= 0:
if nums[i] == target:
return start - i
i -= 1
while j < len(nums):
if nums[j] == target:
return j - start
j += 1
|
minimum-distance-to-the-target-element
|
Optimized Python Approach Without Min and Abs | O(n) time, O(1) space
|
kcstar
| 0
| 5
|
minimum distance to the target element
| 1,848
| 0.585
|
Easy
| 26,327
|
https://leetcode.com/problems/minimum-distance-to-the-target-element/discuss/2633820/Simple-one-liner-or-Python
|
class Solution:
def getMinDistance(self, nums: List[int], target: int, start: int) -> int:
return min(abs(key - start) for key, val in enumerate(nums) if val == target)
|
minimum-distance-to-the-target-element
|
Simple one liner | Python
|
Abhi_-_-
| 0
| 5
|
minimum distance to the target element
| 1,848
| 0.585
|
Easy
| 26,328
|
https://leetcode.com/problems/minimum-distance-to-the-target-element/discuss/2054301/Python-Solution-or-O(n)-or-One-Liner-or-Min-of-List
|
class Solution:
def getMinDistance(self, nums: List[int], target: int, start: int) -> int:
return min([abs(idx - start) for idx in range(len(nums)) if nums[idx] == target])
|
minimum-distance-to-the-target-element
|
Python Solution | O(n) | One-Liner | Min of List
|
Gautam_ProMax
| 0
| 71
|
minimum distance to the target element
| 1,848
| 0.585
|
Easy
| 26,329
|
https://leetcode.com/problems/minimum-distance-to-the-target-element/discuss/2022150/Python-Middle-Out-or-Two-Pointers-or-Start-at-the-Start-or-Clean-and-Simple
|
class Solution:
def getMinDistance(self, nums, target, start):
n = len(nums)
l = r = start
while l >= 0 or r < n:
if l >= 0:
if nums[l]==target: return start-l
l -= 1
if r < n:
if nums[r]==target: return r-start
r += 1
|
minimum-distance-to-the-target-element
|
Python - Middle-Out | Two-Pointers | Start at the Start | Clean and Simple
|
domthedeveloper
| 0
| 50
|
minimum distance to the target element
| 1,848
| 0.585
|
Easy
| 26,330
|
https://leetcode.com/problems/minimum-distance-to-the-target-element/discuss/1963869/Brute-force-list-comp
|
class Solution:
def getMinDistance(self, nums: List[int], target: int, start: int) -> int:
# find the smallest absolute difference between all indicies that contain the target & start
indicies = [i for i, n in enumerate(nums) if n == target]
dist = [abs(start - i) for i in indicies]
return min(dist)
|
minimum-distance-to-the-target-element
|
Brute force list comp
|
andrewnerdimo
| 0
| 28
|
minimum distance to the target element
| 1,848
| 0.585
|
Easy
| 26,331
|
https://leetcode.com/problems/minimum-distance-to-the-target-element/discuss/1829262/4-Lines-Python-Solution-oror-50-Faster-oror-Memory-less-than-75
|
class Solution:
def getMinDistance(self, nums: List[int], target: int, start: int) -> int:
ans=10**4
for i in range(len(nums)):
if nums[i]==target and abs(i-start)<ans: ans=abs(i-start)
return ans
|
minimum-distance-to-the-target-element
|
4-Lines Python Solution || 50% Faster || Memory less than 75%
|
Taha-C
| 0
| 43
|
minimum distance to the target element
| 1,848
| 0.585
|
Easy
| 26,332
|
https://leetcode.com/problems/minimum-distance-to-the-target-element/discuss/1765258/Simple-Python3-one-liner-(beats-~77)
|
class Solution:
def getMinDistance(self, nums: List[int], target: int, start: int) -> int:
return min(abs(i - start) for i in range(len(nums)) if nums[i] == target)
|
minimum-distance-to-the-target-element
|
Simple Python3 one-liner (beats ~77%)
|
y-arjun-y
| 0
| 40
|
minimum distance to the target element
| 1,848
| 0.585
|
Easy
| 26,333
|
https://leetcode.com/problems/minimum-distance-to-the-target-element/discuss/1736947/Python-Simple-or-O(n)-or-Beats-99.56-in-Memory
|
class Solution:
def getMinDistance(self, nums: List[int], target: int, start: int) -> int:
min_sum = 10**5
for i in range(len(nums)):
if nums[i]==target:
if abs(i-start) < min_sum:
min_sum = abs(i-start)
return min_sum
|
minimum-distance-to-the-target-element
|
Python Simple | O(n) | Beats 99.56% in Memory
|
veerbhansari
| 0
| 44
|
minimum distance to the target element
| 1,848
| 0.585
|
Easy
| 26,334
|
https://leetcode.com/problems/minimum-distance-to-the-target-element/discuss/1665541/Python-1-liner%3A-O(1)-Space-O(n)-Time-Almost-Never-Visits-All-Elements
|
class Solution:
def getMinDistance(self, nums: List[int], target: int, start: int) -> int:
return next(j for j in range(len(nums)) if (start+j < len(nums) and nums[start + j] == target) or (start >= j and nums[start - j] == target))
|
minimum-distance-to-the-target-element
|
Python 1-liner: O(1) Space O(n) Time, Almost Never Visits All Elements
|
SamRagusa
| 0
| 62
|
minimum distance to the target element
| 1,848
| 0.585
|
Easy
| 26,335
|
https://leetcode.com/problems/minimum-distance-to-the-target-element/discuss/1519218/Walk-from-start-to-both-directions-87-speed
|
class Solution:
def getMinDistance(self, nums: List[int], target: int, start: int) -> int:
len_nums = len(nums)
for i in range(len_nums):
if (start + i < len_nums and nums[start + i] == target or
start - i > - 1 and nums[start - i] == target):
return i
return -1
|
minimum-distance-to-the-target-element
|
Walk from start to both directions, 87% speed
|
EvgenySH
| 0
| 56
|
minimum distance to the target element
| 1,848
| 0.585
|
Easy
| 26,336
|
https://leetcode.com/problems/minimum-distance-to-the-target-element/discuss/1389412/Python-simple-solution
|
class Solution:
def getMinDistance(self, nums: List[int], target: int, start: int) -> int:
l = len(nums)
an=[]
for i in range(0,l):
if nums[i] == target:
an.append(abs(i-start))
return min(an)
|
minimum-distance-to-the-target-element
|
Python simple solution
|
kdevharsh2001
| 0
| 58
|
minimum distance to the target element
| 1,848
| 0.585
|
Easy
| 26,337
|
https://leetcode.com/problems/minimum-distance-to-the-target-element/discuss/1192674/Intuitive-approach-by-list-comprehension-map-and-sort
|
class Solution:
def getMinDistance(self, nums: List[int], target: int, start: int) -> int:
# 0): nums = [1,2,3,4,5], target=5, start=3
# 1): plist = [4]
# 2): dlist = [1]
# 3): ans = dlist[0] = 1
plist = [i for i, v in enumerate(nums) if v == target]
dlist = list(map(lambda p: abs(p-start), plist))
return sorted(dlist)[0]
|
minimum-distance-to-the-target-element
|
Intuitive approach by list comprehension, map and sort
|
puremonkey2001
| 0
| 37
|
minimum distance to the target element
| 1,848
| 0.585
|
Easy
| 26,338
|
https://leetcode.com/problems/minimum-distance-to-the-target-element/discuss/1191568/Simple-python-99-faster
|
class Solution:
def getMinDistance(self, nums: List[int], target: int, start: int) -> int:
min_abs = float('inf')
for i in range(len(nums)):
if nums[i]==target:
min_abs = min(abs(i-start),min_abs)
return min_abs
|
minimum-distance-to-the-target-element
|
Simple python 99% faster
|
pheobhe
| 0
| 69
|
minimum distance to the target element
| 1,848
| 0.585
|
Easy
| 26,339
|
https://leetcode.com/problems/minimum-distance-to-the-target-element/discuss/1187113/PythonPython3-Solution
|
class Solution:
def getMinDistance(self, nums: List[int], target: int, start: int) -> int:
mini = 10**9
for i,num in enumerate(nums):
if num == target:
mini = min(mini,abs(i-start))
return mini
|
minimum-distance-to-the-target-element
|
Python/Python3 Solution
|
prasanthksp1009
| 0
| 70
|
minimum distance to the target element
| 1,848
| 0.585
|
Easy
| 26,340
|
https://leetcode.com/problems/splitting-a-string-into-descending-consecutive-values/discuss/2632013/Clear-Python-DFS-with-comments
|
class Solution:
def splitString(self, s: str) -> bool:
"""
Time = O(2^N)
Space = O(N) space from stack
"""
def dfs(index: int, last: int) -> bool:
if index == len(s):
return True
# j: [index, len(s)-1]
for j in range(index, len(s)):
# cur: [index, index] ~ [index, len(s)-1]
cur = int(s[index:j + 1])
# last: [...,index-1]
# cur: [index+1, j]
# last = cur -> next: [j+1,...)
# DFS condition: cur = last - 1 && dfs(j+1, cur) == true
if cur == last - 1 and dfs(j + 1, cur):
return True
return False
for i in range(len(s) - 1):
last = int(s[:i+1])
if dfs(i + 1, last):
return True
return False
|
splitting-a-string-into-descending-consecutive-values
|
Clear Python DFS with comments
|
changyou1009
| 0
| 8
|
splitting a string into descending consecutive values
| 1,849
| 0.323
|
Medium
| 26,341
|
https://leetcode.com/problems/splitting-a-string-into-descending-consecutive-values/discuss/1837563/Slow-but-easy-solution
|
class Solution:
def splitString(self, s: str) -> bool:
s = str(int(s))
def check(l):
if len(l)<2:
return False
#print(l)
for i in range(len(l)-1):
if int(l[i])!=int(l[i+1])+1:
return False
return True
def backtrack(start,t,s):
if start==len(s):
if check(t):
return True
for i in range(start,len(s)):
if len(s[start:i+1])>1 and len(s[i+1:])>1 and int(s[start:i+1])<int(s[i+1:i+len(s[start:i+1])]):
continue
if len(t)>1 and int(t[-1])<int(s[start:i+1]):
return
t.append(s[start:i+1])
if backtrack(i+1,t,s):
return True
t.pop()
return False
return backtrack(0,[],s)
|
splitting-a-string-into-descending-consecutive-values
|
Slow but easy solution
|
aazad20
| 0
| 56
|
splitting a string into descending consecutive values
| 1,849
| 0.323
|
Medium
| 26,342
|
https://leetcode.com/problems/splitting-a-string-into-descending-consecutive-values/discuss/1755227/Python3-or-Recursive-solution-with-a-helper-function-or-24ms-beats-99.24
|
class Solution:
def splitString(self, s: str) -> bool:
self.res = False
def helper(s, k):
n1 = int(s[:k+1])
for j in range(k+1, len(s)):
n2 = int(s[k+1:j+1])
if n1 - n2 == 1:
if j == len(s)-1:
self.res = True
else:
helper(s[k+1:], j-(k+1))
if n2 >= n1:
break
for i in range(len(s)):
helper(s, i)
return self.res
|
splitting-a-string-into-descending-consecutive-values
|
Python3 | Recursive solution with a helper function | 24ms beats 99.24%
|
nandhakiran366
| 0
| 39
|
splitting a string into descending consecutive values
| 1,849
| 0.323
|
Medium
| 26,343
|
https://leetcode.com/problems/splitting-a-string-into-descending-consecutive-values/discuss/1357639/String-manipulation-96-speed
|
class Solution:
def splitString(self, s: str) -> bool:
s = s.lstrip("0")
if s:
for end in range(1, len(s)):
next_num = str(int(s[:end]) - 1)
remaining_s = s[end:]
if set(remaining_s) == {"0"}:
remaining_s = "0"
else:
remaining_s = remaining_s.lstrip("0")
while remaining_s and remaining_s.startswith(next_num):
remaining_s = remaining_s[len(next_num):]
if set(remaining_s) == {"0"}:
remaining_s = "0"
else:
remaining_s = remaining_s.lstrip("0")
next_num = str(int(next_num) - 1)
if not remaining_s:
return True
return False
|
splitting-a-string-into-descending-consecutive-values
|
String manipulation, 96% speed
|
EvgenySH
| 0
| 66
|
splitting a string into descending consecutive values
| 1,849
| 0.323
|
Medium
| 26,344
|
https://leetcode.com/problems/splitting-a-string-into-descending-consecutive-values/discuss/1188042/Python3-Recursion-solution-for-reference
|
class Solution:
def splitString(self, s: str) -> bool:
# convert the string into digits.
s = [int(i) for i in list(s)]
def r(base, index, nums):
## increment power of 10.
d = 0
## accumulate the value for 10.
acc = 0
res = False
## check the value from reverse from the index -1 where we calculated base.
for x in range(index,-1,-1):
acc += (10**d)*nums[x]
if base + 1 == acc:
if x-1 >= 0:
## collect recursion output
res = res or r(acc, x-1, s)
else:
res = True
d+=1
return res
d = 0
ans = False
acc = 0
## same logic as recursion - just driver outside the recusion function.
## The logic below could possibly also be included ithe same recursion solution with some effort.
for x in range(len(s)-1,-1,-1):
acc += (10**d)*s[x]
ans = ans or r(acc, x-1, s)
d+=1
return ans
|
splitting-a-string-into-descending-consecutive-values
|
[Python3] Recursion solution for reference
|
vadhri_venkat
| 0
| 51
|
splitting a string into descending consecutive values
| 1,849
| 0.323
|
Medium
| 26,345
|
https://leetcode.com/problems/splitting-a-string-into-descending-consecutive-values/discuss/1186877/Python3-backtracking
|
class Solution:
def splitString(self, s: str) -> bool:
def fn(i, x):
"""Return True if s[i:] can be split following x."""
if i == len(s): return True
if x == 0: return False
ans = False
for ii in range(i, len(s) - int(i == 0)):
if x is None or int(s[i:ii+1]) == x - 1:
ans = ans or fn(ii+1, int(s[i:ii+1]))
return ans
return fn(0, None)
|
splitting-a-string-into-descending-consecutive-values
|
[Python3] backtracking
|
ye15
| 0
| 24
|
splitting a string into descending consecutive values
| 1,849
| 0.323
|
Medium
| 26,346
|
https://leetcode.com/problems/minimum-adjacent-swaps-to-reach-the-kth-smallest-number/discuss/1186887/Python3-brute-force
|
class Solution:
def getMinSwaps(self, num: str, k: int) -> int:
num = list(num)
orig = num.copy()
for _ in range(k):
for i in reversed(range(len(num)-1)):
if num[i] < num[i+1]:
ii = i+1
while ii < len(num) and num[i] < num[ii]: ii += 1
num[i], num[ii-1] = num[ii-1], num[i]
lo, hi = i+1, len(num)-1
while lo < hi:
num[lo], num[hi] = num[hi], num[lo]
lo += 1
hi -= 1
break
ans = 0
for i in range(len(num)):
ii = i
while orig[i] != num[i]:
ans += 1
ii += 1
num[i], num[ii] = num[ii], num[i]
return ans
|
minimum-adjacent-swaps-to-reach-the-kth-smallest-number
|
[Python3] brute-force
|
ye15
| 7
| 803
|
minimum adjacent swaps to reach the kth smallest number
| 1,850
| 0.719
|
Medium
| 26,347
|
https://leetcode.com/problems/minimum-adjacent-swaps-to-reach-the-kth-smallest-number/discuss/1467322/Python-3-or-Permutation-Brute-Force-or-Explanation
|
class Solution:
def getMinSwaps(self, num: str, k: int) -> int:
def next_permutation(nums):
small = len(nums) - 2
while small >= 0 and nums[small] >= nums[small+1]: small -= 1 # find last place there is an increase
if small == -1: nums.reverse() # mono-decrease
else:
next_larger = small+1
for i in range(len(nums)-1, small, -1):
# find smallest number larger than `nums[small]` from right side of `small`,
# if there are same value, take the most right one
if nums[small] < nums[i]: next_larger = i; break
nums[small], nums[next_larger] = nums[next_larger], nums[small]
start = small+1
nums[start:] = nums[start:][::-1]
return nums
origin, num = list(num), list(num)
for _ in range(k): # O(n*k)
num = next_permutation(num)
ans, n = 0, len(origin)
for i in range(n): # O(n*n)
j = num.index(origin[i], i)
ans += j - i
num[i:j+1] = [num[j]] + num[i:j]
return ans
|
minimum-adjacent-swaps-to-reach-the-kth-smallest-number
|
Python 3 | Permutation, Brute Force | Explanation
|
idontknoooo
| 2
| 378
|
minimum adjacent swaps to reach the kth smallest number
| 1,850
| 0.719
|
Medium
| 26,348
|
https://leetcode.com/problems/minimum-adjacent-swaps-to-reach-the-kth-smallest-number/discuss/1928733/Python-or-using-next_perm-with-explanation
|
class Solution:
def getMinSwaps(self, num: str, k: int) -> int:
#find kth
target=num
for i in range(k):
target=self.next_perm(target)
#count step
res=0
num=list(num)
for i in range(len(num)):
if num[i]!=target[i]:
j=i
#num[j]==target[i]
while num[j]!=target[i]:
j+=1
#swap (j-i) times
while j>i:
num[j-1],num[j]=num[j],num[j-1]
res+=1
j-=1
return res
def next_perm(self,num):
num=list(num)
# find first non-ascending digit num[i-1] from right to left
i=len(num)-1
while i>0 and num[i-1]>=num[i]:
i-=1
# find first larger digit num[j] from right to left
if i>0:
for j in range(len(num)-1,i-1,-1):
if num[j]>num[i-1]:
break
#swap
num[i-1],num[j]=num[j],num[i-1]
#reverse
return ''.join(num[:i]+sorted(num[i:]))
|
minimum-adjacent-swaps-to-reach-the-kth-smallest-number
|
Python | using next_perm with explanation
|
ginaaunchat
| 1
| 218
|
minimum adjacent swaps to reach the kth smallest number
| 1,850
| 0.719
|
Medium
| 26,349
|
https://leetcode.com/problems/minimum-adjacent-swaps-to-reach-the-kth-smallest-number/discuss/1431107/O(n*(k%2Bn-log-n))-T-or-O(n)-S-or-implicit-treap-%2B-next-permutation-or-Python-3
|
class Solution:
def getMinSwaps(self, num: str, k: int) -> int:
import random
class ImplicitTreap:
class ImplicitTreapNode:
def __init__(self, y, value, left=None, right=None):
self.y = y
self.value = value
self.left = left
self.right = right
self.size = 1
def recalc(self):
self.size = (self.left.size if self.left is not None else 0) + (self.right.size if self.right is not None else 0) + 1
def __init__(self, values=None):
self.root = None
for value in values:
self.append(value)
@staticmethod
def _merge(left, right):
if left is None:
return right
if right is None:
return left
if left.y > right.y:
left.right = ImplicitTreap._merge(left.right, right)
result = left
else:
right.left = ImplicitTreap._merge(left, right.left)
result = right
result.recalc()
return result
@staticmethod
def _split(node, index):
if node is None:
return None, None
left_size = node.left.size if node.left is not None else 0
if index >= left_size + 1:
left, right = ImplicitTreap._split(node.right, index - left_size - 1)
node.right = left
node.recalc()
return node, right
else:
left, right = ImplicitTreap._split(node.left, index)
node.left = right
node.recalc()
return left, node
def __getitem__(self, index):
if self.root is None or index > self.root.size or index < -self.root.size:
raise Exception('Index out of range')
if index < 0:
index = -1 - index
node = self.root
while True:
left_size = node.left.size if node.left is not None else 0
if index < left_size:
node = node.left
elif node.left is not None and index == 0:
return node.value
elif index == left_size:
return node.value
else:
node = node.right
index -= left_size + 1
def insert(self, index, value):
if self.root is None:
self.root = ImplicitTreap.ImplicitTreapNode(random.random(), value)
return
if index > self.root.size:
raise Exception('Index out of range')
left, right = ImplicitTreap._split(self.root, index)
node = ImplicitTreap.ImplicitTreapNode(random.random(), value)
self.root = ImplicitTreap._merge(ImplicitTreap._merge(left, node), right)
def append(self, value):
self.insert(self.root.size if self.root is not None else 0, value)
def pop(self, index=None):
if index is None:
index = self.root.size - 1
left, right = ImplicitTreap._split(self.root, index)
_, right = ImplicitTreap._split(right, 1)
self.root = ImplicitTreap._merge(left, right)
def __len__(self):
return self.root.size if self.root is not None else 0
def __str__(self):
result = []
def dfs(node):
nonlocal result
if node is None:
return
dfs(node.left)
result.append(node.value)
dfs(node.right)
dfs(self.root)
return str(result)
def next_permutation(permutation):
for i in range(len(permutation)-2, -1, -1):
if permutation[i] < permutation[i+1]:
k = i
break
else:
return
for i in range(len(permutation)-1, k, -1):
if permutation[k] < permutation[i]:
r = i
break
permutation = list(permutation)
permutation[k], permutation[r] = permutation[r], permutation[k]
return ''.join(permutation[0:k+1] + list(reversed(permutation[k+1:])))
permutation = num
for _ in range(k):
permutation = next_permutation(permutation)
result = 0
permutation = ImplicitTreap(permutation)
for i in range(len(permutation)):
if num[i] != permutation[i]:
for j in range(i+1, len(permutation)):
if num[i] == permutation[j]:
result += j - i
permutation.pop(j)
permutation.insert(i, num[i])
break
return result
|
minimum-adjacent-swaps-to-reach-the-kth-smallest-number
|
O(n*(k+n log n)) T | O(n) S | implicit treap + next permutation | Python 3
|
CiFFiRO
| 0
| 167
|
minimum adjacent swaps to reach the kth smallest number
| 1,850
| 0.719
|
Medium
| 26,350
|
https://leetcode.com/problems/minimum-adjacent-swaps-to-reach-the-kth-smallest-number/discuss/1188750/Python3-Solution-for-reference-combining-next-permutation-and-adjacent-swapping
|
class Solution:
def getMinSwaps(self, num: str, k: int) -> int:
nums = [int(i) for i in num]
orig = [int(i) for i in num]
right = len(nums) - 1
ans = 0
for _ in range(k):
for x in range(right, 0, -1):
if nums[x] > nums[x-1]:
iter = x
mini = (float('inf'), -1)
while iter <= right:
# Number should be greater than nums[x-1]
# Number should be closer to nums[x-1] than the temp value at mini[0]
if nums[iter] > nums[x-1] and (mini[0] - nums[x-1]) > (nums[iter] - nums[x-1]):
mini = (nums[iter], iter)
iter += 1
# Swap the item found at index that is immediately greater than number at x-1
nums[x-1], nums[mini[1]] = nums[mini[1]], nums[x-1]
ans += (mini[1] - (x-1))
# Sort the numbers to the right of swapped number
nums[x:] = sorted(nums[x:])
# print ("".join([str(i) for i in nums]))
break
# print (nums, orig)
i = 0
count = 0
# minimum number of adjacent swaps to get to nums from orig.
# check where the number differs in the array and count the number of swaps to get the right number in the slot.
while i < len(nums):
if nums[i] == orig[i]:
i+=1
else:
j = i
while nums[i] != orig[j]:
j+=1
while j > i:
## swap the number so that the calculations are correct as you traverse!
orig[j-1], orig[j] = orig[j], orig[j-1]
j -= 1
count += 1
return count
|
minimum-adjacent-swaps-to-reach-the-kth-smallest-number
|
[Python3] Solution for reference combining next permutation and adjacent swapping
|
vadhri_venkat
| 0
| 263
|
minimum adjacent swaps to reach the kth smallest number
| 1,850
| 0.719
|
Medium
| 26,351
|
https://leetcode.com/problems/minimum-interval-to-include-each-query/discuss/1422509/For-Beginners-oror-Easy-Approach-oror-Well-Explained-oror-Clean-and-Concise
|
class Solution:
def minInterval(self, intervals: List[List[int]], queries: List[int]) -> List[int]:
intervals.sort(key = lambda x:x[1]-x[0])
q = sorted([qu,i] for i,qu in enumerate(queries))
res=[-1]*len(queries)
for left,right in intervals:
ind = bisect.bisect(q,[left])
while ind<len(q) and q[ind][0]<=right:
res[q.pop(ind)[1]]=right-left+1
return res
|
minimum-interval-to-include-each-query
|
📌📌 For Beginners || Easy-Approach || Well-Explained || Clean & Concise 🐍
|
abhi9Rai
| 4
| 274
|
minimum interval to include each query
| 1,851
| 0.479
|
Hard
| 26,352
|
https://leetcode.com/problems/minimum-interval-to-include-each-query/discuss/2652142/Clean-Python3-or-Sorting-and-Heap
|
class Solution:
def minInterval(self, intervals: List[List[int]], queries: List[int]) -> List[int]:
queries_asc = sorted((q, i) for i, q in enumerate(queries))
intervals.sort()
i, num_intervals = 0, len(intervals)
size_heap = [] # (size, left)
for pos, qnum in queries_asc:
while i < num_intervals:
left, right = intervals[i]
if left > pos:
break
heapq.heappush(size_heap, (right - left + 1, left))
i += 1
while size_heap:
size, left = size_heap[0]
right = left + size - 1
if right >= pos:
break
heapq.heappop(size_heap)
queries[qnum] = size_heap[0][0] if size_heap else -1
return queries
|
minimum-interval-to-include-each-query
|
Clean Python3 | Sorting & Heap
|
ryangrayson
| 2
| 56
|
minimum interval to include each query
| 1,851
| 0.479
|
Hard
| 26,353
|
https://leetcode.com/problems/minimum-interval-to-include-each-query/discuss/1187214/PythonPython3-solution-using-heap-and-sorting-method
|
class Solution:
def minInterval(self, intervals: List[List[int]], queries: List[int]) -> List[int]:
# To store the output result
lis = [0 for i in range(len(queries))]
#sort the intervals in the reverse order
intervals.sort(reverse = True)
#View the intervals list
print(intervals)
#store the index number of the query with query number
queriesWithIndex = sorted([(q,i) for i,q in enumerate(queries)])
#Print and view the queriesWithInd
print(queriesWithInd)
#decare the lis to store the valuew but with the help of heap so the it will be store in sorted form
heapLis = []
#Traverse the queryWithIndex list which consists of tuples
for query,i in queriesWithIndex:
# loop should run till the intervals becomes empty
while len(intervals) and query >=intervals[-1][0]:
#pop the last value from interval and store it in start and end value
start, end = intervals.pop()
#push the value in the heap list
heappush(heapLis,[end - start + 1, end])
# traverse till the heaplis becomes empty or the element in heapLis[0][1] < query
while len(heapLis) and heapLis[0][1] < query:
#pop the tuple from the heapLis
heappop(heapLis)
#if len(heapLis) is 0 then simply assign lis to -1 else assign the value of heapLis[0][0] to lis[i]
if len(heapLis) == 0:
lis[i] = -1
else:
lis[i] = heapLis[0][0]
#return the lis
return lis
|
minimum-interval-to-include-each-query
|
Python/Python3 solution using heap and sorting method
|
prasanthksp1009
| 2
| 112
|
minimum interval to include each query
| 1,851
| 0.479
|
Hard
| 26,354
|
https://leetcode.com/problems/minimum-interval-to-include-each-query/discuss/1186916/Python3-priority-queue
|
class Solution:
def minInterval(self, intervals: List[List[int]], queries: List[int]) -> List[int]:
intervals.sort()
pq = []
k = 0
ans = [-1] * len(queries)
for query, i in sorted(zip(queries, range(len(queries)))):
while k < len(intervals) and intervals[k][0] <= query:
heappush(pq, (intervals[k][1] - intervals[k][0] + 1, *intervals[k]))
k += 1
while pq and pq[0][2] < query:
heappop(pq)
if pq: ans[i] = pq[0][0]
return ans
|
minimum-interval-to-include-each-query
|
[Python3] priority queue
|
ye15
| 2
| 81
|
minimum interval to include each query
| 1,851
| 0.479
|
Hard
| 26,355
|
https://leetcode.com/problems/minimum-interval-to-include-each-query/discuss/2315278/Python-3-oror-hashMap-priority-queue-min-heap
|
class Solution:
def minInterval(self, intervals: List[List[int]], queries: List[int]) -> List[int]:
hashMap = {}
intervals.sort()
minHeap = []
i_l = len(intervals)
i = 0
for q in sorted(queries):
while i < i_l and intervals[i][0] <= q:
start, end = intervals[i]
heapq.heappush(minHeap, [(end-start+1), end])
i += 1
while minHeap and minHeap[0][1] < q:
heapq.heappop(minHeap)
hashMap[q] = minHeap[0][0] if minHeap else -1
return [hashMap[q] for q in queries]
|
minimum-interval-to-include-each-query
|
Python 3 || hashMap, priority queue, min-heap
|
sagarhasan273
| 1
| 114
|
minimum interval to include each query
| 1,851
| 0.479
|
Hard
| 26,356
|
https://leetcode.com/problems/minimum-interval-to-include-each-query/discuss/1187869/Python-3-Dynamic-heap-with-detailed-explanation-(1900ms)
|
class Solution:
def minInterval(self, intervals: List[List[int]], queries: List[int]) -> List[int]:
# sort queries from small to large
q = deque(sorted([(x, i) for i, x in enumerate(queries)]))
# answer to queries, initial state set to -1
ans = [-1] * len(queries)
# sort intervals by low, high and size
ivals = deque(sorted([(a, b, b - a + 1) for a, b in intervals]))
# available intervals
cands = []
while q:
x, i = q.popleft()
# if lower bound of intervals on the top of stack <= current query
while ivals and x >= ivals[0][0]:
a, b, c = ivals.popleft()
# if higher bound of intervals also meets the requirements
# if not then discard the interval
if x <= b:
heappush(cands, (c, b, a))
# udpate available intervals by removing old ones which no longer has a eligible higher bound
while cands:
c, b, a = heappop(cands)
if x <= b:
ans[i] = c
heappush(cands, (c, b, a))
break
return ans
|
minimum-interval-to-include-each-query
|
[Python 3] Dynamic heap with detailed explanation (1900ms)
|
chestnut890123
| 0
| 78
|
minimum interval to include each query
| 1,851
| 0.479
|
Hard
| 26,357
|
https://leetcode.com/problems/maximum-population-year/discuss/1210686/Python3-O(N)
|
class Solution:
def maximumPopulation(self, logs: List[List[int]]) -> int:
# the timespan 1950-2050 covers 101 years
delta = [0] * 101
# to make explicit the conversion from the year (1950 + i) to the ith index
conversionDiff = 1950
for l in logs:
# the log's first entry, birth, increases the population by 1
delta[l[0] - conversionDiff] += 1
# the log's second entry, death, decreases the population by 1
delta[l[1] - conversionDiff] -= 1
runningSum = 0
maxPop = 0
year = 1950
# find the year with the greatest population
for i, d in enumerate(delta):
runningSum += d
# since we want the first year this population was reached, only update if strictly greater than the previous maximum population
if runningSum > maxPop:
maxPop = runningSum
year = conversionDiff + i
return year
|
maximum-population-year
|
Python3 O(N)
|
signifying
| 21
| 2,000
|
maximum population year
| 1,854
| 0.599
|
Easy
| 26,358
|
https://leetcode.com/problems/maximum-population-year/discuss/1198702/Python3-greedy
|
class Solution:
def maximumPopulation(self, logs: List[List[int]]) -> int:
vals = []
for x, y in logs:
vals.append((x, 1))
vals.append((y, -1))
ans = prefix = most = 0
for x, k in sorted(vals):
prefix += k
if prefix > most:
ans = x
most = prefix
return ans
|
maximum-population-year
|
[Python3] greedy
|
ye15
| 7
| 886
|
maximum population year
| 1,854
| 0.599
|
Easy
| 26,359
|
https://leetcode.com/problems/maximum-population-year/discuss/1206057/python-solution
|
class Solution:
def maximumPopulation(self, logs: List[List[int]]) -> int:
b=[logs[i][0] for i in range(len(logs))]
d=[logs[i][1] for i in range(len(logs))]
m=0 #max population
a=0 #alive
r=1950
for i in range(1950,2051):
a+=b.count(i)-d.count(i)
if a>m:
m=a
r=i
return r
|
maximum-population-year
|
python solution
|
_Light_
| 2
| 226
|
maximum population year
| 1,854
| 0.599
|
Easy
| 26,360
|
https://leetcode.com/problems/maximum-population-year/discuss/2714948/Simple-python-solution
|
class Solution:
def maximumPopulation(self, logs: List[List[int]]) -> int:
dic={}
logs.sort()
initial=logs[0][0]
final=logs[-1][1]
for i in range(initial,final):
dic[i]=0
for j in logs:
if(i>=j[0] and i<j[1]):
dic[i]+=1
m=max(dic.values())
for i in dic.keys():
if(dic[i]==m):
return i
|
maximum-population-year
|
Simple python solution
|
Kiran_Rokkam
| 0
| 11
|
maximum population year
| 1,854
| 0.599
|
Easy
| 26,361
|
https://leetcode.com/problems/maximum-population-year/discuss/2560790/using-heapq
|
class Solution:
def maximumPopulation(self, logs: List[List[int]]) -> int:
# sort based on birth
logs.sort()
# an array to save info
death_birth_years = []
# maximum length
maxlen = 0
# output year
year = None
# itearte over logs
for i in logs:
# if new birth is after min death year pop
while(death_birth_years and i[0] >= death_birth_years[0][0] ):
heapq.heappop(death_birth_years)
# push in inverted order ie, death, birth here
heapq.heappush(death_birth_years, (i[1],i[0]))
# check if it hits max length
if len(death_birth_years) > maxlen:
maxlen = max(len(death_birth_years),maxlen)
# save the latest birth that trigged population peak
year = i[0]
# return the year
return year
|
maximum-population-year
|
using heapq
|
krishnamsgn
| 0
| 24
|
maximum population year
| 1,854
| 0.599
|
Easy
| 26,362
|
https://leetcode.com/problems/maximum-population-year/discuss/2481447/Python3-differential-array
|
class Solution:
def maximumPopulation(self, logs: List[List[int]]) -> int:
# Year_Converted = Year - 1949
# The converted year is between 1 and 101
diff_array = [0] * 102
for log in logs:
birth_converted = log[0] - 1949
die_converted = log[1] - 1949
# Add one to those year between birth_converted
# and die_converted - 1, inclusive
diff_array[birth_converted] += 1
diff_array[die_converted] -= 1
curr_pop = 0
max_pop = 0
earliest_year = 0
for i in range(1, 101):
curr_pop += diff_array[i]
if curr_pop > max_pop:
max_pop = curr_pop
earliest_year = i + 1949
return earliest_year
|
maximum-population-year
|
Python3 differential array
|
Aden-Q
| 0
| 41
|
maximum population year
| 1,854
| 0.599
|
Easy
| 26,363
|
https://leetcode.com/problems/maximum-population-year/discuss/2021335/Python-Array-and-Dictionary-or-Clean-and-Simple!
|
class Solution:
def maximumPopulation(self, logs):
start = 1950
population = [0] * 101
for b,d in logs:
b,d = b-start, d-start
for year in range(b, d): population[year] += 1
return population.index(max(population)) + start
|
maximum-population-year
|
Python - Array and Dictionary | Clean and Simple!
|
domthedeveloper
| 0
| 94
|
maximum population year
| 1,854
| 0.599
|
Easy
| 26,364
|
https://leetcode.com/problems/maximum-population-year/discuss/2021335/Python-Array-and-Dictionary-or-Clean-and-Simple!
|
class Solution:
def maximumPopulation(self, logs):
population = Counter()
for b,d in logs:
for year in range(b, d): population[year] += 1
maxPopulation = max(population.values())
return min(k for k,v in population.items() if v == maxPopulation)
|
maximum-population-year
|
Python - Array and Dictionary | Clean and Simple!
|
domthedeveloper
| 0
| 94
|
maximum population year
| 1,854
| 0.599
|
Easy
| 26,365
|
https://leetcode.com/problems/maximum-population-year/discuss/1857572/Simple-Python-Solution-oror-55-Faster-oror-Memory-less-than-60
|
class Solution:
def maximumPopulation(self, logs: List[List[int]]) -> int:
years=sorted(list(chain(*logs))) ; ans=0 ; mx=0
for year in years:
cnt=0
for i in range(len(logs)):
if logs[i][0]<=year and logs[i][1]>year: cnt+=1
if cnt>mx: mx=cnt ; ans=year
return ans
|
maximum-population-year
|
Simple Python Solution || 55% Faster || Memory less than 60%
|
Taha-C
| 0
| 88
|
maximum population year
| 1,854
| 0.599
|
Easy
| 26,366
|
https://leetcode.com/problems/maximum-population-year/discuss/1857572/Simple-Python-Solution-oror-55-Faster-oror-Memory-less-than-60
|
class Solution:
def maximumPopulation(self, logs: List[List[int]]) -> int:
d = defaultdict(int)
for birth, death in logs:
for i in range(birth, death): d[i] += 1
return max(d.items(), key=lambda x:(x[1],-x[0]))[0]
|
maximum-population-year
|
Simple Python Solution || 55% Faster || Memory less than 60%
|
Taha-C
| 0
| 88
|
maximum population year
| 1,854
| 0.599
|
Easy
| 26,367
|
https://leetcode.com/problems/maximum-population-year/discuss/1529568/One-pass-over-logs-and-years
|
class Solution:
def maximumPopulation(self, logs: List[List[int]]) -> int:
years = defaultdict(int)
max_population = max_year = 0
for start, end in logs:
for y in range(start, end):
years[y] += 1
if (years[y] > max_population or
years[y] == max_population and y < max_year):
max_population = years[y]
max_year = y
return max_year
|
maximum-population-year
|
One pass over logs and years
|
EvgenySH
| 0
| 182
|
maximum population year
| 1,854
| 0.599
|
Easy
| 26,368
|
https://leetcode.com/problems/maximum-population-year/discuss/1388920/Explained-Python3-Simulation-with-two-events-in-timeline-'born'-'dead'
|
class Solution:
def maximumPopulation(self, logs: List[List[int]]) -> int:
events = []
for born, died in logs:
events.extend([(born, '1_born'), (died, '0_died')])
# let us simulate the events in timeline order
# the order in which they happened
events.sort()
# Question says:
# "person is not counted in the year that they die."
# since '0' < '1' we will first count the deaths
# and then the birth, so the death year is not included ;)
alive = 0
max_year, max_alive = 0, 0
for year, event in events:
if event == '1_born':
alive += 1
else:
alive -= 1
if alive > max_alive:
max_alive, max_year = alive, year
return max_year
|
maximum-population-year
|
Explained Python3 Simulation, with two events in timeline, 'born' 'dead'
|
yozaam
| 0
| 144
|
maximum population year
| 1,854
| 0.599
|
Easy
| 26,369
|
https://leetcode.com/problems/maximum-population-year/discuss/1229181/Python3-simple-solution-using-dictionary
|
class Solution:
def maximumPopulation(self, logs: List[List[int]]) -> int:
d = {}
for i,j in enumerate(logs):
for k in range(j[0],j[1]):
d[k] = d.get(k,0)+1
return sorted([i for i in d.keys() if d[i] == max(d.values())])[0]
|
maximum-population-year
|
Python3 simple solution using dictionary
|
EklavyaJoshi
| -1
| 121
|
maximum population year
| 1,854
| 0.599
|
Easy
| 26,370
|
https://leetcode.com/problems/maximum-population-year/discuss/1223429/easy-solution-or-array-difference-algorithmor-python
|
class Solution:
def maximumPopulation(self, logs: List[List[int]]) -> int:
u=[0]*(3000)
for j in logs:
u[j[0]]+=1
u[j[1]]-=1
p=[u[0]]
for j in range(1,len(u)):
p.append(p[-1]+u[j])
return p.index(max(p))
|
maximum-population-year
|
easy solution | array difference algorithm| python
|
chikushen99
| -1
| 170
|
maximum population year
| 1,854
| 0.599
|
Easy
| 26,371
|
https://leetcode.com/problems/maximum-distance-between-a-pair-of-values/discuss/2209743/Python3-simple-solution-using-two-pointers
|
class Solution:
def maxDistance(self, nums1: List[int], nums2: List[int]) -> int:
length1, length2 = len(nums1), len(nums2)
i,j = 0,0
result = 0
while i < length1 and j < length2:
if nums1[i] > nums2[j]:
i+=1
else:
result = max(result,j-i)
j+=1
return result
|
maximum-distance-between-a-pair-of-values
|
📌 Python3 simple solution using two pointers
|
Dark_wolf_jss
| 6
| 69
|
maximum distance between a pair of values
| 1,855
| 0.527
|
Medium
| 26,372
|
https://leetcode.com/problems/maximum-distance-between-a-pair-of-values/discuss/1198697/Python-Solution-Simple-2-Pointer
|
class Solution:
def maxDistance(self, nums1: List[int], nums2: List[int]) -> int:
max_diff = 0
i = 0
j = 0
while i<len(nums1) and j <len(nums2):
if i <= j:
if nums1[i] <= nums2[j]:
max_diff=max(max_diff,j-i)
j += 1
else:
i += 1
else:
j += 1
return max_diff
|
maximum-distance-between-a-pair-of-values
|
Python Solution- Simple -2 Pointer
|
SaSha59
| 3
| 132
|
maximum distance between a pair of values
| 1,855
| 0.527
|
Medium
| 26,373
|
https://leetcode.com/problems/maximum-distance-between-a-pair-of-values/discuss/1198720/Python3-sliding-window
|
class Solution:
def maxDistance(self, nums1: List[int], nums2: List[int]) -> int:
ans = ii = 0
for i, x in enumerate(nums2):
while ii <= i and ii < len(nums1) and nums1[ii] > nums2[i]: ii += 1
if ii < len(nums1) and nums1[ii] <= nums2[i]: ans = max(ans, i - ii)
return ans
|
maximum-distance-between-a-pair-of-values
|
[Python3] sliding window
|
ye15
| 2
| 68
|
maximum distance between a pair of values
| 1,855
| 0.527
|
Medium
| 26,374
|
https://leetcode.com/problems/maximum-distance-between-a-pair-of-values/discuss/1944437/Python-Binary-Search
|
class Solution:
def maxDistance(self, nums1: List[int], nums2: List[int]) -> int:
result = 0
max_dist = 0
m, n = len(nums1), len(nums2)
#iterate from left of nums1
for i in range(m):
#for every element, find the index of nums2 with value <= nums1[i] in the range nums2[i:len(nums2)]
start = i
end = len(nums2)-1
#binary-search
while start<=end:
mid = start + (end-start)//2
#look to the left for a closer match
if nums2[mid]<nums1[i]:
end = mid-1
#look to the right for a closer match
elif nums2[mid]>=nums1[i]:
start = mid+1
#at the end of binary-search, nums2[end] will hold the closest value to nums1[i]
#check if it is the max distance
max_dist = max(max_dist,end-i)
return max_dist
|
maximum-distance-between-a-pair-of-values
|
Python Binary Search
|
eforean
| 1
| 46
|
maximum distance between a pair of values
| 1,855
| 0.527
|
Medium
| 26,375
|
https://leetcode.com/problems/maximum-distance-between-a-pair-of-values/discuss/2775161/Easy-Linear-solution-O(1)-space-complexity
|
class Solution:
def maxDistance(self, nums1: List[int], nums2: List[int]) -> int:
res = 0
m, n = len(nums1), len(nums2)
i, j = 0, 0
while i < m and j < n:
if nums1[i] <= nums2[j]:
res = max(res, j-i)
j += 1
else:
i += 1
return res
|
maximum-distance-between-a-pair-of-values
|
Easy Linear solution, O(1) space complexity
|
byuns9334
| 0
| 5
|
maximum distance between a pair of values
| 1,855
| 0.527
|
Medium
| 26,376
|
https://leetcode.com/problems/maximum-distance-between-a-pair-of-values/discuss/2599020/Python3-or-Solved-By-Performing-Binary-Search-on-nums2-to-find-RightMost-Limit-for-Every-index-I
|
class Solution:
#let n = len(nums1) and m = len(nums2)!
#Time-Complexity: O(n * m)
#Space-Complexity: O(1)
def maxDistance(self, nums1: List[int], nums2: List[int]) -> int:
#Approach: Linearly try each and every element in nums1 array! Perform binary
#search to find rightmost element in nums2 which is greater than the
#current nums1 element -> This way we are maximizing distance between the
#pair (i,j) and constantly update answer for every possible pairing for
#every index i w/ respect to nums1 input array!
ans = 0
for i in range(len(nums1)):
#we will consider indices from index i and onwards!
#define our search space!
L, R = i, len(nums2) - 1
#as long as search space has at least one element left to consider,
#continue iterations of binary searching!
while L<=R:
mid = (L + R) // 2
mid_e = nums2[mid]
#check if mid_e is greater than or equal to nums1[i]!
if(mid_e >= nums1[i]):
#we need to search right to find rightmost limit!
L = mid + 1
continue
else:
R = mid - 1
continue
#once we break from while loop, R will be pointing to index pos.
#that describes rightmost element within nums2 that will be form a valid
#pair w/ respsect to current num1[i]!
#make sure that R points to index in-bounds and not negative! If it's
#negative, that means no valid pair exists with current index i element
#of nums1!
if(R < 0):
continue
else:
ans = max(ans, R - i)
return ans
|
maximum-distance-between-a-pair-of-values
|
Python3 | Solved By Performing Binary Search on nums2 to find RightMost Limit for Every index I
|
JOON1234
| 0
| 10
|
maximum distance between a pair of values
| 1,855
| 0.527
|
Medium
| 26,377
|
https://leetcode.com/problems/maximum-distance-between-a-pair-of-values/discuss/2494547/Python-O(N)-Solution
|
class Solution:
def maxDistance(self, nums1: List[int], nums2: List[int]) -> int:
i = 0
j = 0
max_distance = float("-inf")
while i < len(nums1) and j < len(nums2):
if nums1[i] <= nums2[j]:
max_distance = max(max_distance, j-i)
else:
i += 1
j += 1
return max_distance if max_distance != float("-inf") else 0
|
maximum-distance-between-a-pair-of-values
|
Python O(N) Solution
|
yash921
| 0
| 32
|
maximum distance between a pair of values
| 1,855
| 0.527
|
Medium
| 26,378
|
https://leetcode.com/problems/maximum-distance-between-a-pair-of-values/discuss/2459975/C%2B%2BPython-Faster-Optimized-solution
|
class Solution:
def maxDistance(self, nums1: List[int], nums2: List[int]) -> int:
i=0
j=0
res = 0
n = len(nums1)
m = len(nums2)
while i<n and j<m:
if nums1[i]>nums2[j]:
i+=1
else:
res=max(res,j-i)
j+=1
return res
|
maximum-distance-between-a-pair-of-values
|
C++/Python Faster Optimized solution
|
arpit3043
| 0
| 48
|
maximum distance between a pair of values
| 1,855
| 0.527
|
Medium
| 26,379
|
https://leetcode.com/problems/maximum-distance-between-a-pair-of-values/discuss/2393307/Python-Accurate-Faster-Solution-oror-Documented
|
class Solution:
def maxDistance(self, nums1: List[int], nums2: List[int]) -> int:
maxD = 0 # initialize max distance with 0
i = j = 0 # initialize array pointers with 0
# traverse until both pointers < array-length
while i < len(nums1) and j < len(nums2):
if nums1[i] > nums2[j]: # if not valid pair
i += 1 # move forward i pointer
else: # if valid pair
maxD = max(maxD, j-i) # set max distance
j += 1 # move forward j pointer
return maxD # return max distance
|
maximum-distance-between-a-pair-of-values
|
[Python] Accurate Faster Solution || Documented
|
Buntynara
| 0
| 10
|
maximum distance between a pair of values
| 1,855
| 0.527
|
Medium
| 26,380
|
https://leetcode.com/problems/maximum-distance-between-a-pair-of-values/discuss/2200574/Easy-2-pointer-approach
|
class Solution:
def maxDistance(self, nums1: List[int], nums2: List[int]) -> int:
i, j, n, m, maxDistance = 0, 0, len(nums1), len(nums2), 0
while i < n and j < m:
if nums1[i] <= nums2[j]:
maxDistance = max(maxDistance, j - i)
else:
i += 1
j += 1
return maxDistance
|
maximum-distance-between-a-pair-of-values
|
Easy 2 pointer approach
|
Vaibhav7860
| 0
| 32
|
maximum distance between a pair of values
| 1,855
| 0.527
|
Medium
| 26,381
|
https://leetcode.com/problems/maximum-distance-between-a-pair-of-values/discuss/1215959/Python3-Simple-Two-Pointers-Approach-Explained-with-Comments
|
class Solution:
def maxDistance(self, nums1: List[int], nums2: List[int]) -> int:
'''
1. Start from the rightmost index of nums2 and nums1. If len(nums1)>len(nums2), start from index len(nums2)-1 of array nums1
2. Let j be the current index of nums2 and i be the current index of nums1
3. While i>=0:
- check if nums1[i] <= nums2[j]. If so, then update the maximum difference and decrease i(check the left indices of nums1)
- Otherwise, decrease j. If j gets less than i, set i=j
'''
j=len(nums2)-1 # initialize j
i=min(len(nums1)-1,j) # initialize i as i<=j
max_diff = 0
while i>=0: # check until i=0
if nums1[i]<=nums2[j]: # nums1[i] is less equal nums2[j], so nums1[i-1] can also be less equal nums2[j]
max_diff=max(max_diff, j-i) # update maximum difference
i-=1 # decrement i
else: # nums1[i] is greater than nums2[j], so nums2[j-1] can be greater equal nums1[i]
j-=1 # decrement j
if i>j:
i=j # i must be less equal j, so here, update i accordingly
return max_diff
|
maximum-distance-between-a-pair-of-values
|
Python3 Simple Two Pointers Approach, Explained with Comments
|
bPapan
| 0
| 72
|
maximum distance between a pair of values
| 1,855
| 0.527
|
Medium
| 26,382
|
https://leetcode.com/problems/maximum-distance-between-a-pair-of-values/discuss/1199013/Straightforward-Python3-O(n)-two-pointers-solution-with-explanation
|
class Solution:
def maxDistance(self, nums1: List[int], nums2: List[int]) -> int:
###################################################################
# Assumption/Requirement
###################################################################
# nums1 and nums2 are both decreasing
# return max distance (j-1) where j >= i and nums2[j] >= nums1[i]
###################################################################
###################################################################
# Explanation
###################################################################
# 1. if i is fixed, we want to find out the largest j
# --> keep increase j if the condition "nums2[j] >= nums1[i]" is valid
# 2. if (i, j) is valid, but (i, j+1) is not valid,
# --> start with (i+1, j+1) instead of (i+1, i+1)
# --> since (i, j) is valid, it indicates (i+1, j) must be also valid (nums1[i] >= nums1[i+1])
# --> we will start with (i+1, j+1) to test whether it is valid ornot
###################################################################
res = 0
i, j = 0, 0
while i < len(nums1) and j < len(nums2):
if nums2[j] >= nums1[i]:
res = max(res, j-i)
j += 1
else:
i += 1
return res
|
maximum-distance-between-a-pair-of-values
|
Straightforward Python3 O(n) two-pointers solution with explanation
|
tkuo-tkuo
| 0
| 38
|
maximum distance between a pair of values
| 1,855
| 0.527
|
Medium
| 26,383
|
https://leetcode.com/problems/maximum-subarray-min-product/discuss/1198800/Python3-mono-stack
|
class Solution:
def maxSumMinProduct(self, nums: List[int]) -> int:
prefix = [0]
for x in nums: prefix.append(prefix[-1] + x)
ans = 0
stack = []
for i, x in enumerate(nums + [-inf]): # append "-inf" to force flush all elements
while stack and stack[-1][1] >= x:
_, xx = stack.pop()
ii = stack[-1][0] if stack else -1
ans = max(ans, xx*(prefix[i] - prefix[ii+1]))
stack.append((i, x))
return ans % 1_000_000_007
|
maximum-subarray-min-product
|
[Python3] mono-stack
|
ye15
| 10
| 345
|
maximum subarray min product
| 1,856
| 0.378
|
Medium
| 26,384
|
https://leetcode.com/problems/maximum-subarray-min-product/discuss/1200240/Python-monotonic-stack-beats-100
|
class Solution:
def maxSumMinProduct(self, nums: List[int]) -> int:
mod=int(1e9+7)
stack=[] # (index, prefix sum at index)
rsum=0
res=0
nums.append(0)
for i, v in enumerate(nums):
while stack and nums[stack[-1][0]] >= v:
index, _ = stack.pop()
# if the stack is empty, the subarray sum is the current prefixsum
arrSum=rsum
if stack:
arrSum=rsum-stack[-1][1]
# update res with subarray sum
res=max(res, nums[index]*arrSum)
rsum+=v
stack.append((i, rsum))
return res%mod
|
maximum-subarray-min-product
|
Python monotonic stack beats 100%
|
alan9259
| 5
| 509
|
maximum subarray min product
| 1,856
| 0.378
|
Medium
| 26,385
|
https://leetcode.com/problems/maximum-subarray-min-product/discuss/2411914/Python3-or-Similar-to-Max-Rectangle-in-Histogram
|
class Solution:
def maxSumMinProduct(self, nums: List[int]) -> int:
n,ans=len(nums),-float('inf')
mod=10**9+7
left=[0 for i in range(n)]
right=[0 for i in range(n)]
prefixSum=[0 for i in range(n)]
prefixSum[0]=nums[0]
for i in range(1,n):
prefixSum[i]+=prefixSum[i-1]+nums[i]
stack=[]
for i in range(n):
while stack and nums[stack[-1]]>=nums[i]:
stack.pop()
left[i]=stack[-1] if len(stack) else -1
stack.append(i)
stack=[]
for i in range(n-1,-1,-1):
while stack and nums[stack[-1]]>=nums[i]:
stack.pop()
right[i]=stack[-1]-1 if len(stack) else n-1
stack.append(i)
for i in range(n):
currMax=prefixSum[right[i]]-(prefixSum[left[i]] if left[i]!=-1 else 0)
ans=max(ans,currMax*nums[i])
return ans%mod
|
maximum-subarray-min-product
|
[Python3] | Similar to Max Rectangle in Histogram
|
swapnilsingh421
| 0
| 54
|
maximum subarray min product
| 1,856
| 0.378
|
Medium
| 26,386
|
https://leetcode.com/problems/maximum-subarray-min-product/discuss/2057686/python3-dp-and-stack-solutions-for-reference.
|
class Solution:
def dp(self, nums):
N = len(nums)
dp = [(0, 0) for _ in range(N)]
ans = 0
for x in range(N):
for y in range(x, N):
if x == y:
dp[y] = (nums[y], nums[y])
else:
dp[y] = (min(dp[y-1][0], nums[y]), dp[y-1][1] + nums[y])
a,b = dp[y]
ans = max(ans, a*b)
return ans%(10**9+7)
def minArray(self, nums):
# Just to flush out the stack at the end of iterations.
nums.append(0)
N = len(nums)
z = 0
S = deque([[nums[0], 0]])
rolling_sum = [0]*N
rolling_sum[0] = nums[0]
for idx in range(1, N):
n = nums[idx]
while S and S[-1][0] > n:
a,b = S.pop()
if S:
b = S[-1][1]+1
z = max(z, rolling_sum[idx-1]*S[0][0])
z = max(z, (rolling_sum[idx-1] - rolling_sum[b-1]) * a)
S.append([nums[idx], idx])
rolling_sum[idx] = n + rolling_sum[idx-1]
return z%(10**9+7)
def maxSumMinProduct(self, nums: List[int]) -> int:
return self.minArray(nums)
|
maximum-subarray-min-product
|
[python3] dp and stack solutions for reference.
|
vadhri_venkat
| 0
| 76
|
maximum subarray min product
| 1,856
| 0.378
|
Medium
| 26,387
|
https://leetcode.com/problems/maximum-subarray-min-product/discuss/1436397/Python-Clean
|
class Solution:
def maxSumMinProduct(self, nums: List[int]) -> int:
N, maximum = len(nums), 0
cumulative, stack = [0], []
for num in nums:
cumulative.append(cumulative[-1] + num)
for i, num in enumerate(nums + [-float(inf)]):
start = i
while stack and stack[-1][1] > num:
index, value = stack.pop()
total = cumulative[i] - cumulative[index]
maximum = max(value * total, maximum)
start = index
stack.append((start, num))
return maximum % (10**9 + 7)
|
maximum-subarray-min-product
|
[Python] Clean
|
soma28
| 0
| 223
|
maximum subarray min product
| 1,856
| 0.378
|
Medium
| 26,388
|
https://leetcode.com/problems/maximum-subarray-min-product/discuss/1203747/very-easy-python-soln
|
class Solution(object):
def maxSumMinProduct(self, nums):
n,ans,mod=len(nums),0,10**9 + 7
lft,st=[0],[[nums[0],0]]
for i in range(1,n):
cur=0
while st and nums[i]<=st[-1][0]:
cur+=st.pop()[1]+1
st.append([nums[i],cur])
lft.append(cur)
rgt,st=[0],[[nums[-1],0]]
for i in range(n-2,-1,-1):
cur=0
while st and nums[i]<=st[-1][0]:
cur+=st.pop()[1]+1
st.append([nums[i],cur])
rgt.append(cur)
rgt.reverse()
sums,cur=[0],0
for i in range(n):
cur+=nums[i]
sums.append(cur)
for i in range(n):
ans=max(ans,nums[i]*(sums[i+rgt[i]+1]-sums[i-lft[i]]))
return ans%mod
|
maximum-subarray-min-product
|
very easy python soln
|
aayush_chhabra
| 0
| 257
|
maximum subarray min product
| 1,856
| 0.378
|
Medium
| 26,389
|
https://leetcode.com/problems/maximum-subarray-min-product/discuss/1201859/python-simple-intuitive-greedy-solution
|
class Solution:
def maxSumMinProduct(self, nums: List[int]) -> int:
n = len(nums)
s = list(accumulate(nums)) # sum
t = sorted([(v, i) for i, v in enumerate(nums)], reverse=True) # to greedily iterate over values
j = [i for i in range(n)] # jump array, at first one can only jump in it's own position
seen = [False] * n # to keep check if already seen a position(i.e. index) or not
mx = 0 # keep the maximum
for v, p in t:
if seen[p]: # if already seen position `p`, then just skip
continue
l, r = p, p # we start from position p
while l >= 0 and nums[l] >= v: # jump left as long as we found values >= v
seen[l] = True # marked the position as seen
l = j[l] - 1;
l += 1
while r < n and nums[r] >= v: # jump right as long as we find values >= v
seen[r] = True # marked the position as seen
r = j[r] + 1
r -= 1
ls = 0 if l == 0 else s[l-1]
rs = s[r]
mx = max(mx, v * (rs - ls)) # now update the maximum min-product
j[l], j[r] = r, l # update the jump pointers for position l and r
return mx % (10**9+7)
|
maximum-subarray-min-product
|
[python] simple intuitive greedy solution
|
iamlegend123
| 0
| 154
|
maximum subarray min product
| 1,856
| 0.378
|
Medium
| 26,390
|
https://leetcode.com/problems/largest-color-value-in-a-directed-graph/discuss/1200668/easy-python-sol-..
|
class Solution(object):
def largestPathValue(self, colors, edges):
n=len(colors)
graph=defaultdict(list)
indegree=defaultdict(int)
for u,v in edges:
graph[u].append(v)
indegree[v]+=1
queue=[]
dp=[[0]*26 for _ in range(n)]
colorvalues=[ord(c)-ord("a") for c in colors]
for u in range(n):
if u not in indegree:
queue.append(u)
dp[u][colorvalues[u]]=1
visited=0
while queue:
u=queue.pop()
visited+=1
for v in graph[u]:
for c in range(26):
dp[v][c]=max(dp[v][c],dp[u][c] + (c==colorvalues[v]))
indegree[v]-=1
if indegree[v]==0:
queue.append(v)
del indegree[v]
if visited<n:
return -1
return max(max(x) for x in dp)
```
|
largest-color-value-in-a-directed-graph
|
easy python sol ..
|
aayush_chhabra
| 9
| 299
|
largest color value in a directed graph
| 1,857
| 0.407
|
Hard
| 26,391
|
https://leetcode.com/problems/largest-color-value-in-a-directed-graph/discuss/1199847/Python3-dp
|
class Solution:
def largestPathValue(self, colors: str, edges: List[List[int]]) -> int:
graph = {}
indeg = [0] * len(colors)
for u, v in edges:
indeg[v] += 1
graph.setdefault(u, []).append(v)
# Kahn's algo
roots = [x for x in range(len(colors)) if indeg[x] == 0]
stack = roots.copy()
nodes = []
while stack:
x = stack.pop()
nodes.append(x)
for xx in graph.get(x, []):
indeg[xx] -= 1
if indeg[xx] == 0: stack.append(xx)
if len(nodes) < len(colors): return -1 # cycle detected
@cache
def fn(x):
"""Return distribution of (maximized) colors at given node."""
ans = [0]*26
ans[ord(colors[x]) - 97] = 1
for xx in graph.get(x, []):
val = fn(xx)
for i in range(26):
if i == ord(colors[x]) - 97: ans[i] = max(ans[i], 1 + val[i])
else: ans[i] = max(ans[i], val[i])
return ans
ans = [0]*26
for root in roots:
val = fn(root)
for i in range(26): ans[i] = max(ans[i], val[i])
return max(ans)
|
largest-color-value-in-a-directed-graph
|
[Python3] dp
|
ye15
| 2
| 98
|
largest color value in a directed graph
| 1,857
| 0.407
|
Hard
| 26,392
|
https://leetcode.com/problems/largest-color-value-in-a-directed-graph/discuss/1206392/Python-Iterative-DFS-Solution
|
class Solution:
def largestPathValue(self, colors: str, edges: List[List[int]]) -> int:
d = defaultdict(list)
for v1, v2 in edges:
d[v1].append(v2)
visited = {}
counts = [[0] * 26 for _ in range(len(colors))]
stack = []
global_max = 0
for root in d.keys():
if root in visited:
continue
stack.append(root)
while stack:
v1 = stack[-1]
if v1 in visited:
if visited[v1] == 1:
visited[v1] = 2
stack.pop()
if v1 in d:
for v2 in d[v1]:
for c in range(26):
counts[v1][c] = max(counts[v1][c], counts[v2][c])
counts[v1][ord(colors[v1])-ord('a')] += 1
else:
visited[v1] = 1
if v1 in d:
for v2 in d[v1]:
if v2 in visited:
if visited[v2] == 1:
return -1
else:
stack.append(v2)
global_max = max(global_max, max(counts[root]))
if global_max == 0 and len(d) < len(colors): # in case input is like ("abcde", [])
global_max = 1
return global_max
|
largest-color-value-in-a-directed-graph
|
Python Iterative DFS Solution
|
kylergao
| 0
| 130
|
largest color value in a directed graph
| 1,857
| 0.407
|
Hard
| 26,393
|
https://leetcode.com/problems/sorting-the-sentence/discuss/1219040/Python3-99.60-Fast-Solution
|
class Solution:
def sortSentence(self, s: str) -> str:
arr = [i[-1] + i[:-1] for i in s.split()]
arr.sort()
ans = ""
for i in arr:
ans += i[1:] + ' '
return ans[:-1]
|
sorting-the-sentence
|
[Python3] 99.60% Fast Solution
|
VoidCupboard
| 23
| 2,000
|
sorting the sentence
| 1,859
| 0.844
|
Easy
| 26,394
|
https://leetcode.com/problems/sorting-the-sentence/discuss/1210285/2-Lines-or-Python-Solution-or-Linear-TIme-or-Linear-Memory
|
class Solution:
def sortSentence(self, s: str) -> str:
# split the string and sort the words based upon the last letter
word_list = sorted(s.split(), key = lambda word: word[-1], reverse = False)
return " ".join([word[:-1] for word in word_list]) # join the words, after removing the last letter ie., digit
|
sorting-the-sentence
|
2 Lines | Python Solution | Linear TIme | Linear Memory
|
ramanaditya
| 19
| 1,800
|
sorting the sentence
| 1,859
| 0.844
|
Easy
| 26,395
|
https://leetcode.com/problems/sorting-the-sentence/discuss/1210285/2-Lines-or-Python-Solution-or-Linear-TIme-or-Linear-Memory
|
class Solution:
def sortSentence(self, s: str) -> str:
word_list = s.split() # form a list of words
n = len(word_list) # total words in the list, at max 9
# dict to make k, v pairs as there are at max 9 words in the array
# key as position of word, value as word without position
# because while joining, fetching from dict will take constant time
# and we can just add values iterating over keys from 1 to 9 (including)
index_dict = dict()
for word in word_list:
index_dict[int(word[-1])] = word[:-1]
res = ""
# iterate from 1 to n, and add up all the values
for i in range(1, n+1):
res += index_dict.get(i, "")
res += " "
# we can alse use, res[:-1], res.strip()
return res.rstrip() # right strip as " " is present at the end of the sentence
|
sorting-the-sentence
|
2 Lines | Python Solution | Linear TIme | Linear Memory
|
ramanaditya
| 19
| 1,800
|
sorting the sentence
| 1,859
| 0.844
|
Easy
| 26,396
|
https://leetcode.com/problems/sorting-the-sentence/discuss/1343270/PYTHON-3-or-faster-than-95.14-or-USING-DICTIONARY
|
class Solution:
def sortSentence(self, s: str) -> str:
x = s.split()
dic = {}
for i in x :
dic[i[-1]] = i[:-1]
return ' '.join([dic[j] for j in sorted(dic)])
|
sorting-the-sentence
|
PYTHON 3 | faster than 95.14% | USING DICTIONARY
|
rohitkhairnar
| 14
| 933
|
sorting the sentence
| 1,859
| 0.844
|
Easy
| 26,397
|
https://leetcode.com/problems/sorting-the-sentence/discuss/1986261/Python-Easiest-Solution-With-Explanationor-99.72-Faster-or-Sorting-or-Beg-to-adv
|
class Solution:
def sortSentence(self, s: str) -> str:
splited_string = s[::-1].split() # here first we are reversing the sting and then spliting it, split() function make each word of the string as a separate element of the list. For example: ['3a', '1sihT', '4ecnetnes', '2si']
splited_string.sort() # as we are having number in front of each word now, we can sort the list.
res = [] # taking empty list to save the result.
for word in splited_string: # travering the splited string.
res.append(word[1:][::-1]) # here by doing "[1:]" we are eradicating number from the word & by doing "[::-1]" we are reversing back the word, that we reversed at one step of the solution. Here res will have "['This', 'is', 'a', 'sentence']
return " ".join(res) # in res we are having list of words, now we want a string with words separated -> "This is a sentence".
|
sorting-the-sentence
|
Python Easiest Solution With Explanation| 99.72% Faster | Sorting | Beg to adv
|
rlakshay14
| 3
| 219
|
sorting the sentence
| 1,859
| 0.844
|
Easy
| 26,398
|
https://leetcode.com/problems/sorting-the-sentence/discuss/1492510/1-line-solution-in-Python
|
class Solution:
def sortSentence(self, s: str) -> str:
return " ".join(word[:-1] for word in sorted(s.split(), key=lambda w: w[-1]))
|
sorting-the-sentence
|
1-line solution in Python
|
mousun224
| 2
| 292
|
sorting the sentence
| 1,859
| 0.844
|
Easy
| 26,399
|
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.