post_href stringlengths 57 213 | python_solutions stringlengths 71 22.3k | slug stringlengths 3 77 | post_title stringlengths 1 100 | user stringlengths 3 29 | upvotes int64 -20 1.2k | views int64 0 60.9k | problem_title stringlengths 3 77 | number int64 1 2.48k | acceptance float64 0.14 0.91 | difficulty stringclasses 3 values | __index_level_0__ int64 0 34k |
|---|---|---|---|---|---|---|---|---|---|---|---|
https://leetcode.com/problems/sort-array-by-parity/discuss/2151481/Python-97.35-faster-ororSimplest-solution-with-explanationoror-Beg-to-Advoror-Two-Pointer | class Solution:
def sortArrayByParity(self, nums: List[int]) -> List[int]:
left = 0 # taking first pointer
right = len(nums) - 1 # second pointer
while left < right: # as we are using two pointer technique, one pointer should be smaller then other one.
if nums[left] % 2 != 0: # we are checking if the left most element is odd or not.
nums[left], nums[right] = nums[right], nums[left] # if the left number is odd then we will put it to the last place.
right-=1 # increasing the last pointer
else:
left+=1 # in case left most element is already a even element then we are moving forward.
return nums | sort-array-by-parity | Python 97.35% faster ||Simplest solution with explanation|| Beg to Adv|| Two Pointer | rlakshay14 | 0 | 25 | sort array by parity | 905 | 0.757 | Easy | 14,700 |
https://leetcode.com/problems/sort-array-by-parity/discuss/2102977/Python-very-easy-solution | class Solution:
def sortArrayByParity(self, nums: List[int]) -> List[int]:
numeven = []
numodd =[]
for i in range(len(nums)):
if(nums[i]%2==0):
numeven.append(nums[i])
else:
numodd.append(nums[i])
return numeven+numodd | sort-array-by-parity | Python very easy solution | yashkumarjha | 0 | 26 | sort array by parity | 905 | 0.757 | Easy | 14,701 |
https://leetcode.com/problems/sort-array-by-parity/discuss/2096765/Python3-%3A-Easy-to-understand-solution-for-beginners-(One-Liner) | class Solution:
def sortArrayByParity(self, nums: List[int]) -> List[int]:
return sorted(nums,key=lambda x: x%2) | sort-array-by-parity | Python3 : Easy to understand solution for beginners (One Liner) | kushal2201 | 0 | 12 | sort array by parity | 905 | 0.757 | Easy | 14,702 |
https://leetcode.com/problems/sort-array-by-parity/discuss/2031377/Python-solution | class Solution:
def sortArrayByParity(self, nums: List[int]) -> List[int]:
ans = []
for i in nums:
if i%2 == 0:
ans.insert(0,i)
else:
ans.append(i)
return ans | sort-array-by-parity | Python solution | StikS32 | 0 | 35 | sort array by parity | 905 | 0.757 | Easy | 14,703 |
https://leetcode.com/problems/sort-array-by-parity/discuss/2027123/Python-in-place-swap-without-changing-order-easy-understanding. | class Solution:
def sortArrayByParity(self, nums: List[int]) -> List[int]:
even = 0 # The index currently contain odd, waiting for accepting a even num
for odd in range(len(nums)):
if nums[odd] % 2 == 0: # if index-odd encounter a even num, swap it with index-even.
nums[even], nums[odd] = nums[odd], nums[even] # Indices at and before index-even are even num now,
even += 1 # so even-index should go 1 step further
# ready to accept next even num
return nums | sort-array-by-parity | Python in place swap without changing order, easy-understanding. | byroncharly3 | 0 | 21 | sort array by parity | 905 | 0.757 | Easy | 14,704 |
https://leetcode.com/problems/super-palindromes/discuss/1198991/Runtime%3A-Faster-than-94.87-of-Python3-Memory-Usage-less-than-100 | class Solution:
nums = []
for i in range(1, 10**5):
odd = int(str(i)+str(i)[:-1][::-1])**2
even = int(str(i)+str(i)[::-1])**2
if str(odd) == str(odd)[::-1]:
nums.append(odd)
if str(even) == str(even)[::-1]:
nums.append(even)
nums = sorted(list(set(nums)))
def superpalindromesInRange(self, left: str, right: str) -> int:
output = []
for n in self.nums:
if int(left) <= n <= int(right):
output.append(n)
return len(output) | super-palindromes | Runtime: Faster than 94.87% of Python3 Memory Usage less than 100% | pranshusharma712 | 1 | 102 | super palindromes | 906 | 0.392 | Hard | 14,705 |
https://leetcode.com/problems/super-palindromes/discuss/2226814/Python3-Solution-with-explanation | class Solution:
def superpalindromesInRange(self, left: str, right: str) -> int:
min_num, max_num = int(left), int(right)
count, limit = 0, 20001
# odd pals
for num in range(limit + 1):
num_str = str(num)
if num_str[0] != 1 or num_str[0] != 4 or num_str[0] != 5 or num_str[0] != 6 or num_str[0] != 9:
pal = num_str + num_str[:-1][::-1]
num_sqr = int(pal) ** 2
if num_sqr > max_num:
break
if num_sqr >= min_num and str(num_sqr) == str(num_sqr)[::-1]:
count += 1
# even pals
for num in range(limit + 1):
num_str = str(num)
if num_str[0] != 1 or num_str[0] != 4 or num_str[0] != 5 or num_str[0] != 6 or num_str[0] != 9:
pal = num_str + num_str[::-1]
num_sqr = int(pal) ** 2
if len(str(num_sqr)) != 2 or len(str(num_sqr)) != 4 or len(str(num_sqr)) != 8 or \
len(str(num_sqr)) != 10 or len(str(num_sqr)) != 14 or len(str(num_sqr)) != 18:
if num_sqr > max_num:
break
if num_sqr >= min_num and str(num_sqr) == str(num_sqr)[::-1]:
count += 1
return count | super-palindromes | Python3 Solution with explanation | frolovdmn | 0 | 31 | super palindromes | 906 | 0.392 | Hard | 14,706 |
https://leetcode.com/problems/super-palindromes/discuss/1325185/Explained-Clean-Modular-Generate-All-Palindromes-and-check-their-squares | class Solution:
def pal(self, x: int) -> bool: # return whether x am pal
rev = 0
normal = x
while x:
rev = rev*10 + x%10 # push last digit to 'rev'
x = x//10 # remove last digit
return rev == normal
# O(root(n) x log (n)) -> since i generate left half until square(left_half+right_half) reaches
# the 'right' now, why is this passing and below solution TLE? because here i only generate palindromes!
def superpalindromesInRange(self, left: str, right: str) -> int:
left, right = int(left), int(right)
# guess the half of every palindrome,
# generate the other half (reverse)!
left_half = 1
ans = 0
while True: # no need of MAGIC, just stop when all my options > right
right_half = str(left_half)[::-1]
even_palindrome = int(str(left_half) + right_half)
odd_palindrome = int(str(left_half) + right_half[1:])
# print(even_palindrome, odd_palindrome)
even_pal_sqr = even_palindrome*even_palindrome
odd_pal_sqr = odd_palindrome*odd_palindrome
# if (in range) AND (is a palindrome)
if left <= even_pal_sqr <= right and self.pal(even_pal_sqr):
ans += 1
if left <= odd_pal_sqr <= right and self.pal(odd_pal_sqr):
ans += 1
# no more palindromes will be found!
if even_pal_sqr > right and odd_pal_sqr > right:
return ans
left_half += 1
def superpalindromesInRangeTLE(self, left: str, right: str) -> int:
left, right = int(left), int(right)
check = floor(sqrt(left))
while check*check < left:
check += 1
res = 0
while check*check <= right:
if self.pal(check) and self.pal(check*check):
res += 1
check += 1
return res | super-palindromes | Explained Clean Modular Generate All Palindromes and check their squares | yozaam | 0 | 84 | super palindromes | 906 | 0.392 | Hard | 14,707 |
https://leetcode.com/problems/super-palindromes/discuss/1198108/python-ez-understanding-solution | class Solution:
def superpalindromesInRange(self, left: str, right: str) -> int:
left,right = int(left),int(right)
limit = 100000
count = 0
for i in range(limit):
s = str(i)
# 121 -> 12121 and 121121
s1 = s + s[::-1][1:]
s2 = s + s[::-1]
tmp1,tmp2 = pow(int(s1),2),pow(int(s2),2)
if (tmp1 > right):
break
if str(tmp1) == str(tmp1)[::-1] and int(tmp1) >= left:
count += 1
if str(tmp2) == str(tmp2)[::-1] and tmp1 != tmp2 and int(tmp2) <= right and int(tmp2) >= left:
count += 1
return count | super-palindromes | python ez understanding solution | yingziqing123 | 0 | 74 | super palindromes | 906 | 0.392 | Hard | 14,708 |
https://leetcode.com/problems/super-palindromes/discuss/1197664/PythonPython3-solution-with-Explanation | class Solution:
def superpalindromesInRange(self, left: str, right: str) -> int:
left,right = int(left),int(right)
#Just to travese the loop declare a variable and set the limit
limit = 100000
#to count super Palindromes
cnt = 0
#count odd number length palindromes
for i in range(1,limit):
# to add the the numbers it easily I have converted it to string
s = str(i)
# add s with s in the reverse order by leaving the 1st element so that we will get odd number length string
p = s+s[::-1][1:]#or U can use negative indexing s[-2::-1]
#square the number we got
p2 = int(p) ** 2
#if the squares number of p is greater than right value break the loop
if p2 > right:
break
#if squared value of p is greater than or equal to left and and the reversal of that squares value is also a palindrome then increase the count
if p2 >=left and str(p2) == str(p2)[::-1]:
#print(p,p2)
cnt += 1
#to count even number length palindromes
for i in range(limit):
# to add the the numbers it easily I have converted it to string
s = str(i)
# add s with s in the reverse order so that we will get even number length string
p = s + s[::-1]
#square the number we got
p2 = int(p) ** 2
#if the squares number of p is greater than right value break the loop
if p2 > right:
break
#if squared value of p is greater than or equal to left and and the reversal of that squares value is also a palindrome then increase the count
if p2 >= left and str(p2) == str(p2)[::-1]:
#print(p,p2)
cnt += 1
return cnt | super-palindromes | Python/Python3 solution with Explanation | prasanthksp1009 | 0 | 178 | super palindromes | 906 | 0.392 | Hard | 14,709 |
https://leetcode.com/problems/super-palindromes/discuss/1197616/python3-build-palindromes-solution-for-reference. | class Solution:
def superpalindromesInRange(self, left: str, right: str) -> int:
a = set()
ileft = int(left)
iright = int(right)
res = 0
for i in range(10):
isq = i**2
if isq >= ileft and isq <= iright and str(isq) == str(isq)[::-1]:
res += 1
for idx in range(1, 10000):
# even length palindromes
sidx = str(idx)
sidxr = str(idx)[::-1]
even = sidx+sidxr
ieven = int(even)**2
if ieven >= ileft and ieven <= iright and str(ieven) == str(ieven)[::-1]:
res += 1
for j in range(10):
odd = sidx + str(j) + sidxr
iodd = int(odd)**2
if iodd >= ileft and iodd <= iright and str(iodd) == str(iodd)[::-1]:
res += 1
return res | super-palindromes | [python3] build palindromes solution for reference. | vadhri_venkat | 0 | 92 | super palindromes | 906 | 0.392 | Hard | 14,710 |
https://leetcode.com/problems/super-palindromes/discuss/1168245/Python3-Easy-approach-or-Explanation-and-Comments-added | class Solution:
def superpalindromesInRange(self, left: str, right: str) -> int:
'''
1. For each number in the range [floor(square root of integer value of left), floor(square root of integer value of right)],
- need to check if the number is palindrome and (number^2) is palindrome
2. One possible way to do this quicker is
- to generate all the palindromes within the range [floor(square root of integer value of left), floor(square root of integer value of right)]
- and check whether the square of this palindrome is also a palindrome
3. If [floor(square root of integer value of left)] is of x digits and [floor(square root of integer value of right)] is of y digits, then
- if x>1: start generating palindrome from the lowest number of x digits that is divisible by 10, else: start generating palindrome from 1
- generate palindrome upto the highest number of y digits that is 999...9 (y 9's)
4. To generate palindromes of x and y digits, we need to check only the first ceil(x/2) digits and ceil(y/2) digits
of [floor(square root of integer value of left)] and [floor(square root of integer value of right)] respectively
'''
cnt = 0
lft = str(int(int(left)**0.5))
rght = str(int(int(right)**0.5))
lft_1 = lft
rght_1 = rght
if len(lft)%2:
lft = "1"+"0"*((len(lft)//2))
else:
lft = "1"+"0"*((len(lft)//2)-1) #getting the value from where palindromes are started to be generated
if len(rght)%2:
rght = "9"*((len(rght)//2)+1)
else:
rght = "9"*(len(rght)//2) #getting the value upto which palindromes are generated
for num in range(int(lft),int(rght)+1):
num=str(num)
len_string=len(num)
if (len_string*2)-1 >= len(lft_1): #length of palindrome must be greater than or equal the given 'left' string parameter
str_N_1 = num[0:len_string-1]+num[len_string-1]+num[0:len_string-1][::-1] #generate an odd length palindrome by appending the num string in two opposite orders, and keep the middle character fixed
sq_1 = str(int(str_N_1)**2) #generate the string representation of the square of the palindrome integer
if int(left) <= int(sq_1) <= int(right) and sq_1==sq_1[::-1]: #square is palindrome and within the given left and right parameters
cnt+=1 #increment the result by 1
if len_string*2 <= len(rght_1): #length of palindrome must be less than or equal the given 'right' string parameter
str_N_2 = num+num[::-1] #generate an even length palindrome by appending the num string in two opposite orders
sq_2 = str(int(str_N_2)**2)
if int(left) <= int(sq_2) <= int(right) and sq_2==sq_2[::-1]:
cnt+=1
return cnt | super-palindromes | Python3 Easy approach | Explanation and Comments added | bPapan | 0 | 201 | super palindromes | 906 | 0.392 | Hard | 14,711 |
https://leetcode.com/problems/sum-of-subarray-minimums/discuss/2846444/Python-3Monotonic-stack-boundry | class Solution:
def sumSubarrayMins(self, arr: List[int]) -> int:
M = 10 ** 9 + 7
# right bound for current number as minimum
q = []
n = len(arr)
right = [n-1] * n
for i in range(n):
# must put the equal sign to one of the bound (left or right) for duplicate nums (e.g. [71, 55, 82, 55])
while q and arr[i] <= arr[q[-1]]:
right[q.pop()] = i - 1
q.append(i)
# left bound for current number as minimum
q = []
left = [0] * n
for i in reversed(range(n)):
while q and arr[i] < arr[q[-1]]:
left[q.pop()] = i + 1
q.append(i)
# calculate sum for each number
ans = 0
for i in range(n):
l, r = abs(i - left[i]), abs(i - right[i])
# for example: xx1xxx
# left take 0, 1, 2 numbers (3 combs) and right take 0, 1, 2, 3 numbers (4 combs)
covered = (l + 1) * (r + 1)
ans = (ans + arr[i] * covered) % M
return ans | sum-of-subarray-minimums | [Python 3]Monotonic stack boundry | chestnut890123 | 10 | 475 | sum of subarray minimums | 907 | 0.346 | Medium | 14,712 |
https://leetcode.com/problems/sum-of-subarray-minimums/discuss/2212520/Python-solution-not-sure-whether-it-is-easy-understanding.... | class Solution:
def sumSubarrayMins(self, arr: List[int]) -> int:
res = 0
stack = [-1] # We are adopting increasing stack to solve this problem.
arr += [0] # The trick is as same as problem 84,
# put 0 in the last of arr, also keeping stack[0] always the smallest element without affecting res.
for i in range(len(arr)):
while arr[i] < arr[stack[-1]]:
mid = stack.pop() # mid is the idx of "num" which is the smallest element in current interval.
num = arr[mid]
right = i # "right" is the right first element smaller than "num"
left = stack[-1] # "left" is the left first element smaller than "num"
res += num * (right-mid) * (mid-left)
stack.append(i)
return res % (10**9 + 7) | sum-of-subarray-minimums | Python solution not sure whether it is easy-understanding.... | byroncharly3 | 7 | 373 | sum of subarray minimums | 907 | 0.346 | Medium | 14,713 |
https://leetcode.com/problems/sum-of-subarray-minimums/discuss/2847805/Python-O(n)-Stack-Video-Solution-Picture | class Solution:
def sumSubarrayMins(self, A: List[int]) -> int:
A = [-math.inf] + A + [-math.inf]
n = len(A)
st = []
res = 0
for i in range(n):
while st and A[st[-1]] > A[i]: # monotonic increasing stack
mid = st.pop()
left = st[-1] # previous smaller element
right = i #next smaller element
res += A[mid] * (mid - left) * (right - mid)
st.append(i)
return res %(10**9 + 7) | sum-of-subarray-minimums | [Python] O(n) - Stack - Video Solution - Picture | cheatcode-ninja | 3 | 64 | sum of subarray minimums | 907 | 0.346 | Medium | 14,714 |
https://leetcode.com/problems/sum-of-subarray-minimums/discuss/1732965/python-3-monotonic-stack-O(n)-O(n) | class Solution:
def sumSubarrayMins(self, nums: List[int]) -> int:
M = 10 ** 9 + 7
res = 0
stack = []
n = len(nums)
nums.append(0)
for i, num in enumerate(nums):
while stack and (i == n or num < nums[stack[-1]]):
top = stack.pop()
starts = top - stack[-1] if stack else top + 1
ends = i - top
res += starts * ends * nums[top]
res %= M
stack.append(i)
return res | sum-of-subarray-minimums | python 3, monotonic stack, O(n) / O(n) | dereky4 | 3 | 1,000 | sum of subarray minimums | 907 | 0.346 | Medium | 14,715 |
https://leetcode.com/problems/sum-of-subarray-minimums/discuss/2847814/Python-(Faster-than-99.9)-or-Stack-with-DP-solution | class Solution:
def sumSubarrayMins(self, arr: List[int]) -> int:
mod = (10 ** 9) + 7
stack = []
dp = [0] * len(arr)
for i, n in enumerate(arr):
while stack and arr[stack[-1]] >= n:
stack.pop()
if stack:
dp[i] = dp[stack[-1]] + (n * (i - stack[-1]))
else:
dp[i] = n * (i + 1)
stack.append(i)
return sum(dp) % mod | sum-of-subarray-minimums | Python (Faster than 99.9%) | Stack with DP solution | KevinJM17 | 2 | 40 | sum of subarray minimums | 907 | 0.346 | Medium | 14,716 |
https://leetcode.com/problems/sum-of-subarray-minimums/discuss/2847050/Easy-using-Stack-O(n)-Solution | class Solution:
def sumSubarrayMins(self, nums):
MOD = 10**9+7
stack = []
res = 0
prevsum = 0
for index, value in enumerate(nums):
count = 1
while stack and stack[-1][0]>=value:
v, c = stack.pop()
count+=c
prevsum-=v*c
stack.append((value,count))
prevsum+=value*count
res+=prevsum
return res%MOD | sum-of-subarray-minimums | Easy using Stack O(n) Solution | namanxk | 2 | 200 | sum of subarray minimums | 907 | 0.346 | Medium | 14,717 |
https://leetcode.com/problems/sum-of-subarray-minimums/discuss/2106623/Python-O(n)-m*n-trick-explained | class Solution:
def sumSubarrayMins(self, A: List[int]) -> int:
n = len(A)
next_smaller = [n] * n
prev_smaller = [0] * n
ns_s = []
ps_s = []
for i, a in enumerate(A):
while ns_s and A[ns_s[-1]] > a:
j = ns_s.pop()
next_smaller[j] = i
ns_s.append(i)
while ps_s and A[ps_s[-1]] > a:
ps_s.pop()
if ps_s:
prev_smaller[i] = ps_s[-1]
else:
prev_smaller[i] = -1
ps_s.append(i)
res = 0
for i, a in enumerate(A):
res += (i - prev_smaller[i]) * a * (next_smaller[i] - i)
return res % (10**9 + 7) | sum-of-subarray-minimums | Python O(n), m*n trick explained | rajabi | 2 | 261 | sum of subarray minimums | 907 | 0.346 | Medium | 14,718 |
https://leetcode.com/problems/sum-of-subarray-minimums/discuss/2848658/Python-solution | class Solution:
def sumSubarrayMins(self, arr: List[int]) -> int:
stack = []
res = 0
arr = [float('-inf')] + arr + [float('-inf')]
for i, num in enumerate(arr):
while stack and arr[stack[-1]] > num:
cur = stack.pop()
res += arr[cur] * (i - cur) * (cur - stack[-1])
stack.append(i)
return res % (10**9 + 7) | sum-of-subarray-minimums | Python solution | user2854aZ | 1 | 7 | sum of subarray minimums | 907 | 0.346 | Medium | 14,719 |
https://leetcode.com/problems/sum-of-subarray-minimums/discuss/2847891/Monotic-Stack-Based-Solutionoror-TC%3AO(n)-oror-SC%3A-O(n) | class Solution:
def sumSubarrayMins(self, arr: List[int]) -> int:
size = len(arr)
mod = (10 ** 9) + 7
#NSE_L, NSE_R stores the idx of nearest left and nearest right elements
def nextSmaller_Left(arr):
ans = [-1] * size
stack = [0]
for idx in range(1,size):
curr_elem = arr[idx]
while stack and curr_elem <= arr[stack[-1]]:
stack.pop()
if stack:
ans[idx] = stack[-1]
stack.append(idx)
return ans
def nextSmaller_Right(arr):
ans = [size] * size
stack = [size-1]
for idx in range(size-2,-1,-1):
curr_elem = arr[idx]
while stack and curr_elem < arr[stack[-1]]:
stack.pop()
if stack:
ans[idx] = stack[-1]
stack.append(idx)
return ans
res = 0
left, right = nextSmaller_Left(arr), nextSmaller_Right(arr)
for idx in range(size):
val = arr[idx]
left_contri = idx - left[idx]
right_contri = right[idx] - idx
contri = val * left_contri * right_contri
res += contri
return res % mod | sum-of-subarray-minimums | Monotic Stack Based Solution|| TC:O(n) || SC: O(n) | s_m_d_29 | 1 | 24 | sum of subarray minimums | 907 | 0.346 | Medium | 14,720 |
https://leetcode.com/problems/sum-of-subarray-minimums/discuss/2847025/7-LINES-oror-EASY-PYTHON-SOLUTIONoror-BEGINER-FRIENDLYoror-USING-STACK | class Solution:
def sumSubarrayMins(self, arr: List[int]) -> int:
mod=10**9+7
stack=[]
dp=[0]*len(arr)
for i in range(len(arr)):
while stack and arr[stack[-1]]>=arr[i]:
stack.pop()
if stack:
presmall=stack[-1]
dp[i]=dp[presmall]+(i-presmall)*arr[i]
else:
dp[i]=(i+1)*arr[i]
stack.append(i)
return sum(dp)%mod | sum-of-subarray-minimums | 7 LINES || EASY PYTHON SOLUTION|| BEGINER FRIENDLY|| USING STACK | thezealott | 1 | 81 | sum of subarray minimums | 907 | 0.346 | Medium | 14,721 |
https://leetcode.com/problems/sum-of-subarray-minimums/discuss/2846538/python3-Solution | class Solution:
def sumSubarrayMins(self, arr: List[int]) -> int:
n=len(arr)
left=[1]*n
dec_q=[(arr[0],1)]
for i in range(1,n):
while dec_q and arr[i]<=dec_q[-1][0]:
left[i]+=dec_q.pop()[1]
dec_q.append((arr[i],left[i]))
right=[1]*n
dec_q=[(arr[-1],1)]
for i in range(n-2,-1,-1):
while dec_q and arr[i]<dec_q[-1][0]:
right[i]+=dec_q.pop()[1]
dec_q.append((arr[i], right[i]))
ans=0
for i in range(n):
ans+=arr[i]*left[i]*right[i]
mod=10**9+7
return ans%mod | sum-of-subarray-minimums | python3 Solution | Motaharozzaman1996 | 1 | 90 | sum of subarray minimums | 907 | 0.346 | Medium | 14,722 |
https://leetcode.com/problems/sum-of-subarray-minimums/discuss/949064/Python3-stack-O(N) | class Solution:
def sumSubarrayMins(self, arr: List[int]) -> int:
ans, stack = [], []
for i, x in enumerate(arr):
while stack and arr[stack[-1]] >= x: stack.pop() # mono-stack (increasing)
if stack:
ii = stack[-1]
ans.append(ans[ii] + x*(i-ii))
else: ans.append(x * (i+1))
stack.append(i)
return sum(ans) % 1_000_000_007 | sum-of-subarray-minimums | [Python3] stack O(N) | ye15 | 1 | 574 | sum of subarray minimums | 907 | 0.346 | Medium | 14,723 |
https://leetcode.com/problems/sum-of-subarray-minimums/discuss/949064/Python3-stack-O(N) | class Solution:
def sumSubarrayMins(self, arr: List[int]) -> int:
ans = 0
stack = []
for i in range(len(arr)+1):
while stack and (i == len(arr) or arr[stack[-1]] > arr[i]):
mid = stack.pop()
ii = stack[-1] if stack else -1
ans += arr[mid] * (i - mid) * (mid - ii)
stack.append(i)
return ans % 1_000_000_007 | sum-of-subarray-minimums | [Python3] stack O(N) | ye15 | 1 | 574 | sum of subarray minimums | 907 | 0.346 | Medium | 14,724 |
https://leetcode.com/problems/sum-of-subarray-minimums/discuss/2848867/Why-my-brute-force-O(n2)-solution-failed-in-big-test-case | class Solution:
def sumSubarrayMins(self, arr: List[int]) -> int:
res = 0
cur_min = 0
for l in range(len(arr)):
cur_min = arr[l]
for r in range(l, len(arr)):
cur_min = min(cur_min, arr[r])
res += cur_min
return res | sum-of-subarray-minimums | Why my brute force O(n^2) solution failed in big test case? | TestCeline | 0 | 4 | sum of subarray minimums | 907 | 0.346 | Medium | 14,725 |
https://leetcode.com/problems/sum-of-subarray-minimums/discuss/2848492/Python-O(N)-using-monotonic-stack | class Solution:
def sumSubarrayMins(self, arr: List[int]) -> int:
stack, rez = deque(), 0
for a in arr:
cnt_subarrays, cnt_ends = 0, 1
while stack and stack[-1][0] > a:
val, cnt_starts = stack.pop()
cnt_subarrays = cnt_starts*cnt_ends
cnt_ends += cnt_starts
rez = (rez + val*cnt_subarrays) % (10**9 + 7)
stack.append((a, cnt_ends))
cnt_subarrays, cnt_ends = 0, 1
while stack:
val, cnt_starts = stack.pop()
cnt_subarrays = cnt_starts*cnt_ends
cnt_ends += cnt_starts
rez = (rez + val*cnt_subarrays) % (10**9 + 7)
return rez | sum-of-subarray-minimums | [Python] O(N) using monotonic stack | nonchalant-enthusiast | 0 | 9 | sum of subarray minimums | 907 | 0.346 | Medium | 14,726 |
https://leetcode.com/problems/sum-of-subarray-minimums/discuss/2848330/Monotonic-Stack-O(n)-next-smaller-number | class Solution:
def sumSubarrayMins(self, arr: List[int]) -> int:
l = len(arr)
stack = []
total = 0
for i in range(l+1):
while stack and (i==l or arr[stack[-1]] >= arr[i] ):
mid = stack.pop()
right_bound = i
left_bound = stack[-1] if stack else -1
total = (total + (right_bound-mid)*(mid-left_bound)*arr[mid])%(10**9+7)
stack.append(i)
return total | sum-of-subarray-minimums | Monotonic Stack - O(n) - next smaller number | DavidCastillo | 0 | 16 | sum of subarray minimums | 907 | 0.346 | Medium | 14,727 |
https://leetcode.com/problems/sum-of-subarray-minimums/discuss/2848294/Python-easy-to-read-and-understand-or-stack | class Solution:
def nsr(self, nums):
n = len(nums)
stack, index, res = [], [], []
i = len(nums)-1
while i >= 0:
if len(stack) == 0:
res.append(n-i)
elif len(stack) > 0 and stack[-1] < nums[i]:
res.append(index[-1]-i)
elif len(stack) > 0 and stack[-1] >= nums[i]:
stack.pop()
index.pop()
while len(stack) > 0 and stack[-1] >= nums[i]:
stack.pop()
index.pop()
if len(stack) == 0:
res.append(n-i)
elif len(stack) > 0 and stack[-1] < nums[i]:
res.append(index[-1]-i)
stack.append(nums[i])
index.append(i)
i = i-1
return res[::-1]
def nsl(self, nums):
temp = -1
stack, index, res = [], [], []
for i in range(len(nums)):
if len(stack) == 0:
res.append(i-temp)
elif len(stack) > 0 and stack[-1] <= nums[i]:
res.append(i-index[-1])
elif len(stack) > 0 and stack[-1] > nums[i]:
stack.pop()
index.pop()
while len(stack) > 0 and stack[-1] > nums[i]:
stack.pop()
index.pop()
if len(stack) == 0:
res.append(i-temp)
elif len(stack) > 0 and stack[-1] <= nums[i]:
res.append(i-index[-1])
stack.append(nums[i])
index.append(i)
return res
def sumSubarrayMins(self, arr: List[int]) -> int:
right = self.nsr(arr)
left = self.nsl(arr)
#print(left, right)
ans = 0
for i in range(len(arr)):
ans += (left[i]*right[i]*arr[i])
return ans% (10**9 + 7) | sum-of-subarray-minimums | Python easy to read and understand | stack | sanial2001 | 0 | 12 | sum of subarray minimums | 907 | 0.346 | Medium | 14,728 |
https://leetcode.com/problems/sum-of-subarray-minimums/discuss/2848080/Python3-solution | class Solution:
def sumSubarrayMins(self, arr: List[int]) -> int:
s, res = [-1], 0
arr += [0] # a trick to get rid of boundary checks
for i, n in enumerate(arr):
while arr[s[-1]] > n:
j, k = s.pop(), s[-1]
res += (j-k)*(i-j)*arr[j]
s.append(i)
return res % 1_000_000_007 | sum-of-subarray-minimums | Python3 solution | avs-abhishek123 | 0 | 17 | sum of subarray minimums | 907 | 0.346 | Medium | 14,729 |
https://leetcode.com/problems/sum-of-subarray-minimums/discuss/2847967/Best-approach-ever-with-less-time-complexity | class Solution:
def sumSubarrayMins(self, arr: List[int]) -> int:
kMod = 1_000_000_007
n = len(arr)
ans = 0
# prev[i] := index k s.t. arr[k] is the prev min in arr[:i]
prev = [-1] * n
# next[i] := index k s.t. arr[k] is the next min in arr[i + 1:]
next = [n] * n
stack = []
for i, a in enumerate(arr):
while stack and arr[stack[-1]] > a:
index = stack.pop()
next[index] = i
if stack:
prev[i] = stack[-1]
stack.append(i)
for i, a in enumerate(arr):
ans += a * (i - prev[i]) * (next[i] - i)
ans %= kMod
return ans | sum-of-subarray-minimums | Best approach ever with less time complexity | VivekSingh05 | 0 | 15 | sum of subarray minimums | 907 | 0.346 | Medium | 14,730 |
https://leetcode.com/problems/sum-of-subarray-minimums/discuss/2847704/Python3-easy-DP-Stack | class Solution:
def sumSubarrayMins(self, arr: List[int]) -> int:
ans = 0
cache = 0
stack = []
count = []
for val in arr:
num = 1
while stack and stack[-1] >= val:
cache -= stack.pop() * count[-1]
num += count.pop()
stack.append(val)
count.append(num)
cache += val * num
ans += cache
return ans % (10**9 + 7) | sum-of-subarray-minimums | Python3 easy DP Stack | Nesop | 0 | 12 | sum of subarray minimums | 907 | 0.346 | Medium | 14,731 |
https://leetcode.com/problems/sum-of-subarray-minimums/discuss/2847672/Simple-approach | class Solution:
def sumSubarrayMins(self, arr: List[int]) -> int:
s1,s2,left,right=[],[],[0]*len(arr),[0]*len(arr)
for i in range(len(arr)):
curr = arr[i]
count=1
while s1 and s1[-1][0]>curr:
count+=s1[-1][1]
s1.pop()
left[i]=count
s1.append((arr[i],count))
for i in range(len(arr)-1,-1,-1):
curr,count=arr[i],1
while s2 and s2[-1][0]>=curr:
count+=s2[-1][1]
s2.pop()
right[i]=count
s2.append((arr[i],count))
print(left,right)
ans=0
for i in range(len(arr)):
ans+= (arr[i]*left[i]*right[i])
return ans%(10**9+7) | sum-of-subarray-minimums | Simple approach | parasgarg31 | 0 | 10 | sum of subarray minimums | 907 | 0.346 | Medium | 14,732 |
https://leetcode.com/problems/sum-of-subarray-minimums/discuss/2847643/Monotonic-Stack-Solution | class Solution:
def sumSubarrayMins(self, arr: List[int]) -> int:
mod = 10**9 + 7
stack = []
total = 0
for i in range(len(arr)+1):
while stack and (len(arr)==i or arr[stack[-1]] >= arr[i]):
mid = stack.pop()
end = stack[-1] if stack else -1
total += arr[mid]*(i-mid)*(mid-end)
stack.append(i)
return total%mod | sum-of-subarray-minimums | Monotonic Stack Solution | Karthikjb | 0 | 7 | sum of subarray minimums | 907 | 0.346 | Medium | 14,733 |
https://leetcode.com/problems/sum-of-subarray-minimums/discuss/2847520/Easy-to-understand-optimal-python-O(n)-solution | class Solution:
def sumSubarrayMins(self, arr: List[int]) -> int:
res = 0
min_stack = [] # (min, count, total_sum)
for i in range(len(arr)):
num = arr[i]
count = 1
while min_stack and num <= min_stack[-1][0]:
count += min_stack.pop()[1] # count how many previous mincan be replaced by this new min
if min_stack:
min_stack.append((num, count, min_stack[-1][2] + num*count))
else:
min_stack.append((num, count, num*count))
res += min_stack[-1][2]
return res % (10 ** 9 + 7) | sum-of-subarray-minimums | Easy to understand optimal python O(n) solution | Priceincoding | 0 | 10 | sum of subarray minimums | 907 | 0.346 | Medium | 14,734 |
https://leetcode.com/problems/sum-of-subarray-minimums/discuss/2847154/Python-official-solution-(Fast) | class Solution:
def sumSubarrayMins(self, arr: List[int]) -> int:
MOD = 10 ** 9 + 7
# monotonic increasing stack
stack = []
# make a dp array of the same size as the input array
dp = [0] * len(arr)
# populate monotonically increasing stack
for i in range(len(arr)):
# before pushing an element, make sure all
# larger and equal elements in the stack are
# removed
while stack and arr[stack[-1]] >= arr[i]:
stack.pop()
# calculate the sum of minimums of all subarrays
# ending at index i
if stack:
previousSmaller = stack[-1]
dp[i] = dp[previousSmaller] + (i - previousSmaller) * arr[i]
else:
dp[i] = (i + 1) * arr[i]
stack.append(i)
# add all the elements of dp to get the answer
return sum(dp) % MOD | sum-of-subarray-minimums | Python official solution (Fast) | subidit | 0 | 19 | sum of subarray minimums | 907 | 0.346 | Medium | 14,735 |
https://leetcode.com/problems/sum-of-subarray-minimums/discuss/2846950/Python3O(n)-Two-mono-stack-to-get-left-and-right | class Solution:
def sumSubarrayMins(self, arr: List[int]) -> int:
n = len(arr)
left, right = list(range(n)), list(range(n))
stk = []
for i in range(n):
while stk and arr[stk[-1]] >= arr[i]: right[stk.pop()] = i - 1
stk.append(i)
while stk: right[stk.pop()] = n - 1
for i in range(n - 1, -1, -1):
while stk and arr[stk[-1]] > arr[i]: left[stk.pop()] = i + 1
stk.append(i)
while stk: left[stk.pop()] = 0
ans, MOD = 0, 10 ** 9 + 7
for i in range(n):
l, r = i - left[i] + 1, right[i] - i + 1
ans = (ans + l * r * arr[i]) % MOD
return ans | sum-of-subarray-minimums | [Python3]O(n) Two mono stack to get left and right | cava | 0 | 10 | sum of subarray minimums | 907 | 0.346 | Medium | 14,736 |
https://leetcode.com/problems/sum-of-subarray-minimums/discuss/2846918/DP-or-Top-down-and-Bottom-Up-or-Short-solution | class Solution:
def sumSubarrayMins(self, arr: List[int]) -> int:
n = len(arr)
MOD = 10**9 + 7
next_smaller = [n] * n
# next_smaller[i] = index of next element which is smaller than arr[i]
# if no such element exist, next_smaller[i] = n
stack = []
for i in range(n):
while stack and arr[stack[-1]] >= arr[i]:
next_smaller[stack.pop()] = i
stack.append(i)
dp = [0] * (n+1)
dp[-2] = arr[-1]
for i in range(n-2, -1, -1):
dp[i] = arr[i] * (next_smaller[i] - i) + dp[next_smaller[i]]
return sum(dp) % MOD | sum-of-subarray-minimums | DP | Top-down & Bottom-Up | Short solution | xyp7x | 0 | 44 | sum of subarray minimums | 907 | 0.346 | Medium | 14,737 |
https://leetcode.com/problems/sum-of-subarray-minimums/discuss/2846918/DP-or-Top-down-and-Bottom-Up-or-Short-solution | class Solution:
def sumSubarrayMins(self, arr: List[int]) -> int:
n = len(arr)
MOD = 10**9 + 7
next_smaller = [n] * n
# next_smaller[i] = index of next element which is smaller than arr[i]
# if no such element exist, next_smaller[i] = n
stack = []
for i in range(n):
while stack and arr[stack[-1]] >= arr[i]:
next_smaller[stack.pop()] = i
stack.append(i)
@lru_cache(None)
def minSumIncluding(i):
return (next_smaller[i]-i) * arr[i] + minSumIncluding(next_smaller[i]) if i < n else 0
return sum(minSumIncluding(i) for i in range(n)) % MOD | sum-of-subarray-minimums | DP | Top-down & Bottom-Up | Short solution | xyp7x | 0 | 44 | sum of subarray minimums | 907 | 0.346 | Medium | 14,738 |
https://leetcode.com/problems/sum-of-subarray-minimums/discuss/2846682/Python-solution-without-using-stack-or-easy-solution-and-another-one-with-stack | class Solution:
def sumSubarrayMins(self, arr: List[int]) -> int:
res=[[]]
s=0
for i in range(len(arr)+1):
for j in range(i):
res.append(arr[j:i])
for i in range(1,len(res)):
s+=min(res[i])
return s
################ Solution using stack ########################
mod, res, stack = 1000000007, 0, []
for i in range(len(arr)):
while stack and arr[i] <= arr[stack[-1]]:
idx = stack.pop()
l, r = stack[-1] if stack else -1, i
res += (r-idx) * (idx-l) * arr[idx]
res %= mod
stack.append(i)
while stack:
idx = stack.pop()
l, r = stack[-1] if stack else -1, len(arr)
res += (r-idx) * (idx-l) * arr[idx]
res %= mod
return res | sum-of-subarray-minimums | Python solution without using stack | easy solution and another one with stack | ashishneo | 0 | 16 | sum of subarray minimums | 907 | 0.346 | Medium | 14,739 |
https://leetcode.com/problems/sum-of-subarray-minimums/discuss/2652363/Python-solution-with-stack | class Solution:
def sumSubarrayMins(self, arr: List[int]) -> int:
# get the index of the first previous value that is less than the current one.
# if there is no value less than the current one in the previous array
# set the index as -1 which means all previous values are larger than
# the current one so we can include all the previous array in the subarray
# with current index as the minimun.
prev_less_index = [-1] * len(arr)
stack = []
for i, val in enumerate(arr):
while stack and arr[stack[-1]] > val:
stack.pop()
prev_less_index[i] = stack[-1] if stack else - 1
stack.append(i)
# with similar logtic, get the first index of following values that is less than
# the current one.
next_less_index = [len(arr)] * len(arr)
stack = []
for i, val in enumerate(arr):
while stack and arr[stack[-1]] > val:
next_less_index[stack.pop()] = i
stack.append(i)
res = 0
for i, val in enumerate(arr):
res = (res + val * (i - prev_less_index[i]) * (next_less_index[i] - i)) % 1_000_000_007
return res | sum-of-subarray-minimums | Python solution with stack | michaelniki | 0 | 35 | sum of subarray minimums | 907 | 0.346 | Medium | 14,740 |
https://leetcode.com/problems/smallest-range-i/discuss/535164/Python-O(n)-by-min-and-Max.-85%2B-w-Visualization | class Solution:
def smallestRangeI(self, A: List[int], K: int) -> int:
M, m = max(A), min(A)
diff, extension = M - m, 2*K
if diff <= extension:
return 0
else:
return diff - extension | smallest-range-i | Python O(n) by min & Max. 85%+ [w/ Visualization ] | brianchiang_tw | 17 | 872 | smallest range i | 908 | 0.678 | Easy | 14,741 |
https://leetcode.com/problems/smallest-range-i/discuss/1383929/pytthon3-%3A-simple-approach | class Solution:
def smallestRangeI(self, nums: List[int], k: int) -> int:
if len(nums) <=1:
return 0
diff=max(nums)-min(nums)
## diff after
new_diff=diff-2*k
if new_diff < 0:
return 0
else:
return new_diff | smallest-range-i | pytthon3 : simple approach | p_a | 2 | 119 | smallest range i | 908 | 0.678 | Easy | 14,742 |
https://leetcode.com/problems/smallest-range-i/discuss/362139/Solution-in-Python-3-(beats-~100)-(one-line) | class Solution:
def smallestRangeI(self, A: List[int], K: int) -> int:
return max(0, max(A) - min(A) - 2*K)
- Junaid Mansuri
(LeetCode ID)@hotmail.com | smallest-range-i | Solution in Python 3 (beats ~100%) (one line) | junaidmansuri | 2 | 342 | smallest range i | 908 | 0.678 | Easy | 14,743 |
https://leetcode.com/problems/smallest-range-i/discuss/2848427/Simple-Python-Solution-with-Min-and-Max | class Solution:
def smallestRangeI(self, nums: List[int], k: int) -> int:
if len(set(nums)) == 1:
return 0
mini,maxi = min(nums),max(nums)
if abs(mini - maxi) <=2*k:
return 0
else:
return (maxi - k ) - (mini + k) | smallest-range-i | Simple Python Solution with Min and Max | vijay_2022 | 0 | 1 | smallest range i | 908 | 0.678 | Easy | 14,744 |
https://leetcode.com/problems/smallest-range-i/discuss/2848017/Easy-To-Understand-Python-Solution-Beats-79.12! | class Solution:
def smallestRangeI(self, nums: List[int], k: int) -> int:
a = max(nums)
b = min(nums)
#Since the minimum output we can get is 0 due to ranges being unable to have negative length,
#the ideal situation is: max(nums)-x == min(nums)-y, x and y in range [-k,k]
#And this means: max(nums)-k <= min(nums)+k or max(nums) - min(nums) <= 2*k
#If that is the case we return 0
if a - b <= 2*k:
return 0
#If not then we get max(nums) and min(nums) as close as possible
#through : (max(nums)-k) - (min(nums) + k) == max(nums) - min(nums) - 2*k
return a - b - 2*k | smallest-range-i | Easy To Understand Python Solution Beats 79.12%! | dmeirLmas | 0 | 2 | smallest range i | 908 | 0.678 | Easy | 14,745 |
https://leetcode.com/problems/smallest-range-i/discuss/2787650/Very-Easy-to-Understand-or-Aditya-Bahl-or-C%2B%2B-Java-Python-Python-C-JavaScript-Kotlin | class Solution(object):
def smallestRangeI(self, nums, k):
return max(0, max(nums) - min(nums) - 2 * k) | smallest-range-i | Very Easy to Understand 💯💯 | Aditya Bahl | C++, Java, Python, Python, C#, JavaScript, Kotlin | adityabahl | 0 | 12 | smallest range i | 908 | 0.678 | Easy | 14,746 |
https://leetcode.com/problems/smallest-range-i/discuss/2787650/Very-Easy-to-Understand-or-Aditya-Bahl-or-C%2B%2B-Java-Python-Python-C-JavaScript-Kotlin | class Solution:
def smallestRangeI(self, nums: List[int], k: int) -> int:
return max(0, max(nums) - min(nums) - 2 * k) | smallest-range-i | Very Easy to Understand 💯💯 | Aditya Bahl | C++, Java, Python, Python, C#, JavaScript, Kotlin | adityabahl | 0 | 12 | smallest range i | 908 | 0.678 | Easy | 14,747 |
https://leetcode.com/problems/smallest-range-i/discuss/2545356/python-easy-solution | class Solution:
def smallestRangeI(self, nums: List[int], k: int) -> int:
mi = min(nums)+k
mx = max(nums)-k
if mi >= mx:
return 0
return mx-mi | smallest-range-i | python easy solution | anshsharma17 | 0 | 48 | smallest range i | 908 | 0.678 | Easy | 14,748 |
https://leetcode.com/problems/smallest-range-i/discuss/2476935/Easy-94-Faster-Python-Solution. | class Solution:
def smallestRangeI(self, nums: List[int], k: int) -> int:
nums.sort()
min_val = nums[0]
max_val = nums[-1]
if min_val + k >= max_val - k:
return 0
else:
return (max_val - min_val - 2*k) | smallest-range-i | Easy 94% Faster Python Solution. | Siyuan_Wu | 0 | 45 | smallest range i | 908 | 0.678 | Easy | 14,749 |
https://leetcode.com/problems/smallest-range-i/discuss/1827891/1-Line-Python-Solution-oror-55-Faster-oror-Memory-less-than-95 | class Solution:
def smallestRangeI(self, nums: List[int], k: int) -> int:
return 0 if max(nums)-min(nums)<=2*k else max(nums)-min(nums)-2*k | smallest-range-i | 1-Line Python Solution || 55% Faster || Memory less than 95% | Taha-C | 0 | 75 | smallest range i | 908 | 0.678 | Easy | 14,750 |
https://leetcode.com/problems/smallest-range-i/discuss/1725288/Python-3-one-line-O(n) | class Solution:
def smallestRangeI(self, nums: List[int], k: int) -> int:
return max(0, max(nums) - min(nums) - 2*k) | smallest-range-i | Python 3, one line, O(n) | dereky4 | 0 | 138 | smallest range i | 908 | 0.678 | Easy | 14,751 |
https://leetcode.com/problems/smallest-range-i/discuss/1565678/Python3-Solution-or-1-line-answer | class Solution:
def smallestRangeI(self, nums: List[int], k: int) -> int:
return max(max(nums) - min(nums) - 2*k , 0) | smallest-range-i | Python3 Solution | 1 line answer | satyam2001 | 0 | 56 | smallest range i | 908 | 0.678 | Easy | 14,752 |
https://leetcode.com/problems/smallest-range-i/discuss/1368386/Python3-dollarolution | class Solution:
def smallestRangeI(self, nums: List[int], k: int) -> int:
i, j = min(nums) + k, max(nums) - k
if i > j:
return 0
else:
return (j - i) | smallest-range-i | Python3 $olution | AakRay | 0 | 115 | smallest range i | 908 | 0.678 | Easy | 14,753 |
https://leetcode.com/problems/smallest-range-i/discuss/1237960/Python3-or-One-Liner-or-Min-Max | class Solution:
def smallestRangeI(self, nums: List[int], k: int) -> int:
return max(max(nums)-min(nums)-2*k, 0) | smallest-range-i | Python3 | One Liner | Min-Max | Sanjaychandak95 | 0 | 61 | smallest range i | 908 | 0.678 | Easy | 14,754 |
https://leetcode.com/problems/smallest-range-i/discuss/1063098/Python3-simple-solution | class Solution:
def smallestRangeI(self, A: List[int], K: int) -> int:
return max(0,max(A)-min(A)-2*K) | smallest-range-i | Python3 simple solution | EklavyaJoshi | 0 | 55 | smallest range i | 908 | 0.678 | Easy | 14,755 |
https://leetcode.com/problems/snakes-and-ladders/discuss/2491448/Python-3-oror-BFS-Solution-Using-board-mapping | class Solution:
def snakesAndLadders(self, board: List[List[int]]) -> int:
# creating a borad map to loop-up the square value
board_map = {}
i = 1
b_rev = board[::-1]
for d, r in enumerate(b_rev):
# reverse for even rows - here d is taken as direction
if d%2 != 0: r = r[::-1]
for s in r:
board_map[i] = s
i += 1
# BFS Algorithm
q = [(1, 0)] # (curr, moves)
v = set()
goal = len(board) * len(board) # end square
while q:
curr, moves = q.pop(0)
# win situation
if curr == goal: return moves
# BFS on next 6 places (rolling a die)
for i in range(1, 7):
# skip square outside board
if curr+i > goal: continue
# get value from mapping
next_pos = curr+i if board_map[curr+i] == -1 else board_map[curr+i]
if next_pos not in v:
v.add(next_pos)
q.append((next_pos, moves+1))
return -1 | snakes-and-ladders | Python 3 || BFS Solution - Using board mapping | kevintoms | 1 | 161 | snakes and ladders | 909 | 0.409 | Medium | 14,756 |
https://leetcode.com/problems/snakes-and-ladders/discuss/1524927/Python-easy-understand-solutoin-with-explaination | class Solution:
def snakesAndLadders(self, board: List[List[int]]) -> int:
N = len(board)
seen = set()
queue = collections.deque()
queue.append((1,0))
flatten = self.getFlattenBoard(board)
# bfs
while queue:
label, step = queue.popleft()
if flatten[label] != -1:
label = flatten[label]
if label == N * N:
return step
# Get the next steps
for x in range(1 ,7):
nextLabel = label + x
if nextLabel <= N * N and nextLabel not in seen:
seen.add(nextLabel)
queue.append((nextLabel,step + 1))
return -1
def getFlattenBoard(self, board):
N = len(board)
# Use i to keep track of the direction of labels
i = 0
# The first cell in the flatten array is the extra element so the index in board can match the index in flatten array
flatten = [-1]
#Iterating from the bottom row
for row in range(N-1, -1, -1):
# store labels from left to right
if i % 2 == 0:
for col in range(N):
flatten.append(board[row][col])
#store labels from right to left
else:
for col in range(N-1,-1,-1):
flatten.append(board[row][col])
i += 1
return flatten | snakes-and-ladders | Python easy understand solutoin with explaination | qaz6209031 | 1 | 300 | snakes and ladders | 909 | 0.409 | Medium | 14,757 |
https://leetcode.com/problems/snakes-and-ladders/discuss/2104750/python-3-oror-simple-bfs | class Solution:
def snakesAndLadders(self, board: List[List[int]]) -> int:
n = len(board)
size = n * n
def numToCell(num):
row = n - 1 - (num - 1) // n
if (n - row) % 2 == 0:
col = n - 1 - (num - 1) % n
else:
col = (num - 1) % n
return row, col
visited = {1}
q = collections.deque([(1, 0)])
while q:
curr, level = q.popleft()
if curr == size:
return level
for nxt in range(curr + 1, min(curr + 6, size) + 1):
row, col = numToCell(nxt)
if board[row][col] != -1:
nxt = board[row][col]
if nxt in visited:
continue
visited.add(nxt)
q.append((nxt, level + 1))
return -1 | snakes-and-ladders | python 3 || simple bfs | dereky4 | 0 | 110 | snakes and ladders | 909 | 0.409 | Medium | 14,758 |
https://leetcode.com/problems/snakes-and-ladders/discuss/955232/Python3-BFS-O(N) | class Solution:
def snakesAndLadders(self, board: List[List[int]]) -> int:
n = len(board)
ans = 0
queue = [1]
seen = {1}
while queue:
newq = []
for x in queue:
if x == n*n: return ans
for xx in range(x+1, x+7):
if xx <= n*n:
i, j = divmod(xx-1, n)
if board[~i][~j if i&1 else j] != -1: xx = board[~i][~j if i&1 else j]
if xx not in seen:
newq.append(xx)
seen.add(xx)
ans += 1
queue = newq
return -1 | snakes-and-ladders | [Python3] BFS O(N) | ye15 | 0 | 94 | snakes and ladders | 909 | 0.409 | Medium | 14,759 |
https://leetcode.com/problems/smallest-range-ii/discuss/980784/Python-3-Solution-Explained-(video-%2B-code) | class Solution:
def smallestRangeII(self, A: List[int], K: int) -> int:
A.sort()
res = A[-1] - A[0]
for indx in range(0, len(A) - 1):
# assuming that A[indx] is the max val
min_val = min(A[0] + K, A[indx + 1] - K)
max_val = max(A[indx] + K, A[-1] - K)
res = min(res, max_val - min_val)
return res | smallest-range-ii | [Python 3] Solution Explained (video + code) | spec_he123 | 3 | 361 | smallest range ii | 910 | 0.346 | Medium | 14,760 |
https://leetcode.com/problems/smallest-range-ii/discuss/955300/Python3-greedy-O(NlogN) | class Solution:
def smallestRangeII(self, A: List[int], K: int) -> int:
A.sort()
ans = A[-1] - A[0]
for i in range(1, len(A)):
mn = min(A[0] + K, A[i] - K) # move up A[:i]
mx = max(A[i-1]+K, A[-1] - K) # move down A[i:]
ans = min(ans, mx - mn)
return ans | smallest-range-ii | [Python3] greedy O(NlogN) | ye15 | 3 | 91 | smallest range ii | 910 | 0.346 | Medium | 14,761 |
https://leetcode.com/problems/smallest-range-ii/discuss/2156417/Simple-Python-Solution-oror-Faster-than-100 | class Solution:
def smallestRangeII(self, nums: List[int], k: int) -> int:
# Remove duplicates and sort
arr = sorted(list(set(nums)))
res = arr[-1] - arr[0]
for i in range(len(arr) - 1):
res = min(res, max(arr[i] + k, arr[-1] - k) - min(arr[0] + k, arr[i + 1] - k))
return res | smallest-range-ii | Simple { Python } Solution || Faster than 100% | vofinaev | 0 | 86 | smallest range ii | 910 | 0.346 | Medium | 14,762 |
https://leetcode.com/problems/sort-an-array/discuss/461394/Python-3-(Eight-Sorting-Algorithms)-(With-Explanation) | class Solution:
def sortArray(self, N: List[int]) -> List[int]:
L = len(N)
return [N.pop(min(range(L-i), key = lambda x: N[x])) for i in range(L)] | sort-an-array | Python 3 (Eight Sorting Algorithms) (With Explanation) | junaidmansuri | 125 | 9,200 | sort an array | 912 | 0.594 | Medium | 14,763 |
https://leetcode.com/problems/sort-an-array/discuss/461394/Python-3-(Eight-Sorting-Algorithms)-(With-Explanation) | class Solution:
def sortArray(self, N: List[int]) -> List[int]:
L, B = len(N), 1
while B:
B = 0
for i in range(L-1):
if N[i] > N[i+1]: N[i], N[i+1], B = N[i+1], N[i], 1
return N | sort-an-array | Python 3 (Eight Sorting Algorithms) (With Explanation) | junaidmansuri | 125 | 9,200 | sort an array | 912 | 0.594 | Medium | 14,764 |
https://leetcode.com/problems/sort-an-array/discuss/461394/Python-3-(Eight-Sorting-Algorithms)-(With-Explanation) | class Solution:
def sortArray(self, N: List[int]) -> List[int]:
L = len(N)
for i in range(1,L):
for j in range(0,i):
if N[i] < N[j]:
N.insert(j, N.pop(i))
break
return N | sort-an-array | Python 3 (Eight Sorting Algorithms) (With Explanation) | junaidmansuri | 125 | 9,200 | sort an array | 912 | 0.594 | Medium | 14,765 |
https://leetcode.com/problems/sort-an-array/discuss/461394/Python-3-(Eight-Sorting-Algorithms)-(With-Explanation) | class Solution:
def sortArray(self, N: List[int]) -> List[int]:
L = len(N)
for i in range(1,L): bisect.insort_left(N, N.pop(i), 0, i)
return N | sort-an-array | Python 3 (Eight Sorting Algorithms) (With Explanation) | junaidmansuri | 125 | 9,200 | sort an array | 912 | 0.594 | Medium | 14,766 |
https://leetcode.com/problems/sort-an-array/discuss/461394/Python-3-(Eight-Sorting-Algorithms)-(With-Explanation) | class Solution:
def sortArray(self, N: List[int]) -> List[int]:
C, m, M, S = collections.Counter(N), min(N), max(N), []
for n in range(m,M+1): S.extend([n]*C[n])
return S | sort-an-array | Python 3 (Eight Sorting Algorithms) (With Explanation) | junaidmansuri | 125 | 9,200 | sort an array | 912 | 0.594 | Medium | 14,767 |
https://leetcode.com/problems/sort-an-array/discuss/461394/Python-3-(Eight-Sorting-Algorithms)-(With-Explanation) | class Solution:
def sortArray(self, N: List[int]) -> List[int]:
def quicksort(A, I, J):
if J - I <= 1: return
p = partition(A, I, J)
quicksort(A, I, p), quicksort(A, p + 1, J)
def partition(A, I, J):
A[J-1], A[(I + J - 1)//2], i = A[(I + J - 1)//2], A[J-1], I
for j in range(I,J):
if A[j] < A[J-1]: A[i], A[j], i = A[j], A[i], i + 1
A[J-1], A[i] = A[i], A[J-1]
return i
quicksort(N,0,len(N))
return N | sort-an-array | Python 3 (Eight Sorting Algorithms) (With Explanation) | junaidmansuri | 125 | 9,200 | sort an array | 912 | 0.594 | Medium | 14,768 |
https://leetcode.com/problems/sort-an-array/discuss/461394/Python-3-(Eight-Sorting-Algorithms)-(With-Explanation) | class Solution:
def sortArray(self, N: List[int]) -> List[int]:
def mergesort(A):
LA = len(A)
if LA == 1: return A
LH, RH = mergesort(A[:LA//2]), mergesort(A[LA//2:])
return merge(LH,RH)
def merge(LH, RH):
LLH, LRH = len(LH), len(RH)
S, i, j = [], 0, 0
while i < LLH and j < LRH:
if LH[i] <= RH[j]: i, _ = i + 1, S.append(LH[i])
else: j, _ = j + 1, S.append(RH[j])
return S + (RH[j:] if i == LLH else LH[i:])
return mergesort(N) | sort-an-array | Python 3 (Eight Sorting Algorithms) (With Explanation) | junaidmansuri | 125 | 9,200 | sort an array | 912 | 0.594 | Medium | 14,769 |
https://leetcode.com/problems/sort-an-array/discuss/461394/Python-3-(Eight-Sorting-Algorithms)-(With-Explanation) | class Solution:
def sortArray(self, N: List[int]) -> List[int]:
def insertion_sort(A):
for i in range(1,len(A)):
for j in range(0,i):
if A[i] < A[j]:
A.insert(j, A.pop(i))
break
return A
def bucketsort(A):
buckets, m, S = [[] for _ in range(1000)], min(A), []
R = max(A) - m
if R == 0: return A
for a in A: buckets[999*(a-m)//R]
for b in buckets: S.extend(insertion_sort(b))
return S
return bucketsort(N)
- Junaid Mansuri
- Chicago, IL | sort-an-array | Python 3 (Eight Sorting Algorithms) (With Explanation) | junaidmansuri | 125 | 9,200 | sort an array | 912 | 0.594 | Medium | 14,770 |
https://leetcode.com/problems/sort-an-array/discuss/905913/mergesort-in-python3 | class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
#mergesort
if len(nums) <= 1:
return nums
middle = len(nums) // 2
left = self.sortArray(nums[:middle])
right = self.sortArray(nums[middle:])
merged = []
while left and right:
if left[0] <= right [0]:
merged.append(left.pop(0))
else:
merged.append(right.pop(0))
merged.extend(right if right else left)
return merged | sort-an-array | mergesort in python3 | dqdwsdlws | 10 | 602 | sort an array | 912 | 0.594 | Medium | 14,771 |
https://leetcode.com/problems/sort-an-array/discuss/1677667/Python-merge-sort | class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
if len(nums)>1:
mid=len(nums)//2
l=nums[:mid]
r=nums[mid:]
self.sortArray(l)
self.sortArray(r)
i=j=k=0
while i<len(l) and j<len(r):
if l[i]<r[j]:
nums[k]=l[i]
i+=1
else:
nums[k]=r[j]
j+=1
k+=1
while i<len(l):
nums[k]=l[i]
i+=1
k+=1
while j<len(r):
nums[k]=r[j]
j+=1
k+=1
return nums
# nums.sort()
# return nums | sort-an-array | Python merge sort | amannarayansingh10 | 3 | 543 | sort an array | 912 | 0.594 | Medium | 14,772 |
https://leetcode.com/problems/sort-an-array/discuss/905905/python3-shell-sort | class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
#shell
sub = len(nums) // 2
while sub > 0:
for start in range(sub):
self.shell(nums, start, sub)
sub = sub // 2
return nums
def shell(self, alist, start, gap):
for i in range(start+gap, len(alist), gap):
current = alist[i]
position = i
while position >= gap and alist[position-gap] > current:
alist[position] = alist[position-gap]
position -= gap
alist[position] = current | sort-an-array | python3 shell sort | dqdwsdlws | 3 | 114 | sort an array | 912 | 0.594 | Medium | 14,773 |
https://leetcode.com/problems/sort-an-array/discuss/2162769/Python3-5-Common-Sorting-Algorithms-(selection-bubble-insertion-merge-quick) | class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
# self.selectionSort(nums)
# self.bubbleSort(nums)
# self.insertionSort(nums)
# self.mergeSort(nums)
self.quickSort(nums)
return nums
'''
Selection Sort (TLE)
TC: O(n^2) ; SC: O(1), in-place
Not Stable
Minimum swaps
'''
def selectionSort(self, nums):
for i in range(len(nums)):
min_idx=i
for j in range(i, len(nums)):
if nums[j]<nums[min_idx]:
min_idx=j
nums[i], nums[min_idx] = nums[min_idx], nums[i]
'''
Bubble Sort (TLE)
TC: best-O(n), worst-O(n^2)
SC: O(1)
Stable
Use when array is almost sorted
'''
def bubbleSort(self, nums):
for i in range(len(nums)):
swapped = False
for j in range(len(nums)-i-1):
if nums[j]>nums[j+1]:
nums[j], nums[j+1] = nums[j+1], nums[j]
swapped = True
if not swapped:
break
'''
Insertion Sort (TLE)
TC: best-O(n), worst-O(n^2)
SC: O(1)
Stable
'''
def insertionSort(self, nums):
for i in range(1, len(nums)):
key = nums[i]
j=i-1
while j>=0 and key<nums[j]:
nums[j+1]=nums[j]
j-=1
nums[j+1]=key
'''
Merge Sort
Recursive
TC: O(nlogn)
SC: O(n)
Stable
'''
def mergeSort(self, nums):
def merge(nums,L,R):
i = j = k = 0
while i < len(L) and j < len(R):
if L[i] < R[j]:
nums[k] = L[i]
i+=1
else:
nums[k] = R[j]
j+=1
k+=1
while i < len(L):
nums[k] = L[i]
i+=1
k+=1
while j < len(R):
nums[k] = R[j]
j+=1
k+=1
if len(nums)>1:
mid=len(nums)//2
L=nums[:mid]
R=nums[mid:]
self.mergeSort(L)
self.mergeSort(R)
merge(nums,L,R)
'''
QuickSort
Recursive
TC: average-O(nlogn), worst-O(n^2)
SC: average-O(logn), worst-O(n) recursion stack, in-place
Not stable
'''
def quickSort(self, nums):
# 3-way randomized
def partition(l, r):
pivot_idx = random.choice(range(l,r+1))
pivot = nums[pivot_idx]
# print(pivot)
left, move, right = l,l,r
while move<=right:
if nums[move]<pivot:
nums[left], nums[move] = nums[move], nums[left]
move+=1
left+=1
elif nums[move]>pivot:
nums[right], nums[move] = nums[move], nums[right]
right-=1
else:
move+=1
return left-1, move
def quicksort(nums, low, high):
if low<high:
l,r = partition(low, high)
quicksort(nums, low, l)
quicksort(nums, r, high)
quicksort(nums, 0, len(nums)-1)
#---------------------------------------------------------------
# def helper(head, tail):
# if head >= tail: return
# l, r = head, tail
# m = (r - l) // 2 + l
# pivot = nums[m]
# while r >= l:
# while r >= l and nums[l] < pivot: l += 1
# while r >= l and nums[r] > pivot: r -= 1
# if r >= l:
# nums[l], nums[r] = nums[r], nums[l]
# l += 1
# r -= 1
# helper(head, r)
# helper(l, tail)
# helper(0, len(nums)-1) | sort-an-array | [Python3] 5 Common Sorting Algorithms (selection, bubble, insertion, merge, quick) | __PiYush__ | 2 | 311 | sort an array | 912 | 0.594 | Medium | 14,774 |
https://leetcode.com/problems/sort-an-array/discuss/1815762/Solution-using-mergeSort | class Solution(object):
def merge(self, a, b):
i,j = 0, 0
ans = []
while i < len(a) and j < len(b):
if a[i] < b[j]:
ans.append(a[i])
i+=1
else :
ans.append(b[j])
j+=1
if i < len(a) :
ans.extend(a[i:])
elif j<len(b):
ans.extend(b[j:])
return ans
def sortArray(self, nums):
if len(nums) <= 1 :
return nums
mid = len(nums) // 2
left, right = self.sortArray(nums[:mid]), self.sortArray(nums[mid:])
return self.merge(left, right) | sort-an-array | Solution using - mergeSort | shakilbabu | 2 | 293 | sort an array | 912 | 0.594 | Medium | 14,775 |
https://leetcode.com/problems/sort-an-array/discuss/2799651/Python-oror-Easy-oror-Merge-Sort-oror-O(nlogn) | class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
def MergeSort(arr):
if len(arr)>1:
mid=len(arr)//2
L=arr[:mid]
R=arr[mid:]
MergeSort(L)
MergeSort(R)
i=j=k=0
while i<len(L) and j<len(R):
if L[i]<=R[j]:
arr[k]=L[i]
i+=1
else:
arr[k]=R[j]
j+=1
k+=1
while i<len(L):
arr[k]=L[i]
i+=1
k+=1
while j<len(R):
arr[k]=R[j]
j+=1
k+=1
MergeSort(nums)
return nums | sort-an-array | Python || Easy || Merge Sort || O(nlogn) | DareDevil_007 | 1 | 222 | sort an array | 912 | 0.594 | Medium | 14,776 |
https://leetcode.com/problems/sort-an-array/discuss/955399/Python3-O(NlogN)-quick-sort-and-O(N)-bucket-sort | class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
shuffle(nums) # statistical guarantee of O(NlogN)
def part(lo, hi):
"""Return a random partition of nums[lo:hi]."""
i, j = lo+1, hi-1
while i <= j:
if nums[i] < nums[lo]: i += 1
elif nums[j] > nums[lo]: j -= 1
else:
nums[i], nums[j] = nums[j], nums[i]
i += 1
j -= 1
nums[lo], nums[j] = nums[j], nums[lo]
return j
def sort(lo, hi):
"""Sort subarray nums[lo:hi] in place."""
if lo + 1 >= hi: return
mid = part(lo, hi)
sort(lo, mid)
sort(mid+1, hi)
sort(0, len(nums))
return nums | sort-an-array | [Python3] O(NlogN) quick sort & O(N) bucket sort | ye15 | 1 | 211 | sort an array | 912 | 0.594 | Medium | 14,777 |
https://leetcode.com/problems/sort-an-array/discuss/955399/Python3-O(NlogN)-quick-sort-and-O(N)-bucket-sort | class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
def fn(nums, aux, lo, hi):
"""Sort nums via merge sort."""
if lo+1 >= hi: return
mid = lo + hi >> 1
fn(aux, nums, lo, mid)
fn(aux, nums, mid, hi)
i, j = lo, mid
for k in range(lo, hi):
if j >= hi or i < mid and aux[i] < aux[j]:
nums[k] = aux[i]
i += 1
else:
nums[k] = aux[j]
j += 1
fn(nums, nums.copy(), 0, len(nums))
return nums | sort-an-array | [Python3] O(NlogN) quick sort & O(N) bucket sort | ye15 | 1 | 211 | sort an array | 912 | 0.594 | Medium | 14,778 |
https://leetcode.com/problems/sort-an-array/discuss/955399/Python3-O(NlogN)-quick-sort-and-O(N)-bucket-sort | class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
bucket = [0]*100001
for x in nums: bucket[x + 50000] += 1
ans = []
for i, x in enumerate(bucket, -50000):
ans.extend([i]*x)
return ans | sort-an-array | [Python3] O(NlogN) quick sort & O(N) bucket sort | ye15 | 1 | 211 | sort an array | 912 | 0.594 | Medium | 14,779 |
https://leetcode.com/problems/sort-an-array/discuss/2845645/Python-merge-sort-solution | class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
return self.mergeSort(nums,0,len(nums)-1)
def mergeLists(self, arr1,arr2):
mergeArr=[]
i,j=0,0
n1,n2=len(arr1),len(arr2)
while i<n1 and j<n2:
if arr1[i] <= arr2[j]:
mergeArr.append(arr1[i]);i+=1
else:
mergeArr.append(arr2[j]);j+=1
while i<n1:
mergeArr.append(arr1[i]);i+=1
while j<n2:
mergeArr.append(arr2[j]);j+=1
return mergeArr
def mergeSort(self,nums,left,right):
if left<right:
mid=(left+right)//2
arr1=self.mergeSort(nums,left,mid)
arr2=self.mergeSort(nums,mid+1,right)
return self.mergeLists(arr1,arr2)
return nums[left:right+1] | sort-an-array | Python merge sort solution | welin | 0 | 2 | sort an array | 912 | 0.594 | Medium | 14,780 |
https://leetcode.com/problems/sort-an-array/discuss/2841294/Python3-or-Counting-Sort | class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
a = min(nums)
b = max(nums)
r = b-a+1
c = [0 for _ in range(r)]
for i in range(len(nums)):
c[nums[i]-a] += 1
print(c)
k = 0
for i in range(r):
for j in range(c[i]):
nums[k] = i + a
k += 1
return nums | sort-an-array | Python3 | Counting Sort | chakalivinith | 0 | 2 | sort an array | 912 | 0.594 | Medium | 14,781 |
https://leetcode.com/problems/sort-an-array/discuss/2833845/O(nlogn) | class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
half_nums: List[int] = nums[0 : len(nums) // 2]
second_nums: List[int] = nums[len(nums) // 2 : len(nums)]
second_nums.sort()
half_nums.sort()
sort_nums = self.merge_arrays(half_nums, second_nums)
return sort_nums
def merge_arrays(self, a: List[int], b: List[int]) -> List[int]:
i, j = 0, 0
sort_array = []
while i < len(a) or j < len(b):
if j == len(b) or (i < len(a) and a[i] < b[j]):
sort_array.append(a[i])
i = i + 1
else:
sort_array.append(b[j])
j = j + 1
return sort_array | sort-an-array | O(nlogn) | danyalex | 0 | 6 | sort an array | 912 | 0.594 | Medium | 14,782 |
https://leetcode.com/problems/sort-an-array/discuss/2818515/Merge-Sort-or-Python-or-O(nlonn) | class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
def merge_sort(arr, start, end):
if start == end:
return
mid = (start+end)//2
merge_sort(arr, start, mid)
merge_sort(arr, mid+1, end)
i = start
j = mid+1
aux = []
while i <= mid and j <= end:
if arr[i] <= arr[j]:
aux.append(arr[i])
i += 1
else:
aux.append(arr[j])
j += 1
while i <= mid:
aux.append(arr[i])
i += 1
while j <= end:
aux.append(arr[j])
j += 1
arr[start:end+1] = aux
return
merge_sort(nums, 0, len(nums)-1)
return nums | sort-an-array | Merge Sort | Python | O(nlonn) | ajay_gc | 0 | 5 | sort an array | 912 | 0.594 | Medium | 14,783 |
https://leetcode.com/problems/sort-an-array/discuss/2812604/Python-or-Heap-Sort-or-O(nlogn) | class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
def left(i):
return 2*i
def right(i):
return 2*i+1
def min_heapify(A, i):
l = left(i)
r = right(i)
smallest = i
if l <= len(A):
if A[l-1] < A[i-1]:
smallest = l
else:
largest = i
if r <= len(A):
if A[r-1] < A[smallest-1]:
smallest = r
else:
smallest = smallest
if smallest != i:
temp = A[i-1]
A[i-1] = A[smallest-1]
A[smallest-1] = temp
min_heapify(A, smallest)
import math
def build_min_heatify(A):
for i in range(math.floor(len(A)/2), 0, -1):
min_heapify(A, i)
build_min_heatify(nums)
res = []
while len(nums)>1:
temp = nums.pop()
res.append(nums[0])
nums[0] = temp
min_heapify(nums, 1)
res.append(nums[0])
return res | sort-an-array | Python | Heap-Sort | O(nlogn) | IanChen0718 | 0 | 5 | sort an array | 912 | 0.594 | Medium | 14,784 |
https://leetcode.com/problems/sort-an-array/discuss/2802907/912.-Sort-an-Array-oror-Python3-oror-Merge_Sort | class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
return merge(nums)
def merge(nums):
if len(nums)>1:
mid=len(nums)//2
l=nums[:mid]
r=nums[mid:]
#print(l,r)
merge(l)
merge(r)
i=0
j=0
k=0
while i<len(l) and j<len(r):
if l[i]<=r[j]:
nums[k]=l[i]
i+=1
else:
nums[k]=r[j]
j+=1
k+=1
while j<len(r):
nums[k]=r[j]
j+=1
k+=1
while i<len(l):
nums[k]=l[i]
i+=1
k+=1
return nums | sort-an-array | 912. Sort an Array || Python3 || Merge_Sort | shagun_pandey | 0 | 3 | sort an array | 912 | 0.594 | Medium | 14,785 |
https://leetcode.com/problems/sort-an-array/discuss/2742288/Python-Merge-Sort | class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
def mergeSort(nums,s,e):
if e-s+1 <= 1:
return nums
#middle index
middle = (s+e)//2
#left half
mergeSort(nums,s,middle)
#right half
mergeSort(nums,middle+1,e)
#merge Both
merge(nums,s,middle,e)
return nums
#merge inplace
def merge(nums,s,m,e):
L = nums[s:m+1]
R = nums[m+1:e+1]
i = 0 #index for left
j = 0 #index for right
k = s #index for sorted arr
while i < len(L) and j < len(R):
if L[i] <= R[j]:
nums[k] = L[i]
i += 1
k += 1
else:
nums[k] = R[j]
j += 1
k += 1
while i < len(L):
nums[k] = L[i]
i += 1
k += 1
while j < len(R):
nums[k] = R[j]
j += 1
k += 1
return mergeSort(nums,0,len(nums)) | sort-an-array | Python Merge Sort | piyush_54 | 0 | 16 | sort an array | 912 | 0.594 | Medium | 14,786 |
https://leetcode.com/problems/sort-an-array/discuss/2724921/Merge-Sort | class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
s = 0
e = len(nums)-1
return self.mergeSortArray(nums, s, e)
def mergeSortArray(self, A, s, e):
if s == e:
return A
mid = (s+e)//2
self.mergeSortArray(A, s, mid)
self.mergeSortArray(A, mid+1, e)
self.sort_mid_array(A, s , mid, e)
return A
def sort_mid_array(self, A, s, m ,e):
p1 = s
p2 = m+1
p3 = 0
temp_arr = []
while p1 <= m and p2 <= e:
if A[p1] > A[p2]:
temp_arr.append(A[p2])
p2 +=1
else:
temp_arr.append(A[p1])
p1 +=1
while p1 <= m:
temp_arr.append(A[p1])
p1+=1
while p2 <= e:
temp_arr.append(A[p2])
p2+=1
for i in range(len(temp_arr)):
A[i+s] = temp_arr[i]
return A | sort-an-array | Merge Sort | ihimanshu25 | 0 | 8 | sort an array | 912 | 0.594 | Medium | 14,787 |
https://leetcode.com/problems/sort-an-array/discuss/2703928/merge-sort | class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
# use merge sort to divide into sub arrays
# a sub array with a single element is sorted (base case)
# otherwise keep splitting down the middle of the arr
# until the base case is reached
# do this for subarrays before the middle (exclusive) and
# after the middle (inclusive) (these are left and right subarrays)
# keep track of the sub arrays using start middle and end pointers
# for each pair of sub arrays, allocate memory to create the left and
# right sub array, create 3 pointers
# one for the current element to add in left, one for current
# element to add in right, then one to point to which index to place
# the smaller or equal element in the orignal array
# we use smaller or equal to make the algorithm stable
# do this for all sub arrays until the array is sorted
# time O(n * logn) space O(n)
def mergeSort(arr=nums, start=0, end=len(nums) - 1):
if end - start + 1 == 1:
return arr
mid = (start + end) // 2
mergeSort(arr, start, mid)
mergeSort(arr, mid + 1, end)
left = arr[start: mid + 1]
right = arr[mid + 1: end + 1]
l = r = 0
i = start
while l < len(left) and r < len(right):
if left[l] <= right[r]:
arr[i] = left[l]
l += 1
else:
arr[i] = right[r]
r += 1
i += 1
while l < len(left):
arr[i] = left[l]
l += 1
i += 1
while r < len(right):
arr[i] = right[r]
r += 1
i += 1
return arr
return mergeSort() | sort-an-array | merge sort | andrewnerdimo | 0 | 13 | sort an array | 912 | 0.594 | Medium | 14,788 |
https://leetcode.com/problems/sort-an-array/discuss/2521292/Python-runtime-10.48-memory-31.84 | class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
def mergeSort(nums, low, high):
if low < high:
mid = (low+high)//2
left = mergeSort(nums, low, mid)
right = mergeSort(nums, mid+1, high)
ans = []
lp = rp = 0
while lp < len(left) and rp < len(right):
if left[lp] <= right[rp]:
ans.append(left[lp])
lp += 1
else:
ans.append(right[rp])
rp += 1
while lp < len(left):
ans.append(left[lp])
lp += 1
while rp < len(right):
ans.append(right[rp])
rp += 1
return ans
return [nums[low]]
return mergeSort(nums, 0, len(nums)-1) | sort-an-array | Python, runtime 10.48%, memory 31.84% | tsai00150 | 0 | 155 | sort an array | 912 | 0.594 | Medium | 14,789 |
https://leetcode.com/problems/sort-an-array/discuss/2399927/Sort-an-Array | class Solution:
def merge (self, arr,L ,R):
i = j =k = 0
while i <len(L) and j<len(R):
if L[i]>R[j]:
arr[k]= R[j]
j+=1
else:
arr[k]= L[i]
i+=1
k+=1
while i < len(L):
arr[k]= L[i]
i+=1
k+=1
while j < len(R):
arr[k]= R[j]
j+=1
k+=1
def mergeSort (self,arr):
if len(arr)>1:
m= len(arr)//2
L=arr[:m]
R=arr[m:]
self.mergeSort(L)
self.mergeSort(R)
self.merge(arr,L,R)
def sortArray(self, nums: List[int]) -> List[int]:
self.mergeSort(nums)
return nums | sort-an-array | Sort an Array | dhananjayaduttmishra | 0 | 54 | sort an array | 912 | 0.594 | Medium | 14,790 |
https://leetcode.com/problems/sort-an-array/discuss/2366909/minheap-Python-short-and-simple | class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
heapify(nums)
ans=[]
while nums:
ans.append(heappop(nums))
return ans | sort-an-array | minheap Python -short and simple | sunakshi132 | 0 | 57 | sort an array | 912 | 0.594 | Medium | 14,791 |
https://leetcode.com/problems/sort-an-array/discuss/2310013/Python-Very-simple-solution-oror-Easy-to-understand-oror-Documented | class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
# inbuilt function, it will not make you understand how the merge sort is working
# return sorted(nums)
temp = [0] * len(nums)
# merge the two different sorted arrays
# nums[low:mid] and nums[mid+1:high]
# so that elements at low to high become sorted
def merge(low, mid, high):
h = low; i = low; j = mid + 1
# elements exist in both arrays
while h <= mid and j <= high:
if nums[h] <= nums[j]:
temp[i] = nums[h]; h += 1
else:
temp[i] = nums[j]; j += 1
i += 1
# elements still exist at left sorted array
while h <= mid:
temp[i] = nums[h]; h += 1; i += 1
# elements still exist at right sorted array
while j <= high:
temp[i] = nums[j]; j += 1; i += 1
# assign the sorted elements in temp to original array
for j in range(low, i): nums[j] = temp[j]
def mergeSort(low, high):
if low < high:
# divide into two subproblems
mid = int((low + high) / 2)
# solve the subproblems
mergeSort(low, mid)
mergeSort(mid +1, high)
# combine the solutions
merge(low, mid, high)
mergeSort(0, len(nums)-1)
return nums | sort-an-array | [Python] Very simple solution || Easy to understand || Documented | Buntynara | 0 | 63 | sort an array | 912 | 0.594 | Medium | 14,792 |
https://leetcode.com/problems/sort-an-array/discuss/2024335/Python-3-Solution-O(n)-Counting-Sort | class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
max_elm = max(nums)
min_elm = min(nums)
count_nums = [0 for _ in range(min_elm, max_elm + 1)]
for i in range(len(nums)):
count_nums[nums[i] - min_elm] += 1
for i in range(1, len(count_nums)):
count_nums[i] += count_nums[i - 1]
output_nums = [0] * len(nums)
for i in range(len(nums) - 1, -1, -1):
output_nums[count_nums[nums[i] - min_elm] - 1] = nums[i]
count_nums[nums[i] - min_elm] -= 1
return output_nums | sort-an-array | Python 3 Solution, O(n) Counting Sort | AprDev2011 | 0 | 79 | sort an array | 912 | 0.594 | Medium | 14,793 |
https://leetcode.com/problems/sort-an-array/discuss/1920078/Python-oror-Clean-Merge-Sort | class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
def MergeSort(nums):
n = len(nums)
if n <= 1: return nums
mid = n//2
first_half = MergeSort(nums[:mid])
second_half = MergeSort(nums[mid:])
merge = [0]*n
if not first_half: return second_half
if not second_half: return first_half
ni, mi = len(first_half), len(second_half)
i, p , j = 0, 0 ,0
while p < n:
if not j < mi:
merge[p] = first_half[i]
i += 1
elif not i < ni:
merge[p] = second_half[j]
j += 1
elif first_half[i] < second_half[j]:
merge[p] = first_half[i]
i += 1
else:
merge[p] = second_half[j]
j += 1
p += 1
return merge
return MergeSort(nums) | sort-an-array | Python || Clean Merge Sort | morpheusdurden | 0 | 139 | sort an array | 912 | 0.594 | Medium | 14,794 |
https://leetcode.com/problems/sort-an-array/discuss/1845629/Merge-sort-with-explanation-or-Python3-or-Time-%3A-O(nlogn) | class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
'''
Implementing this Question through Merge Sort
'''
#Edge Case - Already sorted!
if len(nums) <= 1 : return nums
#Find the mid point
mid = len(nums) // 2
#Making two seperate list
subList1 = nums[0 : mid]
subList2 = nums[mid : ]
#Recursively calling function on both sublists individually
self.sortArray(subList1)
self.sortArray(subList2)
#After breaking list into small parts, merging them back in one array(sorted)
self.merge(subList1, subList2, nums)
return nums
def merge(self, subList1, subList2, nums) :
#Setting pointers for each list
i = j = k = 0
while i < len(subList1) and j < len(subList2) :
#Filling nums list and incrementing pointers subsequently
if subList1[i] <= subList2[j] :
nums[k] = subList1[i]
i += 1
k += 1
else :
nums[k] = subList2[j]
j += 1
k += 1
#Now filling the rest of the elements left in either of the sublists to nums array
while i < len(subList1) :
nums[k] = subList1[i]
i += 1
k += 1
while j < len(subList2) :
nums[k] = subList2[j]
j += 1
k += 1 | sort-an-array | Merge sort with explanation | Python3 | Time : O(nlogn) | athrvb | 0 | 74 | sort an array | 912 | 0.594 | Medium | 14,795 |
https://leetcode.com/problems/sort-an-array/discuss/1811900/Python-3-Solution | class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
if len(nums) > 1:
mid = len(nums) // 2
left_list = nums[:mid]
right_list = nums[mid:]
self.sortArray(left_list)
self.sortArray(right_list)
i = 0
j = 0
k = 0
while i < len(left_list) and j < len(right_list):
if left_list[i] < right_list[j]:
nums[k] = left_list[i]
i = i + 1
k = k + 1
else:
nums[k] = right_list[j]
j = j + 1
k = k + 1
while i < len(left_list):
nums[k] = left_list[i]
i = i + 1
k = k + 1
while j < len(right_list):
nums[k] = right_list[j]
j = j + 1
k = k + 1
return nums | sort-an-array | Python 3 Solution | AprDev2011 | 0 | 91 | sort an array | 912 | 0.594 | Medium | 14,796 |
https://leetcode.com/problems/sort-an-array/discuss/1742082/912.-Sort-an-Array-Python3 | class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
return sorted(nums) | sort-an-array | 912. Sort an Array Python3 | debo75 | 0 | 111 | sort an array | 912 | 0.594 | Medium | 14,797 |
https://leetcode.com/problems/sort-an-array/discuss/1559534/Python3-Counting-sort-solution | class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
_max = max(nums)
_min = min(nums)
positive_arr = [0] * (_max + 1)
negative_arr = [0] * (abs(_min) + 1)
for num in nums:
if num >= 0:
positive_arr[num] += 1
else:
negative_arr[abs(num)] += 1
cur_idx = 0
for i in range(len(negative_arr) - 1, -1, -1):
for j in range(negative_arr[i]):
nums[cur_idx + j] = - i
cur_idx += negative_arr[i]
for i in range(len(positive_arr)):
for j in range(positive_arr[i]):
nums[cur_idx + j] = i
cur_idx += positive_arr[i]
return nums | sort-an-array | [Python3] Counting sort solution | maosipov11 | 0 | 86 | sort an array | 912 | 0.594 | Medium | 14,798 |
https://leetcode.com/problems/sort-an-array/discuss/1101405/O(N)-time-O(N)-space-Beats-90 | class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
vals = [0]*100000
res = []
for num in nums:
vals[num+50000] += 1
for pos, val in enumerate(vals):
if val > 0:
res.extend([pos-50000]*val)
return res | sort-an-array | O(N) time O(N) space Beats 90% | IKM98 | 0 | 292 | sort an array | 912 | 0.594 | Medium | 14,799 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.