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/rearrange-spaces-between-words/discuss/1686209/Easy-to-understand-python-solution | class Solution:
def reorderSpaces(self, text: str) -> str:
countSpace = text.count(" ")
countWords = len(text.split())
## If only one word is present, then add all the spaces at the end
if(countWords == 1):
return ''.join(text.split()[0] + " "*countSpace)
## If number of spaces is equal to one less than number of words then no change needed
if(countWords == countSpace+1):
return text
## Count extra number of spaces for all words (except last)
exNumOfSpaces = countSpace//(countWords-1)
## Count extra number of spaces after last word
exSpacesAtEnd = countSpace % (countWords-1)
output = []
for c in text.split():
output.append(c)
if(c != text.split()[-1]):
output.append(" "*exNumOfSpaces)
else:
output.append(" "*exSpacesAtEnd)
return ''.join(output)
``` | rearrange-spaces-between-words | Easy to understand python solution | htalanki2211 | 0 | 55 | rearrange spaces between words | 1,592 | 0.437 | Easy | 23,400 |
https://leetcode.com/problems/rearrange-spaces-between-words/discuss/1442988/Python3-Faster-Than-96.81 | class Solution:
def reorderSpaces(self, text: str) -> str:
t, spaces = text.split(), text.count(" ")
not_spaces = len(t)
if spaces == 0:
return text
if not_spaces == 1:
return text.strip() + " " * spaces
ratio, left = divmod(spaces, (not_spaces - 1))
return (" " * ratio).join(t) + " " * left | rearrange-spaces-between-words | Python3 Faster Than 96.81% | Hejita | 0 | 73 | rearrange spaces between words | 1,592 | 0.437 | Easy | 23,401 |
https://leetcode.com/problems/rearrange-spaces-between-words/discuss/1335450/python-3-easy-solution-for-beginners | class Solution:
def reorderSpaces(self, text: str) -> str:
count=0
newt=""
rem=0
words=text.split()
for i in text:
if i==" ":
count+=1
if len(words)<=1:
newt=words[0]+" "*(count)
else:
each_sp=count//(len(words)-1)
rem=count%(len(words)-1)
newt=words[0]
for i in range (1,len(words)-1):
newt+=(" "*each_sp)+words[i]
newt+=(" "*each_sp)+words[len(words)-1]+(" "*rem)
return newt | rearrange-spaces-between-words | python 3 easy solution for beginners | minato_namikaze | 0 | 46 | rearrange spaces between words | 1,592 | 0.437 | Easy | 23,402 |
https://leetcode.com/problems/rearrange-spaces-between-words/discuss/1246119/Python3-simple-solution-using-split()-and-count() | class Solution:
def reorderSpaces(self, text: str) -> str:
x = text.count(' ')
n = [i for i in text.split(' ') if len(i) >= 1]
if len(n) == 1:
return n[0] + ' '*x
spaces = x//(len(n)-1)
extra = x%(len(n)-1)
return (' '*spaces).join(n) + extra*' ' | rearrange-spaces-between-words | Python3 simple solution using split() and count() | EklavyaJoshi | 0 | 44 | rearrange spaces between words | 1,592 | 0.437 | Easy | 23,403 |
https://leetcode.com/problems/rearrange-spaces-between-words/discuss/1105505/Easy-to-Understand-no-headache | class Solution:
def reorderSpaces(self, text: str) -> str:
spaces=0
for i in text:
if i==" ":
spaces=spaces+1
words=text.split()
if len(words)==1:
return (" ".join(words)+" "*spaces)
equal=(spaces//(len(words)-1))*" "
extra=(spaces%(len(words)-1))*" "
return (equal.join(words)+extra) | rearrange-spaces-between-words | Easy to Understand no headache | ashish87 | 0 | 56 | rearrange spaces between words | 1,592 | 0.437 | Easy | 23,404 |
https://leetcode.com/problems/rearrange-spaces-between-words/discuss/944342/Intuitive-approach | class Solution:
def reorderSpaces(self, text: str) -> str:
words = text.strip().split()
if len(words) == 1:
return words[0] + (" " * text.count(" "))
else:
space_num = text.count(" ")
d, r = divmod(space_num, len(words)-1)
return (" " * d).join(words) + ("" if r == 0 else " " * r) | rearrange-spaces-between-words | Intuitive approach | puremonkey2001 | 0 | 38 | rearrange spaces between words | 1,592 | 0.437 | Easy | 23,405 |
https://leetcode.com/problems/rearrange-spaces-between-words/discuss/855387/Python-3-or-String-split-count-6-lines-or-Explanations | class Solution:
def reorderSpaces(self, text: str) -> str:
space = text.count(' ') # count how many space in total
text = [word for word in text.split(' ') if word] # split text to individual word in a list
n = len(text) # count total words
if n == 1: return text[0] + space * ' ' # length == 1 is a special case, since no space in between only at the end
avg, reminder = divmod(space, n-1) # get average space between words and spaces left (will be appended the end)
return (' '*avg).join(text) + ' ' * reminder # compose result | rearrange-spaces-between-words | Python 3 | String, split, count, 6 lines | Explanations | idontknoooo | 0 | 94 | rearrange spaces between words | 1,592 | 0.437 | Easy | 23,406 |
https://leetcode.com/problems/split-a-string-into-the-max-number-of-unique-substrings/discuss/855405/Python-3-or-Backtracking-DFS-clean-or-Explanations | class Solution:
def maxUniqueSplit(self, s: str) -> int:
ans, n = 0, len(s)
def dfs(i, cnt, visited):
nonlocal ans, n
if i == n: ans = max(ans, cnt); return # stop condition
for j in range(i+1, n+1):
if s[i:j] in visited: continue # avoid re-visit/duplicates
visited.add(s[i:j]) # update visited set
dfs(j, cnt+1, visited) # backtracking
visited.remove(s[i:j]) # recover visited set for next possibility
dfs(0, 0, set()) # function call
return ans | split-a-string-into-the-max-number-of-unique-substrings | Python 3 | Backtracking, DFS, clean | Explanations | idontknoooo | 5 | 849 | split a string into the max number of unique substrings | 1,593 | 0.55 | Medium | 23,407 |
https://leetcode.com/problems/split-a-string-into-the-max-number-of-unique-substrings/discuss/855071/Python3-backtracking | class Solution:
def maxUniqueSplit(self, s: str) -> int:
def fn(i):
"""Find max length via backtracking."""
nonlocal ans
if i == len(s): return (ans := max(ans, len(tabu)))
for ii in range(i+1, len(s)+1):
if s[i:ii] not in tabu:
tabu.add(s[i:ii])
fn(ii)
tabu.remove(s[i:ii])
ans = 1
tabu = set()
fn(0)
return ans | split-a-string-into-the-max-number-of-unique-substrings | [Python3] backtracking | ye15 | 4 | 801 | split a string into the max number of unique substrings | 1,593 | 0.55 | Medium | 23,408 |
https://leetcode.com/problems/split-a-string-into-the-max-number-of-unique-substrings/discuss/855071/Python3-backtracking | class Solution:
def maxUniqueSplit(self, s: str) -> int:
def fn(i, seen=set()):
"""Find max length via backtracking."""
ans = 0
if i < len(s): # boundary condition when i == len(s)
for ii in range(i+1, len(s)+1):
if s[i:ii] not in seen:
seen.add(s[i:ii])
ans = max(ans, 1 + fn(ii, seen))
seen.remove(s[i:ii])
return ans
return fn(0) | split-a-string-into-the-max-number-of-unique-substrings | [Python3] backtracking | ye15 | 4 | 801 | split a string into the max number of unique substrings | 1,593 | 0.55 | Medium | 23,409 |
https://leetcode.com/problems/split-a-string-into-the-max-number-of-unique-substrings/discuss/1749644/Easy-using-python3-and-backtracking | class Solution:
def maxUniqueSplit(self, s: str) -> int:
ans = 0
n = len(s)
def solve(index,current,vis):
nonlocal ans,n
if(index == n):
ans = max(ans,current)
return
for i in range(index,n):
# print(s[index:i])
if(s[index:i+1] not in vis):
solve(i+1,current+1,vis+(s[index:i+1],))
solve(0,0,())
return ans | split-a-string-into-the-max-number-of-unique-substrings | Easy using python3 and backtracking | jagdishpawar8105 | 1 | 209 | split a string into the max number of unique substrings | 1,593 | 0.55 | Medium | 23,410 |
https://leetcode.com/problems/split-a-string-into-the-max-number-of-unique-substrings/discuss/855790/Simple-python3-backtracking-solution-w-explanation | class Solution:
def maxUniqueSplit(self, s: str) -> int:
def maxU(s, soFar=set()):
if len(s) == 1 and s in soFar:
return 0
maxSplit = len(soFar)+1
for partition in range(1, len(s)):
a = s[:partition]
b = s[partition:]
if a not in soFar:
maxSplit = max(maxSplit, maxU(b, soFar|{a}))
return maxSplit
return maxU(s) | split-a-string-into-the-max-number-of-unique-substrings | Simple python3 backtracking solution w/ explanation | popestr | 1 | 132 | split a string into the max number of unique substrings | 1,593 | 0.55 | Medium | 23,411 |
https://leetcode.com/problems/split-a-string-into-the-max-number-of-unique-substrings/discuss/2786620/Python-backtracking-and-pruning | class Solution:
def maxUniqueSplit_fun(self, s: str, cur_list, sub_set, res) -> int:
if len(cur_list) > 0:
sub = s[cur_list[-1]:]
if len(sub) > 0 and sub not in sub_set:
res[0] = max(res[0], len(cur_list) + 1)
if len(cur_list) + len(s) - cur_list[-1] - 1 < res[0]:
return
start = 1
if len(cur_list) > 0:
start = cur_list[-1] + 1
for i in range(start, len(s)):
sub = s[start-1:i]
if sub not in sub_set:
cur_list.append(i)
sub_set.add(sub)
self.maxUniqueSplit_fun(s, cur_list, sub_set, res)
sub_set.remove(sub)
del cur_list[-1]
def maxUniqueSplit(self, s: str) -> int:
res = [1]
self.maxUniqueSplit_fun(s, [], set(), res)
return res[0] | split-a-string-into-the-max-number-of-unique-substrings | Python backtracking and pruning | laofu_laoluzi | 0 | 4 | split a string into the max number of unique substrings | 1,593 | 0.55 | Medium | 23,412 |
https://leetcode.com/problems/split-a-string-into-the-max-number-of-unique-substrings/discuss/2473823/Python3-or-Intuitive-Recursion-%2B-Backtracking-Approach | class Solution:
#Time-Complexity: O(n^n * n*n), since rec. tree has worst case branching factor and depth of both n! #-> Also, every rec. call will loop at most n times and the splicing operation takes linear time, which
#will copy in worst case each and every n characters! -> O(n^(n+2)) -> O(n^n)
#Space-Complexity: O(n + n) -> O(n) due to call stack from recursion and seen set!
def maxUniqueSplit(self, s: str) -> int:
ans = 0
#2 paramters: remaining string cur, seen which is a set of string elements that
#are already substrings that we formed!
def helper(cur, seen):
nonlocal ans
#base case:if current string is empty, we can't form any more substrings!
if(cur == ""):
#we need to update answer!
ans =max(ans, len(seen))
return
#otherwise, for current string we are on, we need to consider all possible ways we can
#break it up!
#we can take the first char and form substring, first two characters and form substr, #..., etc.! Hence, there are choices to make at every local call, where the number
#of choices equals relatively the number of characters in input string cur!
substring = ""
for i in range(0, len(cur)):
#concatenate the ith index char of cur to built up substring!
substring += cur[i]
#here, boolean flag serves to indicate whether we recursed or not recursed!
flag = False
#we should only recurse if substring we formed is not already previously
#formed substring in seen set!
if(substring not in seen):
flag = True
#mark the substring as used already by updating the seen set!
seen.add(substring)
#remainder is splice of cur starting from index i + 1 and onwards
remainder = cur[i+1:]
helper(remainder, seen)
#once recursion returns, we don't need to update cur since it's unchanged!
#all we need to do is when we backtrack, we need to restore the state of set!
#if we recursed, we for sure added the substring to the seen set!
#make sure to remove it when backtracking after rec. call finishes!
if(flag):
seen.remove(substring)
#kick off recursion by passing in entire string input s and seen set as initially empty
#set!
helper(s, set())
#once recursion finishes, ans should be updated to reflect max. number of unique
#substrings we can form!
return ans | split-a-string-into-the-max-number-of-unique-substrings | Python3 | Intuitive Recursion + Backtracking Approach | JOON1234 | 0 | 45 | split a string into the max number of unique substrings | 1,593 | 0.55 | Medium | 23,413 |
https://leetcode.com/problems/split-a-string-into-the-max-number-of-unique-substrings/discuss/1899045/Python-3-BackTracking | class Solution:
def maxUniqueSplit(self, s: str) -> int:
mx = [0]
def dfs(ansset, remain):
nonlocal mx
if remain == "":
if len(ansset) >= mx[0]:
mx[0] = len(ansset)
for i in range(len(remain)+1):
insert = remain[:i]
if insert not in ansset and insert != '':
ansset.add(insert)
dfs(ansset, remain[i:])
ansset.remove(insert)
dfs(set({}),s)
return(mx[0]) | split-a-string-into-the-max-number-of-unique-substrings | Python 3 BackTracking | DietCoke777 | 0 | 88 | split a string into the max number of unique substrings | 1,593 | 0.55 | Medium | 23,414 |
https://leetcode.com/problems/split-a-string-into-the-max-number-of-unique-substrings/discuss/1847270/Python3-Easy-understanding-backtracking-solution-beats-90-speed-and-100-memory | class Solution:
def maxUniqueSplit(self, s: str) -> int:
def backtrack(string, tempSet):
nonlocal cnt
if string == "": cnt = max(cnt, len(tempSet))
for i in range(1, len(string)+1):
substring = string[:i]
if substring in tempSet: continue
tempSet.add(substring)
backtrack(string[i:], tempSet)
tempSet.remove(substring)
cnt = 0
backtrack(s, set())
return cnt | split-a-string-into-the-max-number-of-unique-substrings | [Python3] Easy understanding backtracking solution, beats 90% speed and 100% memory | freetochoose | 0 | 171 | split a string into the max number of unique substrings | 1,593 | 0.55 | Medium | 23,415 |
https://leetcode.com/problems/split-a-string-into-the-max-number-of-unique-substrings/discuss/1847270/Python3-Easy-understanding-backtracking-solution-beats-90-speed-and-100-memory | class Solution:
def maxUniqueSplit(self, s: str) -> int:
def backtrack(string, tempSet):
nonlocal cnt
if string == "":
cnt = max(cnt, len(tempSet))
for offsetIdx in range(len(string)):
for i in range(len(string)):
tempIdx = offsetIdx + 1
if i+tempIdx > len(string): break
substring = string[i:i+tempIdx]
tempSet.add(substring)
backtrack(string[:i] + string[i+tempIdx:], tempSet)
if substring in tempSet: tempSet.remove(substring)
cnt = 0
backtrack(s, set())
return cnt | split-a-string-into-the-max-number-of-unique-substrings | [Python3] Easy understanding backtracking solution, beats 90% speed and 100% memory | freetochoose | 0 | 171 | split a string into the max number of unique substrings | 1,593 | 0.55 | Medium | 23,416 |
https://leetcode.com/problems/split-a-string-into-the-max-number-of-unique-substrings/discuss/1402642/Simple-Backtracking-Easy-to-understand-python-3 | class Solution:
def maxUniqueSplit(self, s: str) -> int:
strings = set()
self.max_len = 0
def split(s) :
if not s :
self.max_len = max(self.max_len, len(strings))
return
for i in range(1,len(s)+1) :
cs = s[:i]
if cs not in strings :
strings.add(cs)
split(s[i:])
strings.remove(cs)
split(s)
return self.max_len | split-a-string-into-the-max-number-of-unique-substrings | Simple Backtracking Easy to understand python 3 | Manideep8 | -1 | 126 | split a string into the max number of unique substrings | 1,593 | 0.55 | Medium | 23,417 |
https://leetcode.com/problems/maximum-non-negative-product-in-a-matrix/discuss/855131/Python3-top-down-dp | class Solution:
def maxProductPath(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
@lru_cache(None)
def fn(i, j):
"""Return maximum & minimum products ending at (i, j)."""
if i == 0 and j == 0: return grid[0][0], grid[0][0]
if i < 0 or j < 0: return -inf, inf
if grid[i][j] == 0: return 0, 0
mx1, mn1 = fn(i-1, j) # from top
mx2, mn2 = fn(i, j-1) # from left
mx, mn = max(mx1, mx2)*grid[i][j], min(mn1, mn2)*grid[i][j]
return (mx, mn) if grid[i][j] > 0 else (mn, mx)
mx, _ = fn(m-1, n-1)
return -1 if mx < 0 else mx % 1_000_000_007 | maximum-non-negative-product-in-a-matrix | [Python3] top-down dp | ye15 | 36 | 1,800 | maximum non negative product in a matrix | 1,594 | 0.33 | Medium | 23,418 |
https://leetcode.com/problems/maximum-non-negative-product-in-a-matrix/discuss/855377/Python-3-or-DP-O(m*n)-time-In-place-or-Explanation | class Solution:
def maxProductPath(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
grid[0][0] = grid[0][0], grid[0][0] # (small, large) for starting point
for j in range(1, n):
grid[0][j] = grid[0][j-1][0]*grid[0][j], grid[0][j-1][1]*grid[0][j] # special handling first row
for i in range(1, m):
grid[i][0] = grid[i-1][0][0]*grid[i][0], grid[i-1][0][1]*grid[i][0] # special handling first col
for i in range(1, m):
for j in range(1, n):
nums = [grid[i-1][j][0]*grid[i][j], grid[i][j-1][0]*grid[i][j], grid[i-1][j][1]*grid[i][j], grid[i][j-1][1]*grid[i][j]]
small, large = min(nums), max(nums)
grid[i][j] = (small, large) # update all other points
return (grid[-1][-1][1] % 1000000007) if grid[-1][-1][1] >= 0 else -1 | maximum-non-negative-product-in-a-matrix | Python 3 | DP O(m*n) time, In place | Explanation | idontknoooo | 6 | 327 | maximum non negative product in a matrix | 1,594 | 0.33 | Medium | 23,419 |
https://leetcode.com/problems/maximum-non-negative-product-in-a-matrix/discuss/2373966/DFS-oror-Dynamic-Programming-oror-Memoization-oror-Python3 | class Solution:
def maxProductPath(self, grid: List[List[int]]) -> int:
def isBound(row,col):
return 0<=row<len(grid) and 0<=col<len(grid[0])
@lru_cache(None)
def dfs(row,col,product):
if not isBound(row, col):
return -1
if row == len(grid) - 1 and col == len(grid[0]) - 1:
return product * grid[row][col]
return max(dfs(row+1,col, product * grid[row][col]),dfs(row,col+1, product * grid[row][col]))
max_product = dfs(0,0,1)
return max_product %(10**9+7) if max_product!=-1 else -1 | maximum-non-negative-product-in-a-matrix | DFS || Dynamic Programming || Memoization || Python3 | Sefinehtesfa34 | 1 | 133 | maximum non negative product in a matrix | 1,594 | 0.33 | Medium | 23,420 |
https://leetcode.com/problems/maximum-non-negative-product-in-a-matrix/discuss/2816531/Python-(Simple-DP) | class Solution:
def maxProductPath(self, grid):
m, n = len(grid), len(grid[0])
max_ = [[0]*n for _ in range(m)]
min_ = [[0]*n for _ in range(m)]
max_[0][0] = min_[0][0] = grid[0][0]
for i in range(1,m):
max_[i][0] = grid[i][0]*max_[i-1][0]
min_[i][0] = grid[i][0]*min_[i-1][0]
for j in range(1,n):
max_[0][j] = grid[0][j]*max_[0][j-1]
min_[0][j] = grid[0][j]*min_[0][j-1]
for i in range(1,m):
for j in range(1,n):
if grid[i][j] > 0:
max_[i][j] = max(max_[i-1][j],max_[i][j-1])*grid[i][j]
min_[i][j] = min(min_[i-1][j],min_[i][j-1])*grid[i][j]
else:
max_[i][j] = min(min_[i-1][j],min_[i][j-1])*grid[i][j]
min_[i][j] = max(max_[i-1][j],max_[i][j-1])*grid[i][j]
return max_[-1][-1]%(10**9+7) if max_[-1][-1] >= 0 else -1 | maximum-non-negative-product-in-a-matrix | Python (Simple DP) | rnotappl | 0 | 2 | maximum non negative product in a matrix | 1,594 | 0.33 | Medium | 23,421 |
https://leetcode.com/problems/maximum-non-negative-product-in-a-matrix/discuss/2701373/Python-Simple-DP-Solution | class Solution:
def maxProductPath(self, grid: List[List[int]]) -> int:
numRows, numCols = len(grid), len(grid[0])
maxProduct, minProduct = [[0] * numCols for _ in range(numRows)], [[0] * numCols for _ in range(numRows)]
maxProduct[0][0], minProduct[0][0] = grid[0][0], grid[0][0]
for row in range(1, numRows):
minProduct[row][0] = minProduct[row - 1][0] * grid[row][0]
maxProduct[row][0] = maxProduct[row - 1][0] * grid[row][0]
for col in range(1, numCols):
minProduct[0][col] = minProduct[0][col - 1] * grid[0][col]
maxProduct[0][col] = maxProduct[0][col - 1] * grid[0][col]
for row in range(1, numRows):
for col in range(1, numCols):
if grid[row][col] < 0:
maxProduct[row][col] = min(minProduct[row - 1][col], minProduct[row][col - 1]) * grid[row][col]
minProduct[row][col] = max(maxProduct[row - 1][col], maxProduct[row][col - 1]) * grid[row][col]
else:
maxProduct[row][col] = max(maxProduct[row - 1][col], maxProduct[row][col - 1]) * grid[row][col]
minProduct[row][col] = min(minProduct[row - 1][col], minProduct[row][col - 1]) * grid[row][col]
res = maxProduct[numRows - 1][numCols - 1]
return res % 1000000007 if res >= 0 else -1 | maximum-non-negative-product-in-a-matrix | Python Simple DP Solution | hemantdhamija | 0 | 13 | maximum non negative product in a matrix | 1,594 | 0.33 | Medium | 23,422 |
https://leetcode.com/problems/maximum-non-negative-product-in-a-matrix/discuss/1849714/Python-easy-to-read-and-understand-or-DP | class Solution:
def dfs(self, grid, row, col, d):
if row == len(grid)-1 and col == len(grid[0])-1:
return (grid[row][col], grid[row][col])
if row == len(grid) or col == len(grid[0]):
return (float("-inf"), float("inf"))
if grid[row][col] == 0:
return (0, 0)
if (row, col) in d:
return d[(row, col)]
mx1, mn1 = self.dfs(grid, row+1, col, d)
mx2, mn2 = self.dfs(grid, row, col+1, d)
mx = max(mx1, mx2)*grid[row][col]
mn = min(mn1, mn2)*grid[row][col]
d[(row, col)] = (mx, mn) if grid[row][col] > 0 else (mn, mx)
return d[(row, col)]
def maxProductPath(self, grid: List[List[int]]) -> int:
d = {}
mx, _ = self.dfs(grid, 0, 0, d)
return mx % (10**9 + 7) if mx >= 0 else -1 | maximum-non-negative-product-in-a-matrix | Python easy to read and understand | DP | sanial2001 | 0 | 92 | maximum non negative product in a matrix | 1,594 | 0.33 | Medium | 23,423 |
https://leetcode.com/problems/maximum-non-negative-product-in-a-matrix/discuss/1809378/Runtime%3A-40-ms-faster-than-100.00-of-Python3-online-submissions | class Solution:
def maxProductPath(self, grid: List[List[int]]) -> int:
m,n=len(grid),len(grid[0])
dp=[[[float('-inf'),float('inf')]]*(n+1) for i in range(m+1) ]
dp[m-1][n-1]=[grid[-1][-1],grid[-1][-1]]
for i in range(m-1,-1,-1):
for j in range(n-1,-1,-1):
if i==m-1 and j==n-1:
continue
if grid[i][j]>0:
ma=max(dp[i+1][j][0],dp[i][j+1][0])*grid[i][j]
mi=min(dp[i+1][j][1],dp[i][j+1][1])*grid[i][j]
dp[i][j]=[ma,mi]
else:
ma=min(dp[i+1][j][1],dp[i][j+1][1])*grid[i][j]
mi=max(dp[i+1][j][0],dp[i][j+1][0])*grid[i][j]
dp[i][j]=[ma,mi]
k,l=dp[0][0]
if k<0:
return -1
return k%(1000000000+7) | maximum-non-negative-product-in-a-matrix | Runtime: 40 ms, faster than 100.00% of Python3 online submissions | laxminarayanak | 0 | 41 | maximum non negative product in a matrix | 1,594 | 0.33 | Medium | 23,424 |
https://leetcode.com/problems/maximum-non-negative-product-in-a-matrix/discuss/1289365/Intuitive-Python-Memoization-Easy-understand-Solution | class Solution:
def maxProductPath(self, grid: List[List[int]]) -> int:
m=len(grid)
n=len(grid[0])
dp=[[-1]*n for i in range(m)]
def solve(i,j):
if i==m-1 and j==n-1:
return grid[m-1][n-1],grid[m-1][n-1]
if i>=m or j>=n:
return -inf,inf
if grid[i][j]==0:
return 0,0
if dp[i][j]!=-1:
return dp[i][j]
mx1,mn1=solve(i,j+1)
mx2,mn2=solve(i+1,j)
if grid[i][j]<=0:
dp[i][j]= grid[i][j]*min(mn1,mn2), grid[i][j]*max(mx1,mx2)
else:
dp[i][j]= grid[i][j]*max(mx1,mx2), grid[i][j]*min(mn1,mn2)
return dp[i][j]
mx,mn= solve(0,0)
if mx<0:
return -1
else:
return mx%(10**9+7) | maximum-non-negative-product-in-a-matrix | Intuitive Python Memoization - Easy understand Solution | coder1311 | 0 | 139 | maximum non negative product in a matrix | 1,594 | 0.33 | Medium | 23,425 |
https://leetcode.com/problems/maximum-non-negative-product-in-a-matrix/discuss/855140/Python3-Dynamic-Programming-with-explanation | class Solution:
mod=pow(10,9)+7
def maxProductPath(self, grid: List[List[int]]) -> int:
n,m=len(grid),len(grid[0])
maxPath = [[0 for i in range(m)] for j in range(n)]
minPath = [[0 for i in range(m)] for j in range(n)]
for i in range(n):
for j in range(m):
mn = float('inf')
mx = float('-inf')
if (i == 0 and j == 0):
mx = grid[i][j]
mn = grid[i][j]
if (i > 0):
tempmx = max((maxPath[i - 1][j] * grid[i][j]),(minPath[i - 1][j] * grid[i][j]))
mx = max(mx, tempmx)
tempmn = min((maxPath[i - 1][j] * grid[i][j]),(minPath[i - 1][j] * grid[i][j]))
mn = min(mn, tempmn);
if (j > 0):
tempmx = max((maxPath[i][j - 1] * grid[i][j]),(minPath[i][j - 1] * grid[i][j]))
mx = max(mx, tempmx);
tempmn = min((maxPath[i][j - 1] * grid[i][j]),(minPath[i][j - 1] * grid[i][j]))
mn = min(mn, tempmn);
maxPath[i][j] = mx;
minPath[i][j] = mn;
if(maxPath[n-1][m-1]<0):
return -1
return maxPath[n-1][m-1]%self.mod | maximum-non-negative-product-in-a-matrix | [Python3] Dynamic Programming with explanation | pranav05 | 0 | 57 | maximum non negative product in a matrix | 1,594 | 0.33 | Medium | 23,426 |
https://leetcode.com/problems/maximum-non-negative-product-in-a-matrix/discuss/855094/Python-DP-Top-Down | class Solution:
def maxProductPath(self, mat: List[List[int]]) -> int:
mod = 10**9+7
m, n = len(mat), len(mat[0])
@lru_cache(None)
def dp(i, j):
if i >= m or j >= n: return (-math.inf, math.inf)
curr = mat[i][j]
if i == m-1 and j == n-1 or curr == 0: return (curr, curr)
mp, mn = 0, 0
pd, nd = dp(i+1, j)
pr, nr = dp(i, j+1)
if curr < 0:
mp = max(curr*nd, curr*nr)
mn = min(curr*pd, curr*pr)
else:
mp = max(curr*pd, curr*pr)
mn = min(curr*nd, curr*nr)
return (mp, mn)
ans = dp(0, 0)[0]
return ans%mod if ans >= 0 else -1 | maximum-non-negative-product-in-a-matrix | [Python] DP Top Down | carloscerlira | 0 | 98 | maximum non negative product in a matrix | 1,594 | 0.33 | Medium | 23,427 |
https://leetcode.com/problems/maximum-non-negative-product-in-a-matrix/discuss/1493852/DP-oror-For-Beginners-oror-Well-Explained-oror-97-faster | class Solution:
def maxProductPath(self, grid: List[List[int]]) -> int:
MOD = 10**9+7
m,n = len(grid),len(grid[0])
dp = [[[0,0] for _ in range(n)] for _ in range(m)]
dp[0][0][0]=grid[0][0]
dp[0][0][1]=grid[0][0]
for i in range(1,m): #First Column
dp[i][0][0] = dp[i-1][0][0]*grid[i][0]
dp[i][0][1] = dp[i-1][0][1]*grid[i][0]
for j in range(1,n): #First Row
dp[0][j][0] = dp[0][j-1][0]*grid[0][j]
dp[0][j][1] = dp[0][j-1][1]*grid[0][j]
for i in range(1,m):
for j in range(1,n):
if grid[i][j]<0:
dp[i][j][0] = min(dp[i][j-1][1],dp[i-1][j][1])*grid[i][j]
dp[i][j][1] = max(dp[i][j-1][0],dp[i-1][j][0])*grid[i][j]
else:
dp[i][j][0] = max(dp[i][j-1][0],dp[i-1][j][0])*grid[i][j]
dp[i][j][1] = min(dp[i][j-1][1],dp[i-1][j][1])*grid[i][j]
if dp[-1][-1][0]<0 and dp[-1][-1][1]<0:
return -1
return max(dp[-1][-1][0],dp[-1][-1][1])%MOD | maximum-non-negative-product-in-a-matrix | ππ DP || For Beginners || Well-Explained || 97% faster π | abhi9Rai | -1 | 240 | maximum non negative product in a matrix | 1,594 | 0.33 | Medium | 23,428 |
https://leetcode.com/problems/minimum-cost-to-connect-two-groups-of-points/discuss/858187/Python3-top-down-dp | class Solution:
def connectTwoGroups(self, cost: List[List[int]]) -> int:
m, n = len(cost), len(cost[0])
mn = [min(x) for x in zip(*cost)] # min cost of connecting points in 2nd group
@lru_cache(None)
def fn(i, mask):
"""Return min cost of connecting group1[i:] and group2 represented as mask."""
if i == m: return sum(mn[j] for j in range(n) if not (mask & (1<<j)))
return min(cost[i][j] + fn(i+1, mask | 1<<j) for j in range(n))
return fn(0, 0) | minimum-cost-to-connect-two-groups-of-points | [Python3] top-down dp | ye15 | 1 | 169 | minimum cost to connect two groups of points | 1,595 | 0.463 | Hard | 23,429 |
https://leetcode.com/problems/minimum-cost-to-connect-two-groups-of-points/discuss/858187/Python3-top-down-dp | class Solution:
def connectTwoGroups(self, cost: List[List[int]]) -> int:
m, n = len(cost), len(cost[0])
mn = [min(x) for x in cost] # min cost of connecting points in 1st group
@lru_cache(None)
def fn(j, mask):
"""Return min cost of connecting group1[i:] and group2 represented as mask."""
if j == n: return sum(mn[i] for i in range(m) if not (mask & (1<<i)))
return min(cost[i][j] + fn(j+1, mask | 1<<i) for i in range(m))
return fn(0, 0) | minimum-cost-to-connect-two-groups-of-points | [Python3] top-down dp | ye15 | 1 | 169 | minimum cost to connect two groups of points | 1,595 | 0.463 | Hard | 23,430 |
https://leetcode.com/problems/crawler-log-folder/discuss/866343/Python3-straightforward | class Solution:
def minOperations(self, logs: List[str]) -> int:
ans = 0
for log in logs:
if log == "./": continue
elif log == "../": ans = max(0, ans-1) # parent directory
else: ans += 1 # child directory
return ans | crawler-log-folder | [Python3] straightforward | ye15 | 11 | 627 | crawler log folder | 1,598 | 0.644 | Easy | 23,431 |
https://leetcode.com/problems/crawler-log-folder/discuss/2102858/PYTHON-or-Super-Easy-python-solution | class Solution:
def minOperations(self, logs: List[str]) -> int:
res = 0
for i in logs:
if i == '../' and res > 0:
res -= 1
elif i != './' and i != '../':
res += 1
return res | crawler-log-folder | PYTHON | Super Easy python solution | shreeruparel | 3 | 123 | crawler log folder | 1,598 | 0.644 | Easy | 23,432 |
https://leetcode.com/problems/crawler-log-folder/discuss/2507874/Intuitive-code-and-easily-understandable-in-Python | class Solution:
def minOperations(self, logs: List[str]) -> int:
res = 0
for i in logs:
if i == './':
continue
elif i == '../':
if res > 0:
res -= 1
else:
res += 1
return res | crawler-log-folder | Intuitive code and easily understandable in Python | ankurbhambri | 1 | 46 | crawler log folder | 1,598 | 0.644 | Easy | 23,433 |
https://leetcode.com/problems/crawler-log-folder/discuss/1291927/Easy-Python-Solution(93.94) | class Solution:
def minOperations(self, logs: List[str]) -> int:
stack=[]
for i in logs:
if(i=='../' and stack):
stack.pop()
elif(i=='./'):
continue
elif(i!='../' ):
stack.append(i)
return len(stack) | crawler-log-folder | Easy Python Solution(93.94%) | Sneh17029 | 1 | 140 | crawler log folder | 1,598 | 0.644 | Easy | 23,434 |
https://leetcode.com/problems/crawler-log-folder/discuss/2836646/Simple-Python-solution-beats-90 | class Solution:
def minOperations(self, logs: List[str]) -> int:
steps = 0
for i in logs:
if i == "../" and steps != 0:
steps -= 1
elif i == "./" or i == "../" and steps == 0:
continue
else:
steps += 1
return steps | crawler-log-folder | Simple Python solution beats 90% | aruj900 | 0 | 1 | crawler log folder | 1,598 | 0.644 | Easy | 23,435 |
https://leetcode.com/problems/crawler-log-folder/discuss/2703615/Easy-or-Python-or-1-loop | class Solution:
def minOperations(self, logs: List[str]) -> int:
check=[]
for i in logs:
if i=="../" and len(check)!=0:
check.pop()
elif i=="./":
continue
else:
if i!="./" and i!="../":
check.append(i[:-1])
return len(check) | crawler-log-folder | Easy | Python | 1 loop | pranshuvishnoi85 | 0 | 4 | crawler log folder | 1,598 | 0.644 | Easy | 23,436 |
https://leetcode.com/problems/crawler-log-folder/discuss/2673874/Python-solution | class Solution:
def minOperations(self, logs: List[str]) -> int:
listof= []
for l in logs:
if l == '../':
if not (len(listof) == 0):
listof.pop()
elif l == './':
pass
else:
listof.append(l)
le = len(listof)
return le | crawler-log-folder | Python solution | Sheeza | 0 | 4 | crawler log folder | 1,598 | 0.644 | Easy | 23,437 |
https://leetcode.com/problems/crawler-log-folder/discuss/2650218/Easy-Python-solution-with-explanation | class Solution:
def minOperations(self, logs: List[str]) -> int:
# Initiate a blank list
shortest_dir_path = []
for i in range(len(logs)):
if logs[i] == "../":
# If str element = ../ , then remove last element of the shortestdirpath list only if it ain't empty. Do absolutely nothing if the list is empty
if shortest_dir_path:
shortest_dir_path.pop()
elif logs[i] != "./" :
# Since "./" means preserving the previous state hence append all the other elements except "./"
shortest_dir_path.append(logs[i])
return len(shortest_dir_path) | crawler-log-folder | Easy Python solution with explanation | code_snow | 0 | 12 | crawler log folder | 1,598 | 0.644 | Easy | 23,438 |
https://leetcode.com/problems/crawler-log-folder/discuss/2632873/Python-solution-(easy) | class Solution:
def minOperations(self, logs: List[str]) -> int:
ans = 0
for i in logs:
if i == "./":
continue
elif i == "../":
if ans > 0:
ans -= 1
else:
ans += 1
return ans | crawler-log-folder | Python solution (easy) | rohansardar | 0 | 10 | crawler log folder | 1,598 | 0.644 | Easy | 23,439 |
https://leetcode.com/problems/crawler-log-folder/discuss/2614540/Simple-and-easy-way-or-Python-or-faster-than-97 | class Solution(object):
def minOperations(self, logs):
#only define two entries, one have to move folder back, other have to do nothing, means we don't need to count it. If no statment is in dictionary, it means we have created folder
#We must have to define "./" in dictionary, otherwise it will count and consider that we have created a folder in the following implementation
operations={
"../":-1,
"./":0,
}
steps=0
for opr in logs:
if opr in operations:
if steps!=0:
steps+=operations[opr]
else:
steps+=1
return steps | crawler-log-folder | Simple and easy way | Python | faster than 97% | msherazedu | 0 | 26 | crawler log folder | 1,598 | 0.644 | Easy | 23,440 |
https://leetcode.com/problems/crawler-log-folder/discuss/2484737/Python-Stack-99.54-faster-or-Simplest-solution-with-explanation-or-Beg-to-Adv-or-Stack | class Solution:
def minOperations(self, logs: List[str]) -> int:
stack = [] # taking empty stack
for elem in logs: # traversing through the list.
if elem!="../" and elem!="./": # As these are operations as we cant have them in stack as a directory.
stack.append(elem)# if its a directory then we`ll push it to the stack.
elif elem == "../" and len(stack)>0: # checking for ../ as it significs go back one directory, also to go to previous there should be some directory thats why we are checking the len of stack.
stack.pop() # if ../ operation is mentioned will go to the last directry
return len(stack) # returing len as what ever number of directories we would have, we have to take those mamy operations to get back to main. | crawler-log-folder | Python Stack 99.54% faster | Simplest solution with explanation | Beg to Adv | Stack | rlakshay14 | 0 | 39 | crawler log folder | 1,598 | 0.644 | Easy | 23,441 |
https://leetcode.com/problems/crawler-log-folder/discuss/2319446/Easy-python-stack | class Solution:
def minOperations(self, logs: List[str]) -> int:
stack=[]
for i in logs:
if stack:
if i=="../":
stack.pop()
elif i=="./":
pass
else:
stack.append(i)
else:
if i not in ("../","./"):
stack.append(i)
return len(stack) | crawler-log-folder | Easy python stack | sunakshi132 | 0 | 49 | crawler log folder | 1,598 | 0.644 | Easy | 23,442 |
https://leetcode.com/problems/crawler-log-folder/discuss/2032657/Python3-or-Easy-Solution-or-Steps-Counter-or-Time-O(N) | class Solution:
def minOperations(self, logs: List[str]) -> int:
steps = 0
for x in logs:
if x == "../":
if steps != 0:
steps -= 1
elif x == "./":
pass
else:
steps += 1
return steps | crawler-log-folder | Python3 | Easy Solution | Steps Counter | Time O(N) | PeterPierinakos | 0 | 19 | crawler log folder | 1,598 | 0.644 | Easy | 23,443 |
https://leetcode.com/problems/crawler-log-folder/discuss/2032633/Python-Stack-implementation | class Solution:
def minOperations(self, logs: List[str]) -> int:
stack = []
for i in logs:
if i == "./":
pass
elif i=="../":
if len(stack)>0:
stack.pop()
else:
stack.append(i[0:len(i)-1])
return len(stack) | crawler-log-folder | Python Stack implementation | Vamsidhar01 | 0 | 27 | crawler log folder | 1,598 | 0.644 | Easy | 23,444 |
https://leetcode.com/problems/crawler-log-folder/discuss/1998240/Python-Solution-or-Over-96-Faster-or-Straightforward-Logic | class Solution:
def minOperations(self, logs: List[str]) -> int:
deep = 0
for op in logs:
if op == "./":
continue
elif op == "../":
if deep > 0:
deep -= 1
else:
deep += 1
return deep | crawler-log-folder | Python Solution | Over 96% Faster | Straightforward Logic | Gautam_ProMax | 0 | 19 | crawler log folder | 1,598 | 0.644 | Easy | 23,445 |
https://leetcode.com/problems/crawler-log-folder/discuss/1862411/Python-Simple-Solution | class Solution:
def minOperations(self, logs: List[str]) -> int:
result = 0
for op in logs:
# The if-else conditions are ordered this way to pass certain test cases
if op == "./":
continue
elif op == "../":
# Checks if there are multiple '../' in a row when it's already in the parent folder
if result == 0:
continue
else:
result -= 1
else:
result += 1
return result | crawler-log-folder | Python Simple Solution | White_Frost1984 | 0 | 14 | crawler log folder | 1,598 | 0.644 | Easy | 23,446 |
https://leetcode.com/problems/crawler-log-folder/discuss/1759358/Python-dollarolution-(Faster-than-97) | class Solution:
def minOperations(self, logs: List[str]) -> int:
count = 0
for i in logs:
if i[0:2] == '..':
if count > 0:
count -= 1
elif i[0:2] != './':
count += 1
return count | crawler-log-folder | Python $olution (Faster than 97%) | AakRay | 0 | 35 | crawler log folder | 1,598 | 0.644 | Easy | 23,447 |
https://leetcode.com/problems/crawler-log-folder/discuss/1575498/44-ms-and-14.4-MB-easy-python-solution | class Solution:
def minOperations(self, logs: List[str]) -> int:
operations=0
for i in logs:
if i!="./" and i!="../":
operations+=1
if i=="../" and operations>0:
operations-=1
return operations | crawler-log-folder | 44 ms and 14.4 MB easy python solution | fluturandra2 | 0 | 20 | crawler log folder | 1,598 | 0.644 | Easy | 23,448 |
https://leetcode.com/problems/crawler-log-folder/discuss/1420963/O(1)-space-solution-in-Python | class Solution:
def minOperations(self, logs: List[str]) -> int:
i, n, cnt = 0, len(logs), 0
while i < n:
if logs[i] == "../":
if cnt > 0:
cnt -= 1
elif logs[i] != "./":
cnt += 1
i += 1
return cnt | crawler-log-folder | O(1) space solution in Python | mousun224 | 0 | 52 | crawler log folder | 1,598 | 0.644 | Easy | 23,449 |
https://leetcode.com/problems/crawler-log-folder/discuss/1327951/PythonororSimple-logicoror-o(1)-space-o(n)-time-oror-No-length-of-array-No-stack | class Solution:
def minOperations(self, logs: List[str]) -> int:
step=0
# steps till main
for x in logs:
if x=="../":
if step:
step-=1
#one folder removed move one step back or stay at main
elif x!="./":
step+=1
#one folder added move one step forward
return step
#return number of steps away from main | crawler-log-folder | Python||Simple logic|| o(1) space o(n) time || No length of array No stack | ana_2kacer | 0 | 26 | crawler log folder | 1,598 | 0.644 | Easy | 23,450 |
https://leetcode.com/problems/crawler-log-folder/discuss/1312588/Python-O(1)-Space-O(n)-time-Solution | class Solution:
def minOperations(self, logs: List[str]) -> int:
operations = 0
for log in logs:
string = log[0:2]
if string == "..":
operations -= 1 if operations > 0 else 0
elif string != "./":
operations += 1
return operations | crawler-log-folder | Python O(1) Space, O(n) time Solution | ramit_kumar | 0 | 34 | crawler log folder | 1,598 | 0.644 | Easy | 23,451 |
https://leetcode.com/problems/crawler-log-folder/discuss/1267841/python-or-easy-or-beats-99.22-runtime-and-99.22-less-memory-or | class Solution:
def minOperations(self, logs: List[str]) -> int:
ans=[]
while logs:
a= logs.pop(0)
if a=='../':
if len(ans)>0:
ans.pop()
else:
continue
elif a!= './':
ans.append(a)
return len(ans) | crawler-log-folder | python | easy | beats 99.22% runtime and 99.22% less memory | | chikushen99 | 0 | 50 | crawler log folder | 1,598 | 0.644 | Easy | 23,452 |
https://leetcode.com/problems/crawler-log-folder/discuss/1159046/Python-using-stack | class Solution:
def minOperations(self, logs: List[str]) -> int:
st = list()
for op in logs:
if not st and op == "../":
continue
elif op == "../":
st.pop()
elif op == "./":
continue
else:
st.append(op)
return (len(st)) | crawler-log-folder | Python using stack | keewook2 | 0 | 28 | crawler log folder | 1,598 | 0.644 | Easy | 23,453 |
https://leetcode.com/problems/crawler-log-folder/discuss/1139489/Python-93-faster-(Stacks)-98-faster-(without-Stacks) | class Solution:
def minOperations(self, logs: List[str]) -> int:
Operations = ['./', '../']
Stack = []
for op in logs:
if op not in Operations:
Stack.append(op)
else:
if op == '../':
if not Stack:
continue
else:
Stack.pop()
else:
continue
return len(Stack) | crawler-log-folder | Python - 93% faster (Stacks) - 98% faster (without Stacks) | piyushagg19 | 0 | 40 | crawler log folder | 1,598 | 0.644 | Easy | 23,454 |
https://leetcode.com/problems/crawler-log-folder/discuss/1139489/Python-93-faster-(Stacks)-98-faster-(without-Stacks) | class Solution:
def minOperations(self, logs: List[str]) -> int:
steps = 0
for op in logs:
if op == './':
continue
elif op == '../':
if not steps == 0:
steps -= 1
else: 0
else:
steps += 1
return steps | crawler-log-folder | Python - 93% faster (Stacks) - 98% faster (without Stacks) | piyushagg19 | 0 | 40 | crawler log folder | 1,598 | 0.644 | Easy | 23,455 |
https://leetcode.com/problems/crawler-log-folder/discuss/1060102/Python3-simple-solution | class Solution:
def minOperations(self, logs: List[str]) -> int:
count = 0
for i in logs:
if i.startswith('..'):
if count > 0:
count -= 1
elif i.startswith('.'):
pass
else:
count += 1
return count | crawler-log-folder | Python3 simple solution | EklavyaJoshi | 0 | 21 | crawler log folder | 1,598 | 0.644 | Easy | 23,456 |
https://leetcode.com/problems/crawler-log-folder/discuss/915202/Easy-Python-O(n)-Solution-with-Explanation | class Solution:
def minOperations(self, logs: List[str]) -> int:
res = 0
for i in logs:
if i == './': pass
elif i == '../': res = max(0, res-1)
else: res += 1
return res | crawler-log-folder | Easy Python O(n) Solution with Explanation | shadow_sm36 | 0 | 30 | crawler log folder | 1,598 | 0.644 | Easy | 23,457 |
https://leetcode.com/problems/crawler-log-folder/discuss/897949/Intuitive-approach-by-ifelse | class Solution:
def minOperations(self, logs: List[str]) -> int:
depth = 0
for a in logs:
if a == './':
continue
elif a == '../':
depth = max(0, depth-1)
else:
depth += 1
return depth | crawler-log-folder | Intuitive approach by if/else | puremonkey2001 | 0 | 25 | crawler log folder | 1,598 | 0.644 | Easy | 23,458 |
https://leetcode.com/problems/crawler-log-folder/discuss/1196008/python3-solution-with-stack | class Solution:
def minOperations(self, logs: List[str]) -> int:
res=[]
for word in logs:
if word=="../" and len(res)>0:
res.pop()
elif word=="./":
continue
elif word!="../" and word!="./":
res.append(word)
return len(res) | crawler-log-folder | python3 solution with stack | janhaviborde23 | -1 | 26 | crawler log folder | 1,598 | 0.644 | Easy | 23,459 |
https://leetcode.com/problems/maximum-profit-of-operating-a-centennial-wheel/discuss/866356/Python3-simulation | class Solution:
def minOperationsMaxProfit(self, customers: List[int], boardingCost: int, runningCost: int) -> int:
ans = -1
most = pnl = waiting = 0
for i, x in enumerate(customers):
waiting += x # more people waiting in line
waiting -= (chg := min(4, waiting)) # boarding
pnl += chg * boardingCost - runningCost
if most < pnl: ans, most = i+1, pnl
q, r = divmod(waiting, 4)
if 4*boardingCost > runningCost: ans += q
if r*boardingCost > runningCost: ans += 1
return ans | maximum-profit-of-operating-a-centennial-wheel | [Python3] simulation | ye15 | 5 | 381 | maximum profit of operating a centennial wheel | 1,599 | 0.436 | Medium | 23,460 |
https://leetcode.com/problems/maximum-profit-of-operating-a-centennial-wheel/discuss/866482/Python3-O(n) | class Solution:
def minOperationsMaxProfit(self, customers: List[int], boardingCost: int, runningCost: int) -> int:
n=len(customers)
dp=[]
reserved=0
on_board=0
rotation=0
for i in range(n):
if reserved!=0:
if reserved>=4:
on_board+=4
reserved += customers[i]-4
else:
new_customers=4-reserved
if customers[i]>=new_customers:
on_board+=4
reserved=customers[i]-new_customers
else:
on_board+=reserved+customers[i]
reserved=0
else:
if customers[i]>=4:
on_board+=4
reserved+=customers[i]-4
else:
on_board+=customers[i]
rotation+=1
dp.append(on_board*boardingCost - rotation*runningCost)
for i in range(reserved//4 + 1):
if reserved>=4:
on_board+=4
reserved-=4
else:
on_board+=reserved
reserved=0
rotation+=1
dp.append(on_board*boardingCost - rotation*runningCost)
maxim=max(dp)
return dp.index(maxim)+1 if maxim>=0 else -1 | maximum-profit-of-operating-a-centennial-wheel | Python3 O(n) | harshitCode13 | 0 | 46 | maximum profit of operating a centennial wheel | 1,599 | 0.436 | Medium | 23,461 |
https://leetcode.com/problems/maximum-profit-of-operating-a-centennial-wheel/discuss/866454/Python3-simple-self-explanatory-code | class Solution:
def minOperationsMaxProfit(self, customers: List[int], boardingCost: int, runningCost: int) -> int:
i=0
count=0
profit=0
rem=0
onBoard=0
max_profit_rounds=-1
max_profit=0
while True:
if i>=len(customers)-1 and rem==0:
break
if i<len(customers):
rem+=customers[i]
i+=1
count+=1
if rem>4:
onBoard+=4
rem-=4
else:
onBoard+=rem
rem=0
profit=(onBoard*boardingCost)-(count*runningCost)
if profit>max_profit:
max_profit=profit
max_profit_rounds=count
if max_profit<0:
return -1
return max_profit_rounds | maximum-profit-of-operating-a-centennial-wheel | Python3 simple self explanatory code | tharun_99 | 0 | 58 | maximum profit of operating a centennial wheel | 1,599 | 0.436 | Medium | 23,462 |
https://leetcode.com/problems/maximum-number-of-achievable-transfer-requests/discuss/866369/Python3-10-Lines-Bitmasking-or-Combinations-or-Easy-Explanation | class Solution:
def maximumRequests(self, n: int, req: List[List[int]]) -> int:
tot = len(req)
for i in range(tot, 0, -1):
comb = list(itertools.combinations([j for j in range(tot)], i))
for c in comb:
net = [0 for j in range(n)]
for idx in c:
net[req[idx][0]] -= 1
net[req[idx][1]] += 1
if net == [0 for j in range(n)]:
return i
return 0 | maximum-number-of-achievable-transfer-requests | [Python3] 10 Lines Bitmasking | Combinations | Easy Explanation | uds5501 | 17 | 1,000 | maximum number of achievable transfer requests | 1,601 | 0.513 | Hard | 23,463 |
https://leetcode.com/problems/maximum-number-of-achievable-transfer-requests/discuss/866390/Python3-dfs-w-bitmask | class Solution:
def maximumRequests(self, n: int, requests: List[List[int]]) -> int:
def fn(k, mask):
"""Return maximum number of achievable transfer requests."""
if k == len(requests):
net = [0]*n
for i, (u, v) in enumerate(requests):
if mask & 1 << i:
net[u] -= 1
net[v] += 1
return 0 if any(net) else bin(mask).count("1")
return max(fn(k+1, mask), fn(k+1, mask | 1 << k))
return fn(0, 0) | maximum-number-of-achievable-transfer-requests | [Python3] dfs w/ bitmask | ye15 | 1 | 95 | maximum number of achievable transfer requests | 1,601 | 0.513 | Hard | 23,464 |
https://leetcode.com/problems/alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/discuss/1284866/Python3-or-Dict-%2B-Sort | class Solution:
def alertNames(self, keyName: List[str], keyTime: List[str]) -> List[str]:
key_time = {}
for index, name in enumerate(keyName):
key_time[name] = key_time.get(name, [])
key_time[name].append(int(keyTime[index].replace(":", "")))
ans = []
for name, time_list in key_time.items():
time_list.sort()
n = len(time_list)
for i in range(n-2):
if time_list[i+2] - time_list[i] <= 100:
ans.append(name)
break
return sorted(ans) | alert-using-same-key-card-three-or-more-times-in-a-one-hour-period | Python3 | Dict + Sort | Sanjaychandak95 | 3 | 314 | alert using same key card three or more times in a one hour period | 1,604 | 0.473 | Medium | 23,465 |
https://leetcode.com/problems/alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/discuss/876966/Python-Simple-python-solution | class Solution:
def alertNames(self, keyName: List[str], keyTime: List[str]) -> List[str]:
mapp = {}
for i in range(len(keyName)):
name = keyName[i]
if(name not in mapp):
mapp[name] = [keyTime[i]]
else:
mapp[name].append(keyTime[i])
res = []
for name, arr in mapp.items():
arr.sort()
for i in range(len(arr)-2):
time= arr[i]
t2 = arr[i+1]
t3 = arr[i+2]
if(time[0:2]=="23"):
endTime = "24:00"
if(t2<=endTime and t3<=endTime and t2>time and t3>time):
res.append(name)
break
else:
start = int(time[0:2])
endTime = str(start+1)+time[2:]
if(start<9):
endTime = "0"+endTime
if(t2<=endTime and t3<=endTime):
res.append(name)
break
return sorted(res) | alert-using-same-key-card-three-or-more-times-in-a-one-hour-period | [Python] Simple python solution | AnupBS | 3 | 426 | alert using same key card three or more times in a one hour period | 1,604 | 0.473 | Medium | 23,466 |
https://leetcode.com/problems/alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/discuss/1868311/Python-3-or-Default-Dict-or-Times-to-Minutes | class Solution:
def get_minute(self, time):
hour, minute = map(int, time.split(':'))
return hour * 60 + minute
def alertNames(self, keyName: List[str], keyTime: List[str]) -> List[str]:
lookup = defaultdict(list)
for name, time in zip(keyName, keyTime):
lookup[name].append(self.get_minute(time))
ans = []
for name in sorted(lookup.keys()):
times = lookup[name]
times.sort()
for i in range(1, len(times) - 1):
if times[i + 1] - times[i - 1] <= 60:
ans.append(name)
break
return ans | alert-using-same-key-card-three-or-more-times-in-a-one-hour-period | Python 3 | Default Dict | Times to Minutes | leeteatsleep | 1 | 146 | alert using same key card three or more times in a one hour period | 1,604 | 0.473 | Medium | 23,467 |
https://leetcode.com/problems/alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/discuss/2794500/Python3-Simply-Solution-by-casting-time-to-index | class Solution:
def alertNames(self, keyName: List[str], keyTime: List[str]) -> List[str]:
def cast_to_index(time):
hour, minutes = int(time[:2]), int(time[3:])
return hour*60 + minutes
dicts = defaultdict(list)
for i in range(len(keyName)):
name, time = keyName[i], keyTime[i]
dicts[name].append(cast_to_index(time))
res = []
for key,value in dicts.items():
value.sort()
for t in range(len(value)-2):
if value[t+2] - value[t] <= 60:
res.append(key)
break
return sorted(res) | alert-using-same-key-card-three-or-more-times-in-a-one-hour-period | Python3 Simply Solution by casting time to index | xxHRxx | 0 | 7 | alert using same key card three or more times in a one hour period | 1,604 | 0.473 | Medium | 23,468 |
https://leetcode.com/problems/alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/discuss/2560509/Python3-solution-with-dictmap-and-sliding-window | class Solution:
def alertNames(self, keyName: List[str], keyTime: List[str]) -> List[str]:
hmap = {}
for i in range(len(keyName)):
hmap[keyName[i]] = hmap.get(keyName[i], []) + [int("".join(keyTime[i].split(":")))]
results = []
for ids, times in hmap.items():
times.sort()
for i in range(len(times)-2):
if times[i+2] - times[i] < 60:
results.append(ids)
break
elif times[i+2] // 100 == times[i] // 100 + 1 and times[i] % 100 - times[i+2] % 100 >= 0:
results.append(ids)
break
return sorted(results) | alert-using-same-key-card-three-or-more-times-in-a-one-hour-period | Python3 solution with dict/map and sliding window | WizardOfGryfindor | 0 | 69 | alert using same key card three or more times in a one hour period | 1,604 | 0.473 | Medium | 23,469 |
https://leetcode.com/problems/alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/discuss/2077820/Python3%3A-O(nlogn)-Solution-using-defaultdict-(Dictionary)-and-Sort | class Solution:
def alertNames(self, keyName: List[str], keyTime: List[str]) -> List[str]:
"""
1. use dict to record each name's min
2. for each name in dict, check if within 60 min
"""
def getMin(time):
"""
turn hr:min to min
"""
hr_, min_ = time.split(":")
return int(hr_)*60+int(min_)
from collections import defaultdict
d = defaultdict(list)
# O(nlogn)
zipped = sorted(zip(keyName, map(getMin, keyTime)))
# O(n)
for name, time in zipped:
d[name].append(time)
res = []
for name in d:
time = d[name]
for t in range(2, len(time)):
t1 = time[t-2]
t3 = time[t]
if (t1+60>=t3):
res.append(name)
break
return res | alert-using-same-key-card-three-or-more-times-in-a-one-hour-period | Python3: O(nlogn) Solution using defaultdict (Dictionary) and Sort | yunglinchang | 0 | 71 | alert using same key card three or more times in a one hour period | 1,604 | 0.473 | Medium | 23,470 |
https://leetcode.com/problems/alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/discuss/1732535/Python-Using-Deque | class Solution:
def alertNames(self, keyName: List[str], keyTime: List[str]) -> List[str]:
d = defaultdict(collections.deque)
items = list(zip(keyName, iter(datetime.datetime.strptime(item, "%H:%M") for item in keyTime)))
items.sort(key=lambda l: l[1])
res = set()
for name, time in items:
if len(d[name]) == 2:
if (time - d[name][0]).seconds <= 3600:
res.add(name)
d[name].append(time)
while len(d[name]) > 2:
d[name].popleft()
return sorted([name for name in res]) | alert-using-same-key-card-three-or-more-times-in-a-one-hour-period | Python Using Deque | etherealoptimist | 0 | 66 | alert using same key card three or more times in a one hour period | 1,604 | 0.473 | Medium | 23,471 |
https://leetcode.com/problems/alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/discuss/1088753/Python3-dict-of-deques | class Solution:
def alertNames(self, keyName: List[str], keyTime: List[str]) -> List[str]:
ans = set()
seen = {}
for key, time in sorted(zip(keyName, keyTime)):
if key not in ans:
h, m = time.split(":")
time = int(h) * 60 + int(m)
seen.setdefault(key, deque()).append(time)
if len(seen[key]) == 3:
if seen[key][-1] <= seen[key][0] + 60: ans.add(key)
seen[key].popleft()
return sorted(ans) | alert-using-same-key-card-three-or-more-times-in-a-one-hour-period | [Python3] dict of deques | ye15 | 0 | 80 | alert using same key card three or more times in a one hour period | 1,604 | 0.473 | Medium | 23,472 |
https://leetcode.com/problems/find-valid-matrix-given-row-and-column-sums/discuss/1734833/Python-or-Backtracking | class Solution:
def restoreMatrix(self, rowSum: List[int], colSum: List[int]) -> List[List[int]]:
def backtrack(y, x):
choice = min(rowSum[y], colSum[x])
result[y][x] = choice
rowSum[y] -= choice
colSum[x] -= choice
if y == 0 and x == 0:
return
elif not rowSum[y]:
backtrack(y - 1, x)
elif not colSum[x]:
backtrack(y, x - 1)
Y, X = len(rowSum), len(colSum)
result = [[0 for _ in range(X)] for _ in range(Y)]
backtrack(Y-1, X-1)
return result | find-valid-matrix-given-row-and-column-sums | Python | Backtracking | holdenkold | 1 | 102 | find valid matrix given row and column sums | 1,605 | 0.78 | Medium | 23,473 |
https://leetcode.com/problems/find-valid-matrix-given-row-and-column-sums/discuss/2792270/Python3-or-Moving-Extra-Sum-to-next-column-or-Explanation | class Solution:
def restoreMatrix(self, rowSum: List[int], colSum: List[int]) -> List[List[int]]:
n,m=len(rowSum),len(colSum)
matrix = [[0 for i in range(m)] for j in range(n)]
total = 0
for i in range(n):
matrix[i][0] = rowSum[i]
total += rowSum[i]
for c in range(m):
if total == colSum[c]:
break
else:
nextTotal = total - colSum[c]
total = nextTotal
for r in range(n):
curr = min(matrix[r][c],total)
matrix[r][c] -= curr
total -= curr
if c+1 < m:
matrix[r][c+1] = curr
total = nextTotal
return matrix | find-valid-matrix-given-row-and-column-sums | [Python3] | Moving Extra Sum to next column | Explanation | swapnilsingh421 | 0 | 2 | find valid matrix given row and column sums | 1,605 | 0.78 | Medium | 23,474 |
https://leetcode.com/problems/find-valid-matrix-given-row-and-column-sums/discuss/2769890/Simple-Approach | class Solution:
def restoreMatrix(self, rowSum: List[int], colSum: List[int]) -> List[List[int]]:
R = sorted([r, i] for i, r in enumerate(rowSum))
C = sorted([c, j] for j, c in enumerate(colSum))
# print(R, C)
i, j, m, n = 0, 0, len(rowSum), len(colSum)
ans = [[0]*n for _ in range(m)]
while i < m and j < n:
r, ir = R[i]
c, jc = C[j]
if r == c:
ans[ir][jc] = r
i += 1
j += 1
elif r < c:
ans[ir][jc] = r
C[j][0] = c-r
i += 1
else:
ans[ir][jc] = c
R[i][0] = r-c
j += 1
return ans | find-valid-matrix-given-row-and-column-sums | Simple Approach | Mencibi | 0 | 6 | find valid matrix given row and column sums | 1,605 | 0.78 | Medium | 23,475 |
https://leetcode.com/problems/find-valid-matrix-given-row-and-column-sums/discuss/2270771/Python!-Explained-and-easy-to-understand! | class Solution:
def restoreMatrix(self, rowSum: List[int], colSum: List[int]) -> List[List[int]]:
"""
We can firstly push the number in smallest rowSum and colSum, and push the remain number.
Time comlexity: O(n)(sort use O(nlogn)), space comlexity: O(1)(if ignore the space of answer and sort the rowSum and colSum in-place)
"""
# Generate a matrix contain 0
ans=[[0]*len(colSum) for _ in range(len(rowSum))]
# Enumarate rowNum and colNum and sort them by value
row,col=[[i,rowSum[i]]for i in range(len(rowSum))],[[i,colSum[i]]for i in range(len(colSum))]
row.sort(key=lambda x:x[1])
col.sort(key=lambda x:x[1])
# From smallest rowSum and colSum, push the min(rowSum,colSum) into the position of them, keep it from exceeding the both sum.
# Pop the smaller one, because it has been total used, and the other one minus the amount.
while row and col:
if row[0][1]<=col[0][1]:
ans[row[0][0]][col[0][0]]=row[0][1]
col[0][1]-=row[0][1]
row.pop(0)
else:
ans[row[0][0]][col[0][0]]=col[0][1]
row[0][1]-=col[0][1]
col.pop(0)
return ans | find-valid-matrix-given-row-and-column-sums | Python! Explained and easy to understand! | XRFXRF | 0 | 66 | find valid matrix given row and column sums | 1,605 | 0.78 | Medium | 23,476 |
https://leetcode.com/problems/find-valid-matrix-given-row-and-column-sums/discuss/2263157/Python-Solution | class Solution:
def restoreMatrix(self, rowSum: List[int], colSum: List[int]) -> List[List[int]]:
m=len(rowSum)
n=len(colSum)
arr=[[0]*n for _ in range(m)]
i,j=0,0
while(i<m and j<n):
arr[i][j]=min(rowSum[i],colSum[j])
rowSum[i]-=arr[i][j]
colSum[j]-=arr[i][j]
j+=1
if rowSum[i]==0:
i+=1
j=0
if colSum==n:
j=0
return arr | find-valid-matrix-given-row-and-column-sums | Python Solution | SakshiMore22 | 0 | 28 | find valid matrix given row and column sums | 1,605 | 0.78 | Medium | 23,477 |
https://leetcode.com/problems/find-valid-matrix-given-row-and-column-sums/discuss/1265281/python-oror-clean-and-concise-oror-easy | class Solution:
def restoreMatrix(self, rowSum: List[int], colSum: List[int]) -> List[List[int]]:
n= len(rowSum)
m = len(colSum)
t=[ [0]*(m) for j in range(n)]
for i in range(n):
for j in range(m):
a=min( rowSum[i] , colSum[j] )
t[i][j] = a
rowSum[i] -= a
colSum[j]-=a
return t | find-valid-matrix-given-row-and-column-sums | python || clean and concise || easy | chikushen99 | 0 | 134 | find valid matrix given row and column sums | 1,605 | 0.78 | Medium | 23,478 |
https://leetcode.com/problems/find-valid-matrix-given-row-and-column-sums/discuss/1182626/Easy-and-very-simple-Approach | class Solution:
def restoreMatrix(self, rowSum: List[int], colSum: List[int]) -> List[List[int]]:
row=len(rowSum)
col=len(colSum)
res=[[0 for _ in range(col)] for _ in range(row)]
for i in range(row):
for j in range(col):
res[i][j]=min(rowSum[i],colSum[j])
rowSum[i]-=res[i][j]
colSum[j]-=res[i][j]
return res | find-valid-matrix-given-row-and-column-sums | Easy and very simple Approach | jaipoo | 0 | 83 | find valid matrix given row and column sums | 1,605 | 0.78 | Medium | 23,479 |
https://leetcode.com/problems/find-valid-matrix-given-row-and-column-sums/discuss/1088759/Python3-greedy | class Solution:
def restoreMatrix(self, rowSum: List[int], colSum: List[int]) -> List[List[int]]:
m, n = len(rowSum), len(colSum) # dimensions
ans = [[0]*n for _ in range(m)]
pq = [(-y, j) for j, y in enumerate(colSum)] # min-heap
heapify(pq)
for i, x in enumerate(rowSum):
while x > 0:
y, j = heappop(pq)
ans[i][j] = min(x, -y)
if x + y < 0:
y += x
heappush(pq, (y, j))
x = 0
else: x += y
return ans | find-valid-matrix-given-row-and-column-sums | [Python3] greedy | ye15 | 0 | 126 | find valid matrix given row and column sums | 1,605 | 0.78 | Medium | 23,480 |
https://leetcode.com/problems/find-valid-matrix-given-row-and-column-sums/discuss/1088759/Python3-greedy | class Solution:
def restoreMatrix(self, rowSum: List[int], colSum: List[int]) -> List[List[int]]:
m, n = len(rowSum), len(colSum) # dimensions
ans = [[0]*n for _ in range(m)]
i = j = 0
while i < len(rowSum) and j < len(colSum):
ans[i][j] = min(rowSum[i], colSum[j])
rowSum[i] -= ans[i][j]
colSum[j] -= ans[i][j]
if rowSum[i] == 0: i += 1
if colSum[j] == 0: j += 1
return ans | find-valid-matrix-given-row-and-column-sums | [Python3] greedy | ye15 | 0 | 126 | find valid matrix given row and column sums | 1,605 | 0.78 | Medium | 23,481 |
https://leetcode.com/problems/find-valid-matrix-given-row-and-column-sums/discuss/877972/Intuitive-approach-by-keeping-all-row-sum-in-first-column-and-make-deduction-from-them | class Solution:
def restoreMatrix(self, rowSum: List[int], colSum: List[int]) -> List[List[int]]:
# 0) Initialization
ROW_SIZE = len(rowSum)
COL_SIZE = len(colSum)
mtx = [[0] * COL_SIZE for ri in range(ROW_SIZE)]
for i, rs in enumerate(rowSum):
mtx[i][0] = rs
# 1) Iteratively meet column sum by making reduction from first column
valid_row_set = set(list(filter(lambda ri: mtx[ri][0], range(ROW_SIZE))))
for ci in range(1, COL_SIZE):
cs = colSum[ci]
empty_ri_list = []
for ri in valid_row_set:
if mtx[ri][0] < cs:
cs -= mtx[ri][0]
mtx[ri][ci] = mtx[ri][0]
mtx[ri][0] = 0
empty_ri_list.append(ri)
elif mtx[ri][0] == cs:
mtx[ri][ci] = mtx[ri][0]
mtx[ri][0] = cs = 0
empty_ri_list.append(ri)
break
elif mtx[ri][0] > cs:
mtx[ri][ci] = cs
mtx[ri][0] -= cs
break
for eri in empty_ri_list:
valid_row_set.remove(eri)
return mtx | find-valid-matrix-given-row-and-column-sums | Intuitive approach by keeping all row sum in first column and make deduction from them | puremonkey2001 | 0 | 38 | find valid matrix given row and column sums | 1,605 | 0.78 | Medium | 23,482 |
https://leetcode.com/problems/find-servers-that-handled-most-number-of-requests/discuss/1089184/Python3-summarizing-3-approaches | class Solution:
def busiestServers(self, k: int, arrival: List[int], load: List[int]) -> List[int]:
busy = [] # min-heap
free = list(range(k)) # min-heap
freq = [0]*k
for i, (ta, tl) in enumerate(zip(arrival, load)):
while busy and busy[0][0] <= ta:
_, ii = heappop(busy)
heappush(free, i + (ii - i) % k) # circularly relocate it
if free:
ii = heappop(free) % k
freq[ii] += 1
heappush(busy, (ta+tl, ii))
mx = max(freq)
return [i for i, x in enumerate(freq) if x == mx] | find-servers-that-handled-most-number-of-requests | [Python3] summarizing 3 approaches | ye15 | 13 | 641 | find servers that handled most number of requests | 1,606 | 0.429 | Hard | 23,483 |
https://leetcode.com/problems/special-array-with-x-elements-greater-than-or-equal-x/discuss/1527669/Python-or-Faster-than-94-or-2-methods-or-O(nlogn) | class Solution:
def specialArray(self, nums: List[int]) -> int:
nums.sort()
n = len(nums)
if n<=nums[0]:
return n
for i in range(1,n):
count = n-i #counts number of elements in nums greater than equal i
if nums[i]>=(count) and (count)>nums[i-1]:
return count
return -1 | special-array-with-x-elements-greater-than-or-equal-x | Python | Faster than 94% | 2 methods | O(nlogn) | ana_2kacer | 5 | 531 | special array with x elements greater than or equal x | 1,608 | 0.601 | Easy | 23,484 |
https://leetcode.com/problems/special-array-with-x-elements-greater-than-or-equal-x/discuss/1527669/Python-or-Faster-than-94-or-2-methods-or-O(nlogn) | class Solution:
def specialArray(self, nums: List[int]) -> int:
nums.sort()
n = len(nums)
if n<=nums[0]:
return n
#binary search
start,end = 0,n
while(start<=end):
mid = (start+end)//2
#index of middle element
count = 0
for i in range(0,n):
if nums[i]>=mid:
count = n-i
#count+=1 could use this but will take more iterations then.
break
if count==mid:
return count
elif count<mid:
end = mid-1
else:
start=mid+1
return -1 | special-array-with-x-elements-greater-than-or-equal-x | Python | Faster than 94% | 2 methods | O(nlogn) | ana_2kacer | 5 | 531 | special array with x elements greater than or equal x | 1,608 | 0.601 | Easy | 23,485 |
https://leetcode.com/problems/special-array-with-x-elements-greater-than-or-equal-x/discuss/2330480/Python-Simple-Python-Solution-Using-Two-Approach | class Solution:
def specialArray(self, nums: List[int]) -> int:
low = 0
high = 1000
while low <= high:
mid = ( low + high ) //2
count = 0
for current_number in nums:
if current_number >= mid:
count = count + 1
if mid == count:
return mid
elif mid < count:
low = mid + 1
elif mid > count:
high = mid - 1
return -1 | special-array-with-x-elements-greater-than-or-equal-x | [ Python ] β
β
Simple Python Solution Using Two Approach π₯³βπ | ASHOK_KUMAR_MEGHVANSHI | 3 | 148 | special array with x elements greater than or equal x | 1,608 | 0.601 | Easy | 23,486 |
https://leetcode.com/problems/special-array-with-x-elements-greater-than-or-equal-x/discuss/2330480/Python-Simple-Python-Solution-Using-Two-Approach | class Solution:
def specialArray(self, nums: List[int]) -> int:
nums = sorted(nums)[::-1]
for num in range(len(nums) + 1):
count = 0
for current_number in nums:
if current_number >= num:
count = count + 1
if count == num:
return num
return -1 | special-array-with-x-elements-greater-than-or-equal-x | [ Python ] β
β
Simple Python Solution Using Two Approach π₯³βπ | ASHOK_KUMAR_MEGHVANSHI | 3 | 148 | special array with x elements greater than or equal x | 1,608 | 0.601 | Easy | 23,487 |
https://leetcode.com/problems/special-array-with-x-elements-greater-than-or-equal-x/discuss/2709600/Python-O(n)-Solution | class Solution:
def specialArray(self, nums: List[int]) -> int:
freq=[0 for _ in range(max(nums)+1)]
for i in nums:
freq[i]+=1
suff=[freq[-1]]
for i in freq[::-1][1:]:
suff.append(suff[-1]+i)
suff=suff[::-1]
for i in range(max(nums)+1):
if suff[i]==i:
return i
return -1 | special-array-with-x-elements-greater-than-or-equal-x | Python - O(n) Solution | prateekgoel7248 | 2 | 179 | special array with x elements greater than or equal x | 1,608 | 0.601 | Easy | 23,488 |
https://leetcode.com/problems/special-array-with-x-elements-greater-than-or-equal-x/discuss/2392444/Python-oror-Faster-than-97.27-oror-Sort-and-Binary-Search | class Solution:
def specialArray(self, nums: List[int]) -> int:
#Sorting nums array
nums.sort()
for i in range(len(nums), 0, -1):
#Binary Search for i
low, high = 0, len(nums) - 1
while low <= high:
mid = (low + high) // 2
if nums[mid] < i:
low = mid + 1
else:
high = mid - 1
#Got index of i in sorted list nums in variable low
#Numbers after index i are greater than equal to i = len(nums) - low
if len(nums) - low == i:
return i
return -1 | special-array-with-x-elements-greater-than-or-equal-x | Python || Faster than 97.27% || Sort and Binary Search | dhruva3223 | 1 | 89 | special array with x elements greater than or equal x | 1,608 | 0.601 | Easy | 23,489 |
https://leetcode.com/problems/special-array-with-x-elements-greater-than-or-equal-x/discuss/1932987/orRuntime%3A-faster-than-92.71-or-or-Memory-Usage%3A-less-than-98.29-or | class Solution:
def specialArray(self, nums: List[int]) -> int:
nums.sort()
n = len(nums)
for x in range(1,len(nums)+1):
s = 0
e = len(nums) - 1
while s <=e:
mid = (s + e)//2
if nums[mid] <x:
s= mid + 1
else:
e = mid - 1
if len(nums[s:]) == x:
return x
return -1 | special-array-with-x-elements-greater-than-or-equal-x | |Runtime: faster than 92.71% | | Memory Usage: less than 98.29% | | Ashi_garg | 1 | 91 | special array with x elements greater than or equal x | 1,608 | 0.601 | Easy | 23,490 |
https://leetcode.com/problems/special-array-with-x-elements-greater-than-or-equal-x/discuss/1787793/Python3-accepted-solution | class Solution:
def specialArray(self, nums: List[int]) -> int:
for i in range(1,len(nums)+1):
if(len([nums[j] for j in range(len(nums)) if(nums[j]>=i)]) == i):
return i
return -1 | special-array-with-x-elements-greater-than-or-equal-x | Python3 accepted solution | sreeleetcode19 | 1 | 41 | special array with x elements greater than or equal x | 1,608 | 0.601 | Easy | 23,491 |
https://leetcode.com/problems/special-array-with-x-elements-greater-than-or-equal-x/discuss/1569042/python-sorting-solution | class Solution:
def specialArray(self, nums: List[int]) -> int:
nums.sort()
nums.insert(0, -1)
n = len(nums)
for i in range(1, n):
if nums[i-1] < n - i <= nums[i]:
return n - i
return -1 | special-array-with-x-elements-greater-than-or-equal-x | python sorting solution | dereky4 | 1 | 149 | special array with x elements greater than or equal x | 1,608 | 0.601 | Easy | 23,492 |
https://leetcode.com/problems/special-array-with-x-elements-greater-than-or-equal-x/discuss/1473375/Sort-and-pass-once-98-speed | class Solution:
def specialArray(self, nums: List[int]) -> int:
len_nums = len(nums)
nums.sort(reverse=True)
if nums[0] == 1:
return 1
for i in range(1, len_nums):
if nums[i - 1] >= i > nums[i]:
return i
if nums[-1] >= len_nums:
return len_nums
return -1 | special-array-with-x-elements-greater-than-or-equal-x | Sort and pass once, 98% speed | EvgenySH | 1 | 150 | special array with x elements greater than or equal x | 1,608 | 0.601 | Easy | 23,493 |
https://leetcode.com/problems/special-array-with-x-elements-greater-than-or-equal-x/discuss/1084572/Python3-simple-solution | class Solution:
def specialArray(self, nums: List[int]) -> int:
k = -1
while k <= len(nums):
count = 0
for i in nums:
if i >= k:
count += 1
if k == count:
return k
k += 1
return -1 | special-array-with-x-elements-greater-than-or-equal-x | Python3 simple solution | EklavyaJoshi | 1 | 87 | special array with x elements greater than or equal x | 1,608 | 0.601 | Easy | 23,494 |
https://leetcode.com/problems/special-array-with-x-elements-greater-than-or-equal-x/discuss/2829483/Special-Array-With-X-Elements-Greater-Than-or-Equal-X-or-Python | class Solution:
def specialArray(self, nums: List[int]) -> int:
nums.sort(reverse=True)
left, right = 0, len(nums)
while left < right:
mid = left + (right - left) // 2
if mid < nums[mid]:
left = mid + 1
else:
right = mid
return -1 if left < len(nums) and left == nums[left] else left | special-array-with-x-elements-greater-than-or-equal-x | Special Array With X Elements Greater Than or Equal X | Python | jashii96 | 0 | 1 | special array with x elements greater than or equal x | 1,608 | 0.601 | Easy | 23,495 |
https://leetcode.com/problems/special-array-with-x-elements-greater-than-or-equal-x/discuss/2813355/simple-python-n(log-n) | class Solution:
def specialArray(self, nums: List[int]) -> int:
nums.sort()
for i in range(nums[-1]+1):
low = 0
high = len(nums)
while(low<high):
mid = (low+high)//2
if nums[mid]<i:
low = mid+1
else:
high = mid
if i == len(nums)-low:
return len(nums)-low
else:
return -1 | special-array-with-x-elements-greater-than-or-equal-x | simple python n(log n) | sudharsan1000m | 0 | 1 | special array with x elements greater than or equal x | 1,608 | 0.601 | Easy | 23,496 |
https://leetcode.com/problems/special-array-with-x-elements-greater-than-or-equal-x/discuss/2801013/Help-needed-why-two-seemingly-identical-codes-give-different-results | class Solution:
def specialArray(self, nums: List[int]) -> int:
nums.append(-1)
nums = sorted(nums,reverse = True)
for i,x in enumerate(nums[:len(nums)-1],start=1):
if i <= x and i > nums[i]:
return i
return -1 | special-array-with-x-elements-greater-than-or-equal-x | Help needed - why two seemingly identical codes give different results? | piotr_swicarz | 0 | 10 | special array with x elements greater than or equal x | 1,608 | 0.601 | Easy | 23,497 |
https://leetcode.com/problems/special-array-with-x-elements-greater-than-or-equal-x/discuss/2801013/Help-needed-why-two-seemingly-identical-codes-give-different-results | class Solution:
def specialArray(self, nums: List[int]) -> int:
nums.append(-1)
for i,x in enumerate(sorted(nums,reverse = True)[:len(nums)-1],start=1):
if i <= x and i > nums[i]:
return i
return -1 | special-array-with-x-elements-greater-than-or-equal-x | Help needed - why two seemingly identical codes give different results? | piotr_swicarz | 0 | 10 | special array with x elements greater than or equal x | 1,608 | 0.601 | Easy | 23,498 |
https://leetcode.com/problems/special-array-with-x-elements-greater-than-or-equal-x/discuss/2689789/Easy-To-Understand-Python-Solution | class Solution:
def specialArray(self, nums: List[int]) -> int:
n = len(nums)
while n != len([x for x in nums if x >= n]):
n -= 1
if n == 0:
return -1
return n | special-array-with-x-elements-greater-than-or-equal-x | Easy To Understand Python Solution | scifigurmeet | 0 | 1 | special array with x elements greater than or equal x | 1,608 | 0.601 | Easy | 23,499 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.