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/decode-the-message/discuss/2566207/Python-oror-Hashmap-Simple-Solution
|
class Solution:
def decodeMessage(self, key: str, message: str) -> str:
a = []
b = []
j = 0
s = key.replace(' ','')
for i in range(ord('a'),ord('z')+1):
a.append(chr(i))
for j in range(len(s)):
if s[j] not in b:
b.append(s[j])
else:
continue
d = dict(zip(b,a))
temp = []
for i in range(len(message)):
if message[i] != ' ':
temp.append(d[message[i]])
else:
temp.append(' ')
return ''.join(temp)
|
decode-the-message
|
Python || Hashmap Simple Solution
|
PravinBorate
| 0
| 44
|
decode the message
| 2,325
| 0.848
|
Easy
| 32,000
|
https://leetcode.com/problems/decode-the-message/discuss/2361922/Python-simple-solution
|
class Solution:
def decodeMessage(self, key: str, message: str) -> str:
from string import ascii_lowercase as al
unique_set = set()
ans_dict = {}
for i in [x for x in key if x != ' ']:
if i in unique_set:
continue
else:
unique_set.add(i)
ans_dict[i] = al[len(unique_set)-1]
ans = ''
for i in message:
if i == ' ':
ans += ' '
else:
ans += ans_dict[i]
return ans
|
decode-the-message
|
Python simple solution
|
StikS32
| 0
| 89
|
decode the message
| 2,325
| 0.848
|
Easy
| 32,001
|
https://leetcode.com/problems/decode-the-message/discuss/2352240/Python-3-oror-HashMap-oror-Easy-to-Understand
|
class Solution:
def decodeMessage(self, key: str, message: str) -> str:
dicta = {' ': ' '} # dictionary with already defined key, value for space or ' '
alpha = 97 # chr(97) = a
for i in key:
if i == ' ': # skip for space or ' '
continue
elif i not in dicta:
dicta[i]= chr(alpha)
else:
continue
alpha+=1
answer = ''
for i in message:
answer+=dicta[i]
return answer
```
|
decode-the-message
|
Python 3 || HashMap || Easy to Understand
|
aditya_maskar
| 0
| 40
|
decode the message
| 2,325
| 0.848
|
Easy
| 32,002
|
https://leetcode.com/problems/decode-the-message/discuss/2280720/PYTHON-oror-FASTER-THAN-97-oror-SPACE-LESS-THAN-99oror-BASIC-oror-EASY
|
class Solution:
def decodeMessage(self, key: str, message: str) -> str:
message=list(message)
key=key.replace(" ","")
l,d,a=[],{},0
for i in range(len(key)):
if key[i] not in l:
d[key[i]],a=chr(97+a),a+1
l.append(key[i])
# a+=1
d[" "]=" "
for i in range(len(message)):
message[i]=d[message[i]]
return ("".join(message))
|
decode-the-message
|
PYTHON || FASTER THAN 97% || SPACE LESS THAN 99%|| BASIC || EASY
|
vatsalg2002
| 0
| 65
|
decode the message
| 2,325
| 0.848
|
Easy
| 32,003
|
https://leetcode.com/problems/decode-the-message/discuss/2255502/Python-Straightforward-solution-with-Set
|
class Solution:
def decodeMessage(self, key: str, message: str) -> str:
seen = set()
alphabet = 'abcdefghijklmnopqrstuvwxyz'
w = ''
for k in key:
if k != ' ' and k not in seen:
w += k
seen.add(k)
m = {}
for i, c in enumerate(w):
m[c] = alphabet[i]
ans = ''
for i, c in enumerate(message):
if c == ' ':
ans += ' '
continue
ans += m[c]
return ans
|
decode-the-message
|
[Python] Straightforward solution with Set
|
casshsu
| 0
| 34
|
decode the message
| 2,325
| 0.848
|
Easy
| 32,004
|
https://leetcode.com/problems/decode-the-message/discuss/2249871/python-O(n)
|
class Solution:
def decodeMessage(self, key: str, message: str) -> str:
key_dict = {}
c = ord('a')
for i in key:
if i != ' ':
if i not in key_dict:
key_dict[i] = chr(c)
c += 1
if(c > 122):
break
ans = ''
for i in message:
if i == ' ':
ans += i
else:
ans += key_dict[i]
return ans
|
decode-the-message
|
python O(n)
|
akashp2001
| 0
| 56
|
decode the message
| 2,325
| 0.848
|
Easy
| 32,005
|
https://leetcode.com/problems/decode-the-message/discuss/2244210/Python-hashMap-Beats-80
|
class Solution:
def decodeMessage(self, key: str, message: str) -> str:
d = {}
String = ''
res = ''
'''Remove the Spaces but maintain the Order of the characretrs and also keep only the first occurance of the chars'''
for k in key:
if k !=' ' and k not in String:
String += k
''' Build the Mapping Table'''
for i, ch in enumerate(String):
if ch not in d:
d[ch] = chr(97 + i)
''' Prepare the Output'''
for m in message:
if m.isalpha(): ## This if is needed to ignore the spaces.
res += d[m]
elif m ==' ': ## Keep the Spaces in its original place.
res += ' '
return res
|
decode-the-message
|
Python hashMap Beats 80%
|
theReal007
| 0
| 21
|
decode the message
| 2,325
| 0.848
|
Easy
| 32,006
|
https://leetcode.com/problems/decode-the-message/discuss/2243173/Python3-Straightforward-Mapping
|
class Solution:
def decodeMessage(self, key: str, message: str) -> str:
key_true = []
for char in key.replace(' ', ''):
if not char in key_true:
key_true.append(char)
mapping = {k: v for k, v in zip(key_true, string.ascii_lowercase)}
mapping[' '] = ' '
res = list(map(lambda x: mapping[x], message))
return ''.join(res)
|
decode-the-message
|
[Python3] Straightforward Mapping
|
ivnvalex
| 0
| 16
|
decode the message
| 2,325
| 0.848
|
Easy
| 32,007
|
https://leetcode.com/problems/decode-the-message/discuss/2239164/Python3-2-line
|
class Solution:
def decodeMessage(self, key: str, message: str) -> str:
mp = dict(zip(OrderedDict.fromkeys(key.replace(' ', '')).keys(), ascii_lowercase), **{' ' : ' '})
return ''.join(map(mp.get, message))
|
decode-the-message
|
[Python3] 2-line
|
ye15
| 0
| 19
|
decode the message
| 2,325
| 0.848
|
Easy
| 32,008
|
https://leetcode.com/problems/decode-the-message/discuss/2235289/Python-Solution-using-Map
|
class Solution:
def decodeMessage(self, key: str, message: str) -> str:
map = dict(zip(sorted(set(key.replace(" ","")), key=key.index), list(string.ascii_lowercase)))
map[' '] = ' '
res = ""
for char in message:
res += str(map[char])
return res
|
decode-the-message
|
Python Solution using Map
|
blazers08
| 0
| 14
|
decode the message
| 2,325
| 0.848
|
Easy
| 32,009
|
https://leetcode.com/problems/decode-the-message/discuss/2233760/Easy-Solution-in-Python
|
class Solution:
def decodeMessage(self, key: str, message: str) -> str:
l = []
for i in key:
if i == ' ':
continue
if i in l:
continue
l.append(i)
st = ""
for i in message:
if i == ' ':
st += ' '
else:
st += chr(97+(l.index(i)))
return st
|
decode-the-message
|
Easy Solution in Python
|
forxample
| 0
| 15
|
decode the message
| 2,325
| 0.848
|
Easy
| 32,010
|
https://leetcode.com/problems/decode-the-message/discuss/2232183/Mapping-dict()-and-string-translate-90-speed
|
class Solution:
def decodeMessage(self, key: str, message: str) -> str:
mapping, i, set_letters = {ord(" "): ord(" ")}, 97, set(" ")
for c in key:
if c not in set_letters:
mapping[ord(c)] = i
i += 1
set_letters.add(c)
return str.translate(message, mapping)
|
decode-the-message
|
Mapping dict() and string translate, 90% speed
|
EvgenySH
| 0
| 17
|
decode the message
| 2,325
| 0.848
|
Easy
| 32,011
|
https://leetcode.com/problems/decode-the-message/discuss/2231786/Python-easy-sol
|
class Solution:
def decodeMessage(self, key: str, message: str) -> str:
key=key.replace(" ","")
key=[i for i in key ]
keys=[]
for i in key:
if i not in keys:
keys.append(i)
aplha=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
res=""
k=dict(zip(keys,aplha))
all_key=[i for i in k.keys()]
for i in message:
if i in all_key:
res+=k[i]
elif i==" ":
res+=" "
return res
|
decode-the-message
|
Python easy sol
|
HeyAnirudh
| 0
| 4
|
decode the message
| 2,325
| 0.848
|
Easy
| 32,012
|
https://leetcode.com/problems/decode-the-message/discuss/2230315/Python-Simple-Python-Solution-Using-HashMap-oror-Dictionary-oror-90-Faster
|
class Solution:
def decodeMessage(self, key: str, message: str) -> str:
d = {}
alpha = 'abcdefghijklmnopqrstuvwxyz'
char = 0
for i in key:
if i != ' ' and i not in d and char < 26:
d[i] = alpha[char]
char = char + 1
result = ''
for i in message:
if i in d:
result = result + d[i]
else:
result = result + ' '
return result
|
decode-the-message
|
[ Python ] ✅✅ Simple Python Solution Using HashMap || Dictionary || 90% Faster🥳✌👍
|
ASHOK_KUMAR_MEGHVANSHI
| 0
| 35
|
decode the message
| 2,325
| 0.848
|
Easy
| 32,013
|
https://leetcode.com/problems/decode-the-message/discuss/2230157/Python-solution-using-dictionary
|
class Solution:
def decodeMessage(self, key: str, message: str) -> str:
temp = []
for k in key:
if k.isalpha() and k not in temp:
temp.append(k)
alpha = "abcdefghijklmnopqrstuvwxyz"
mapping = {}
for a, b in zip(temp, alpha):
mapping[a] = b
result = []
for c in message:
if c.isalpha():
result.append(mapping[c])
else:
result.append(c)
return "".join(result)
|
decode-the-message
|
Python solution using dictionary
|
HunkWhoCodes
| 0
| 17
|
decode the message
| 2,325
| 0.848
|
Easy
| 32,014
|
https://leetcode.com/problems/decode-the-message/discuss/2230107/Easy-python-solution-using-hashing
|
class Solution:
def decodeMessage(self, key: str, message: str) -> str:
mapp = {}
temp = 'a'
for i in range(len(key)):
if key[i] != " " and mapp.get(key[i]) == None:
mapp[key[i]] = temp
temp = chr(ord(temp) + 1)
ans = ""
for i in range(len(message)):
if message[i] != " ":
ans += mapp[message[i]]
else:
ans += " "
return ans
|
decode-the-message
|
Easy python solution using hashing
|
shodan11
| 0
| 13
|
decode the message
| 2,325
| 0.848
|
Easy
| 32,015
|
https://leetcode.com/problems/decode-the-message/discuss/2229998/python-3-or-simple-solution
|
class Solution:
def decodeMessage(self, key: str, message: str) -> str:
i = 97
encMap = {' ': ' '}
for c in key:
if c not in encMap:
encMap[c] = chr(i)
i += 1
res = []
for c in message:
res.append(encMap[c])
return ''.join(res)
|
decode-the-message
|
python 3 | simple solution
|
dereky4
| 0
| 37
|
decode the message
| 2,325
| 0.848
|
Easy
| 32,016
|
https://leetcode.com/problems/spiral-matrix-iv/discuss/2230251/Python-easy-solution-using-direction-variable
|
class Solution:
def spiralMatrix(self, m: int, n: int, head: Optional[ListNode]) -> List[List[int]]:
matrix = [[-1]*n for i in range(m)]
current = head
direction = 1
i, j = 0, -1
while current:
for _ in range(n):
if current:
j += direction
matrix[i][j] = current.val
current = current.next
m -= 1
for _ in range(m):
if current:
i += direction
matrix[i][j] = current.val
current = current.next
n -= 1
direction *= -1
return matrix
|
spiral-matrix-iv
|
Python easy solution using direction variable
|
HunkWhoCodes
| 1
| 36
|
spiral matrix iv
| 2,326
| 0.745
|
Medium
| 32,017
|
https://leetcode.com/problems/spiral-matrix-iv/discuss/2229845/Python3-solution-(copy-from-Spiral-Matrix-II)
|
class Solution:
def spiralMatrix(self, m: int, n: int, head: Optional[ListNode]) -> List[List[int]]:
lst = []
while head:
lst.append(head.val)
head = head.next
matrix = [[-1 for _ in range(n)] for _ in range(m)]
x, y, dx, dy = 0, 0, 1, 0
for i in range(len(matrix) * len(matrix[0])):
if i > len(lst) - 1:
break
matrix[y][x] = lst[i]
if not 0 <= x + dx < n:
dx, dy = -dy, dx
elif not 0 <= y + dy < m:
dx, dy = -dy, dx
elif matrix[y + dy][x + dx] != -1:
dx, dy = -dy, dx
x, y = x + dx, y + dy
return matrix
|
spiral-matrix-iv
|
Python3 solution (copy from Spiral Matrix II)
|
WoodlandXander
| 1
| 12
|
spiral matrix iv
| 2,326
| 0.745
|
Medium
| 32,018
|
https://leetcode.com/problems/spiral-matrix-iv/discuss/2737156/Python3-Turn-Right-When-You-Must-(mins-and-maxes)
|
class Solution:
def spiralMatrix(self, m: int, n: int, head: Optional[ListNode]) -> List[List[int]]:
id, jd, ret, i, j, i_min, i_max, j_min, j_max = 0, 1, [[-1 for j in range(n)] for i in range(m)], 0, 0, 0, m-1, 0, n-1
while head is not None:
ret[i][j] = head.val
head=head.next
if not (i_min <= i + id <= i_max and j_min <= j + jd <= j_max):
id, jd = jd, -id
i_min, i_max, j_min, j_max = i_min + max(0, id), i_max + min(0, id), j_min + max(0, jd), j_max + min(0, jd)
i, j = i + id, j + jd
return ret
|
spiral-matrix-iv
|
Python3 Turn Right When You Must (mins and maxes)
|
godshiva
| 0
| 1
|
spiral matrix iv
| 2,326
| 0.745
|
Medium
| 32,019
|
https://leetcode.com/problems/spiral-matrix-iv/discuss/2555905/Python3-or-13-Year-old-coder-friendly
|
class Solution:
def spiralMatrix(self, m: int, n: int, head: Optional[ListNode]) -> List[List[int]]:
matrix = [[-1 for _ in range(n)] for _ in range(m)]
left, right, top, bottom = 0, n-1, 0, m-1
cur = head
while cur:
# Go left -> right
for c in range(left, right+1):
if not cur: break
matrix[top][c] = cur.val
cur = cur.next
# Go top right -> bottom right
for r in range(top+1, bottom+1):
if not cur: break
matrix[r][right] = cur.val
cur = cur.next
# Go bottom right -> bottom left
for c in range(right-1, left-1, -1):
if not cur: break
matrix[bottom][c] = cur.val
cur = cur.next
# Go bottom -> top
for r in range(bottom-1, top, -1):
if not cur: break
matrix[r][left] = cur.val
cur = cur.next
# Update boundary
left += 1
right -= 1
top += 1
bottom -= 1
return matrix
|
spiral-matrix-iv
|
Python3 | 13 Year-old coder friendly
|
Ploypaphat
| 0
| 13
|
spiral matrix iv
| 2,326
| 0.745
|
Medium
| 32,020
|
https://leetcode.com/problems/spiral-matrix-iv/discuss/2548000/Easy-Python-Solution
|
class Solution:
def spiralMatrix(self, m: int, n: int, head: Optional[ListNode]) -> List[List[int]]:
n,m=m,n
arr=[[-1]*m for i in range(n)]
r,c=0,0
while True:
j=c
# first row
while head and j<m:
arr[r][j]=head.val
head=head.next
j+=1
i=r+1
# last column
while head and i<n:
arr[i][m-1]=head.val
head=head.next
i+=1
j=m-2
# last row
while head and j>=c:
arr[n-1][j]=head.val
head=head.next
j-=1
i=n-2
# first column
while head and i>r:
arr[i][c]=head.val
head=head.next
i-=1
# check if there's still data in linked list
if not head:
break
r+=1
c+=1
m-=1
n-=1
return arr
|
spiral-matrix-iv
|
Easy Python Solution
|
Siddharth_singh
| 0
| 12
|
spiral matrix iv
| 2,326
| 0.745
|
Medium
| 32,021
|
https://leetcode.com/problems/spiral-matrix-iv/discuss/2276249/Python3-simple-solution-trim-boundaries-after-each-round
|
class Solution:
def spiralMatrix(self, m: int, n: int, head: Optional[ListNode]) -> List[List[int]]:
result = [[None]*n for _ in range(m)]
temp = head
rowStart, rowEnd, colStart, colEnd = 0, m-1, 0, n-1
while temp and rowStart < m and rowEnd >=0 and colStart < n and colEnd >=0:
j = colStart
while j <= colEnd and temp:
result[rowStart][j] = temp.val
temp = temp.next
j+=1
rowStart+=1
i = rowStart
while i<= rowEnd and temp:
result[i][colEnd] = temp.val
temp = temp.next
i+=1
colEnd-=1
j = colEnd
while j >= colStart and temp:
result[rowEnd][j] = temp.val
temp = temp.next
j-=1
rowEnd-=1
i = rowEnd
while i >= rowStart and temp:
result[i][colStart] = temp.val
temp = temp.next
i-=1
colStart+=1
for i in range(m):
for j in range(n):
if result[i][j] == None:
result[i][j] = -1
return result
|
spiral-matrix-iv
|
📌 Python3 simple solution trim boundaries after each round
|
Dark_wolf_jss
| 0
| 19
|
spiral matrix iv
| 2,326
| 0.745
|
Medium
| 32,022
|
https://leetcode.com/problems/spiral-matrix-iv/discuss/2239171/Python3-rotation
|
class Solution:
def spiralMatrix(self, m: int, n: int, head: Optional[ListNode]) -> List[List[int]]:
ans = [[-1]*n for _ in range(m)]
node = head
i, j, di, dj = 0, 0, 0, 1
while node:
ans[i][j] = node.val
node = node.next
if not (0 <= i+di < m and 0 <= j+dj < n and ans[i+di][j+dj] == -1): di, dj = dj, -di
i, j = i+di, j+dj
return ans
|
spiral-matrix-iv
|
[Python3] rotation
|
ye15
| 0
| 12
|
spiral matrix iv
| 2,326
| 0.745
|
Medium
| 32,023
|
https://leetcode.com/problems/spiral-matrix-iv/discuss/2236373/Four-loops-per-coil-100-speed
|
class Solution:
def spiralMatrix(self, rows: int, cols: int, head: Optional[ListNode]) -> List[List[int]]:
ans = [[-1] * cols for _ in range(rows)]
rows1, cols1 = rows - 1, cols - 1
min_layers = min(rows, cols) // 2
for i in range(min_layers):
for c in range(i, cols1 - i):
ans[i][c] = head.val
head = head.next
if not head:
return ans
col = cols1 - i
for r in range(i, rows1 - i):
ans[r][col] = head.val
head = head.next
if not head:
return ans
row = rows1 - i
for c in range(cols1 - i, i, -1):
ans[row][c] = head.val
head = head.next
if not head:
return ans
for r in range(rows1 - i, i, -1):
ans[r][i] = head.val
head = head.next
if not head:
return ans
if rows <= cols and rows % 2:
for c in range(min_layers, cols - min_layers):
ans[min_layers][c] = head.val
head = head.next
if not head:
return ans
elif cols % 2:
for r in range(min_layers, rows - min_layers):
ans[r][min_layers] = head.val
head = head.next
if not head:
return ans
return ans
|
spiral-matrix-iv
|
Four loops per coil, 100% speed
|
EvgenySH
| 0
| 22
|
spiral matrix iv
| 2,326
| 0.745
|
Medium
| 32,024
|
https://leetcode.com/problems/number-of-people-aware-of-a-secret/discuss/2229808/Two-Queues-or-Rolling-Array
|
class Solution:
def peopleAwareOfSecret(self, n: int, d: int, f: int) -> int:
dp, md = [1] + [0] * (f - 1), 10**9 + 7
for i in range(1, n):
dp[i % f] = (md + dp[(i + f - d) % f] - dp[i % f] + (0 if i == 1 else dp[(i - 1) % f])) % md
return sum(dp) % md
|
number-of-people-aware-of-a-secret
|
Two Queues or Rolling Array
|
votrubac
| 53
| 3,300
|
number of people aware of a secret
| 2,327
| 0.445
|
Medium
| 32,025
|
https://leetcode.com/problems/number-of-people-aware-of-a-secret/discuss/2230263/Python-Tabulation-with-visual-explanation
|
class Solution:
def peopleAwareOfSecret(self, n: int, delay: int, forget: int) -> int:
dp = [0] * (n + 1)
dp[0] = 0
dp[1] = 1
for i in range(1, n+1):
if dp[i] > 0:
lower = i + delay # 3
upper = i + forget
upper_bound = min(upper, n+1)
for j in range(lower, upper_bound):
dp[j] += dp[i]
if upper <= n:
dp[i] = 0
print(dp)
return sum(dp) % (10**9 + 7)
|
number-of-people-aware-of-a-secret
|
[Python] Tabulation with visual explanation
|
megZo
| 5
| 110
|
number of people aware of a secret
| 2,327
| 0.445
|
Medium
| 32,026
|
https://leetcode.com/problems/number-of-people-aware-of-a-secret/discuss/2229948/Python-or-DP-or-Top-Down-or-Easy-Solution
|
class Solution:
def peopleAwareOfSecret(self, n: int, delay: int, forget: int) -> int:
dp = [0]*n
dp[0] = 1
s = 0
for i in range(delay,n):
s += dp[i-delay]
dp[i] = s
if i-forget+1 >= 0:
s -= dp[i-forget+1]
#print(dp[-forget:])
return(sum(dp[-forget:]))%(10**9+7)
|
number-of-people-aware-of-a-secret
|
Python | DP | Top-Down | Easy Solution
|
arjuhooda
| 5
| 106
|
number of people aware of a secret
| 2,327
| 0.445
|
Medium
| 32,027
|
https://leetcode.com/problems/number-of-people-aware-of-a-secret/discuss/2230048/Python-or-DP-or-Dynamic-Programming
|
class Solution:
def peopleAwareOfSecret(self, n: int, delay: int, forget: int) -> int:
dp = [0]*(n+1)
for i in range(1, n+1):
dp[i] += 1
for k in range(i+delay, i+forget):
if k < n+ 1:
dp[k] += dp[i]
if i+forget < n+1:
dp[i+forget] -= 1
return dp[-1] % (10**9+7)
|
number-of-people-aware-of-a-secret
|
Python | DP | Dynamic Programming
|
cruizo
| 4
| 93
|
number of people aware of a secret
| 2,327
| 0.445
|
Medium
| 32,028
|
https://leetcode.com/problems/number-of-people-aware-of-a-secret/discuss/2814978/Python-(Simple-DP)
|
class Solution:
def peopleAwareOfSecret(self, n, delay, forget):
dp, total = [0]*n, 0
dp[0] = 1
for i in range(1,n):
dp[i] = total = total + dp[i-delay] - dp[i-forget]
return sum(dp[n-forget:])%(10**9+7)
|
number-of-people-aware-of-a-secret
|
Python (Simple DP)
|
rnotappl
| 0
| 1
|
number of people aware of a secret
| 2,327
| 0.445
|
Medium
| 32,029
|
https://leetcode.com/problems/number-of-people-aware-of-a-secret/discuss/2399803/Python-or-DP-or-Solution-or-O(n)-or
|
class Solution:
def peopleAwareOfSecret(self, n: int, delay: int, forget: int) -> int:
dp = [0 for i in range(n+1)]
nopss = 0
ans = 0
mod = (10**9)+7
dp[1]=1
for i in range(2,n+1):
nonpss = dp[max(i-delay,0)]
nopfs = dp[max(i-forget,0)]
nopss+=(nonpss-nopfs)
dp[i] =nopss
for i in range(n-forget+1,n+1):
ans=(ans+dp[i])%mod
return ans
|
number-of-people-aware-of-a-secret
|
Python | DP | Solution | O(n) |
|
Brillianttyagi
| 0
| 145
|
number of people aware of a secret
| 2,327
| 0.445
|
Medium
| 32,030
|
https://leetcode.com/problems/number-of-people-aware-of-a-secret/discuss/2239184/Python3-DP-%2B-sliding-window
|
class Solution:
def peopleAwareOfSecret(self, n: int, delay: int, forget: int) -> int:
dp = [0] * (n+1)
dp[1] = 1
rsm = 0
for x in range(2, n+1):
if x >= delay: rsm += dp[x-delay]
if x >= forget: rsm -= dp[x-forget]
dp[x] = rsm = rsm % 1_000_000_007
return sum(dp[-forget:]) % 1_000_000_007
|
number-of-people-aware-of-a-secret
|
[Python3] DP + sliding window
|
ye15
| 0
| 23
|
number of people aware of a secret
| 2,327
| 0.445
|
Medium
| 32,031
|
https://leetcode.com/problems/number-of-people-aware-of-a-secret/discuss/2236818/Python-3Dynaic-programming-with-memorization
|
class Solution:
def peopleAwareOfSecret(self, n: int, delay: int, forget: int) -> int:
M = 10 ** 9 + 7
@lru_cache(None)
def dp(day, know):
if know >= forget:
return 0
if day >= n:
# if reaech day n, check whether also known for delay days
# to share secrets with others
return 1 + int(know >= delay)
if know < delay:
return dp(day+1, know+1) % M
else:
# duration where current person remembers the secret
duration = min(forget - delay, n - day + 1)
# if current person still remember the secret and day n
# plus all person he shared secrets before day of forget
return (int(day+forget-delay - 1 >= n) + sum(dp(day+x, 0) for x in range(duration))) % M
return dp(1, 0) % M
|
number-of-people-aware-of-a-secret
|
[Python 3]Dynaic programming with memorization
|
chestnut890123
| 0
| 26
|
number of people aware of a secret
| 2,327
| 0.445
|
Medium
| 32,032
|
https://leetcode.com/problems/number-of-people-aware-of-a-secret/discuss/2232560/Python3-DP-Solution
|
class Solution:
def peopleAwareOfSecret(self, n: int, delay: int, forget: int) -> int:
#dp
res = [0]*n
grid = [[0]*n for _ in range(delay + 1)]
grid[0][0] = 1
res[0] = 1
correction = [0]*n
dis = forget - delay
for t in range(1, n):
for k in range(1, delay+1):
grid[k][t] += grid[k-1][t-1]
for k in range(dis):
if t + k < n:
grid[-1][t+k] += grid[-2][t-1]
grid[0][t+k] += grid[-2][t-1]
if t + dis < n:
correction[t+dis] -= grid[-2][t-1]
res[t] = (res[t-1] + grid[0][t] + correction[t])
return res[-1] % (10**9 + 7)
|
number-of-people-aware-of-a-secret
|
Python3 DP Solution
|
xxHRxx
| 0
| 13
|
number of people aware of a secret
| 2,327
| 0.445
|
Medium
| 32,033
|
https://leetcode.com/problems/number-of-people-aware-of-a-secret/discuss/2230702/Python-sliding-window-(easy-to-understand!!!!)
|
class Solution:
def peopleAwareOfSecret(self, n: int, delay: int, forget: int) -> int:
lst = [1] # at day 1, one person knows
for i in range(1, n):
if i < delay:
lst.append(0) # this day, no new people know
else:
lst.append(sum(lst[max(0, i - forget + 1):i - delay + 1])) # people in these days will tell others
return sum(lst[max(0, i - forget + 1):])%(10**9+7) #sum the people who still know
|
number-of-people-aware-of-a-secret
|
Python sliding window (easy to understand!!!!)
|
mathemagic
| 0
| 13
|
number of people aware of a secret
| 2,327
| 0.445
|
Medium
| 32,034
|
https://leetcode.com/problems/number-of-people-aware-of-a-secret/discuss/2230182/Python3-DP
|
class Solution:
def peopleAwareOfSecret(self, n: int, delay: int, forget: int) -> int:
dp = [0]*(n+1)
MOD = 10**9+7
dp[1] = 1
for i in range(2, n+1):
dp[i] = dp[i-1]
if i >= delay:
dp[i] += dp[i-delay]
if i >= forget:
dp[i] -= dp[i-forget]
return (dp[n] - dp[n-forget])%MOD
|
number-of-people-aware-of-a-secret
|
Python3 DP
|
Tinky1224
| 0
| 15
|
number of people aware of a secret
| 2,327
| 0.445
|
Medium
| 32,035
|
https://leetcode.com/problems/number-of-people-aware-of-a-secret/discuss/2229954/Python-Simple-DP
|
class Solution:
def peopleAwareOfSecret(self, n: int, delay: int, forget: int) -> int:
'''
Time: O(n^2)
Space: O(n)
'''
# record the newly pepole who know the secret on the given day
dp = [0]*(n+1)
dp[1] = 1
MOD = 10**9 + 7
for i in range(2, n+1):
# newly people who know the secret today is the sum of days(forget:delay]
for j in range(max(0, i-forget+1), max(0, i-delay+1)):
dp[i] += dp[j] % MOD
# return the sum of days where people not forget the secret yet
return sum(dp[n-forget+1:]) % MOD
|
number-of-people-aware-of-a-secret
|
[Python] Simple DP
|
nightybear
| 0
| 36
|
number of people aware of a secret
| 2,327
| 0.445
|
Medium
| 32,036
|
https://leetcode.com/problems/number-of-people-aware-of-a-secret/discuss/2229954/Python-Simple-DP
|
class Solution:
def peopleAwareOfSecret(self, n: int, delay: int, forget: int) -> int:
'''
Time: O(n)
Space: O(n)
'''
# record the newly pepole who know the secret on the given day
dp = [0]*(n+1)
dp[1] = 1
share = 0
MOD = 10**9 + 7
for i in range(2, n+1):
# newly people who know the secret today is the sum of days(forget:delay]
dp[i] = share = (share + dp[i - delay] - dp[i - forget]) % MOD
# return the sum of days where people not forget the secret yet
return sum(dp[n-forget+1:]) % MOD
|
number-of-people-aware-of-a-secret
|
[Python] Simple DP
|
nightybear
| 0
| 36
|
number of people aware of a secret
| 2,327
| 0.445
|
Medium
| 32,037
|
https://leetcode.com/problems/number-of-increasing-paths-in-a-grid/discuss/2691096/Python-(Faster-than-94)-or-DFS-%2B-DP-O(N*M)-solution
|
class Solution:
def countPaths(self, grid: List[List[int]]) -> int:
rows, cols = len(grid), len(grid[0])
dp = {}
mod = (10 ** 9) + 7
def dfs(r, c, prev):
if r < 0 or c < 0 or r >= rows or c >= cols or grid[r][c] <= prev:
return 0
if (r, c) in dp:
return dp[(r, c)]
pathLength = 1
pathLength += (dfs(r + 1, c, grid[r][c]) + dfs(r - 1, c, grid[r][c]) +
dfs(r, c + 1, grid[r][c]) + dfs(r, c - 1, grid[r][c]))
dp[(r, c)] = pathLength
return pathLength
count = 0
for r in range(rows):
for c in range(cols):
count += dfs(r, c, 0)
return count % mod
|
number-of-increasing-paths-in-a-grid
|
Python (Faster than 94%) | DFS + DP O(N*M) solution
|
KevinJM17
| 0
| 3
|
number of increasing paths in a grid
| 2,328
| 0.476
|
Hard
| 32,038
|
https://leetcode.com/problems/number-of-increasing-paths-in-a-grid/discuss/2665580/Python-or-Simple-Dynamic-Programming-or-Caching
|
class Solution:
def countPaths(self, grid: List[List[int]]) -> int:
ROWS = len(grid)
COLS = len(grid[0])
dir = [[1,0],[0,1],[-1,0],[0,-1]]
dp = {}
def dfs(r,c):
if (r,c) in dp:
return dp[(r,c)]
ans = 1
for dr,dc in dir:
if 0<=r+dr<ROWS and 0<=c+dc<COLS and grid[r+dr][c+dc]>grid[r][c]:
ans += dfs(r+dr,c+dc)
dp[(r,c)] = ans%1000000007
return ans%1000000007
res = 0
for r in range(ROWS):
for c in range(COLS):
res += dfs(r,c)
return res%1000000007
|
number-of-increasing-paths-in-a-grid
|
[Python] | Simple Dynamic Programming | Caching
|
user1508i
| 0
| 11
|
number of increasing paths in a grid
| 2,328
| 0.476
|
Hard
| 32,039
|
https://leetcode.com/problems/number-of-increasing-paths-in-a-grid/discuss/2239189/Python3-top-down-DP
|
class Solution:
def countPaths(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
@cache
def fn(i, j):
ans = 1
for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j):
if 0 <= ii < m and 0 <= jj < n and grid[ii][jj] < grid[i][j]: ans += fn(ii, jj)
return ans % 1_000_000_007
return sum(fn(i, j) for i in range(m) for j in range(n)) % 1_000_000_007
|
number-of-increasing-paths-in-a-grid
|
[Python3] top-down DP
|
ye15
| 0
| 12
|
number of increasing paths in a grid
| 2,328
| 0.476
|
Hard
| 32,040
|
https://leetcode.com/problems/number-of-increasing-paths-in-a-grid/discuss/2235245/Short-implementation-in-Python3-with-sorting-and-DP-beating-60
|
class Solution:
def countPaths(self, grid: List[List[int]]) -> int:
n, m = len(grid), len(grid[0])
counts = [[1] * m for _ in range(n)]
vertices = [(grid[i][j], i, j) for i in range(n) for j in range(m)]
vertices.sort()
for v, x, y in vertices:
for dx, dy in [(-1, 0), (1, 0), (0, 1), (0, -1)]:
nx, ny = dx+x, dy+y
if 0 <= nx < n and 0 <= ny < m and v > grid[nx][ny]:
counts[x][y] = (counts[x][y] + counts[nx][ny]) % (10**9 + 7)
return sum(sum(counts[i]) for i in range(n)) % (10**9 + 7)
|
number-of-increasing-paths-in-a-grid
|
Short implementation in Python3 with sorting and DP, beating 60%
|
metaphysicalist
| 0
| 8
|
number of increasing paths in a grid
| 2,328
| 0.476
|
Hard
| 32,041
|
https://leetcode.com/problems/number-of-increasing-paths-in-a-grid/discuss/2231379/Python-Simple-Python-Solution-Using-Depth-First-Search
|
class Solution:
def countPaths(self, grid: List[List[int]]) -> int:
dp = [[1 for _ in range(len(grid[0]))] for _ in range(len(grid))]
def DFS (r,c):
if dp[r][c] != 1:
return dp[r][c]
adjacent_points = [[r-1,c],[r,c-1],[r+1,c],[r,c+1]]
for point in adjacent_points:
x , y = point
if 0 <= x < len(grid) and 0 <= y < len(grid[0]) and grid[x][y] < grid[r][c]:
dp[r][c] = dp[r][c] + DFS(x,y)
return dp[r][c]
result = 0
for row in range(len(grid)):
for col in range(len(grid[0])):
result = result + DFS(row,col)
return result % (10 **9 + 7)
|
number-of-increasing-paths-in-a-grid
|
[ Python ] ✅✅ Simple Python Solution Using Depth-First-Search 🥳✌👍
|
ASHOK_KUMAR_MEGHVANSHI
| 0
| 36
|
number of increasing paths in a grid
| 2,328
| 0.476
|
Hard
| 32,042
|
https://leetcode.com/problems/number-of-increasing-paths-in-a-grid/discuss/2229894/Python-DFS-with-Memo
|
class Solution:
def countPaths(self, grid: List[List[int]]) -> int:
'''
time, space: O(m*n)
similar to : https://leetcode.com/problems/longest-increasing-path-in-a-matrix/
'''
R, C = len(grid), len(grid[0])
memo = {}
MOD = 10**9 + 7
def dfs(i, j, R, C, memo):
if (i, j) in memo:
return memo[(i,j)]
res = 1
for di,dj in [(1,0), (0,1), (-1,0), (0,-1)]:
ni, nj = i+di, j+dj
if 0<=ni<R and 0<=nj<C and grid[ni][nj] > grid[i][j]:
# res = max(res, dfs(ni, nj, R, C, memo))
res += dfs(ni, nj, R, C, memo)
memo[(i, j)] = res % MOD
return memo[(i, j)]
ans = 0
for i in range(R):
for j in range(C):
#ans = max(ans, dfs(i, j, R, C, memo))
ans += dfs(i, j, R, C, memo) % MOD
return ans % MOD
|
number-of-increasing-paths-in-a-grid
|
[Python] DFS with Memo
|
nightybear
| 0
| 35
|
number of increasing paths in a grid
| 2,328
| 0.476
|
Hard
| 32,043
|
https://leetcode.com/problems/evaluate-boolean-binary-tree/discuss/2566445/Easy-python-6-line-solution
|
class Solution:
def evaluateTree(self, root: Optional[TreeNode]) -> bool:
if root.val==0 or root.val==1:
return root.val
if root.val==2:
return self.evaluateTree(root.left) or self.evaluateTree(root.right)
if root.val==3:
return self.evaluateTree(root.left) and self.evaluateTree(root.right)
|
evaluate-boolean-binary-tree
|
Easy python 6 line solution
|
shubham_1307
| 6
| 282
|
evaluate boolean binary tree
| 2,331
| 0.791
|
Easy
| 32,044
|
https://leetcode.com/problems/evaluate-boolean-binary-tree/discuss/2450520/Python-recursive
|
class Solution:
def evaluateTree(self, root: Optional[TreeNode]) -> bool:
if root.left == None:
return root.val
if root.val == 2:
res = self.evaluateTree(root.left) or self.evaluateTree(root.right)
else:
res = self.evaluateTree(root.left) and self.evaluateTree(root.right)
return res
|
evaluate-boolean-binary-tree
|
Python recursive
|
aruj900
| 2
| 86
|
evaluate boolean binary tree
| 2,331
| 0.791
|
Easy
| 32,045
|
https://leetcode.com/problems/evaluate-boolean-binary-tree/discuss/2260492/Python3-oror-Recursion-and-boolean-logic-oror-5-lines
|
class Solution:
def evaluateTree(self, root: TreeNode) -> bool:
#
# Recursion:
#
# Base Case: node.val = 0 or 1. Return T or F
#
# Recursive Case: node.val = 2 or 3. Node value is determined
# upon the values l = node.left.val, r = node.right.val,
# and v = T if node.val = OR else F if node.val = AND
#
# From a Venn diagram or a truth table for l, r, v, one can
# see the return from the recursive call is l&r or l&v or r&v
#
if root.val<2: return root.val
l = self.evaluateTree(root.left)
r = self.evaluateTree(root.right)
v = root.val^1
return l&r or l&v or r&v
|
evaluate-boolean-binary-tree
|
Python3 || Recursion and boolean logic || 5 lines
|
warrenruud
| 2
| 83
|
evaluate boolean binary tree
| 2,331
| 0.791
|
Easy
| 32,046
|
https://leetcode.com/problems/evaluate-boolean-binary-tree/discuss/2361083/Python-Easy-3liner
|
class Solution:
def evaluateTree(self, root: Optional[TreeNode]) -> bool:
if root.val < 2:
return root.val
if root.val == 2:
return self.evaluateTree(root.left) or self.evaluateTree(root.right)
if root.val == 3:
return self.evaluateTree(root.left) and self.evaluateTree(root.right)
|
evaluate-boolean-binary-tree
|
[Python] Easy 3liner
|
lokeshsenthilkumar
| 1
| 32
|
evaluate boolean binary tree
| 2,331
| 0.791
|
Easy
| 32,047
|
https://leetcode.com/problems/evaluate-boolean-binary-tree/discuss/2535338/Basic-Python-Approach
|
class Solution:
def evaluateTree(self, root: Optional[TreeNode]) -> bool:
if root.val == 0:
return False
if root.val == 1:
return True
l=self.evaluateTree(root.left)
r=self.evaluateTree(root.right)
if root.val == 2:
return l | r
elif root.val == 3:
return l & r
|
evaluate-boolean-binary-tree
|
Basic Python Approach
|
beingab329
| 0
| 23
|
evaluate boolean binary tree
| 2,331
| 0.791
|
Easy
| 32,048
|
https://leetcode.com/problems/evaluate-boolean-binary-tree/discuss/2514959/Python3-Solution-with-using-dfs
|
class Solution:
def evaluateTree(self, root: Optional[TreeNode]) -> bool:
if not root:
return None
lv = self.evaluateTree(root.left)
rv = self.evaluateTree(root.right)
if lv is None and rv is None:
return root.val
if root.val == 2:
return lv or rv
return lv and rv
|
evaluate-boolean-binary-tree
|
[Python3] Solution with using dfs
|
maosipov11
| 0
| 16
|
evaluate boolean binary tree
| 2,331
| 0.791
|
Easy
| 32,049
|
https://leetcode.com/problems/evaluate-boolean-binary-tree/discuss/2275577/Python-(99-faster)-oror-Recursion
|
class Solution:
def evaluateTree(self, root: Optional[TreeNode]) -> bool:
if not root.left and not root.right:
return True if root.val == 1 else False
if root.val == 2:
return self.evaluateTree(root.left) or self.evaluateTree(root.right)
else:
return self.evaluateTree(root.left) and self.evaluateTree(root.right)
# Runtime: 51 ms, faster than 99.05% of Python3 online submissions for Evaluate Boolean Binary Tree.
# Memory Usage: 14.6 MB, less than 95.62% of Python3 online submissions for Evaluate Boolean Binary Tree.
|
evaluate-boolean-binary-tree
|
Python (99% faster) || Recursion
|
AnasTazir
| 0
| 49
|
evaluate boolean binary tree
| 2,331
| 0.791
|
Easy
| 32,050
|
https://leetcode.com/problems/evaluate-boolean-binary-tree/discuss/2270083/Python3-dfs-(recursive-and-iterative)
|
class Solution:
def evaluateTree(self, root: Optional[TreeNode]) -> bool:
if root.val in (0, 1): return bool(root.val)
elif root.val == 2: return self.evaluateTree(root.left) or self.evaluateTree(root.right)
return self.evaluateTree(root.left) and self.evaluateTree(root.right)
|
evaluate-boolean-binary-tree
|
[Python3] dfs (recursive & iterative)
|
ye15
| 0
| 58
|
evaluate boolean binary tree
| 2,331
| 0.791
|
Easy
| 32,051
|
https://leetcode.com/problems/evaluate-boolean-binary-tree/discuss/2270083/Python3-dfs-(recursive-and-iterative)
|
class Solution:
def evaluateTree(self, root: Optional[TreeNode]) -> bool:
mp = {}
stack = []
prev, node = None, root
while node or stack:
if node:
stack.append(node)
node = node.left
else:
node = stack[-1]
if node.right and node.right != prev: node = node.right
else:
if not node.left and not node.right: mp[node] = node.val
elif node.val == 2: mp[node] = mp[node.left] or mp[node.right]
else: mp[node] = mp[node.left] and mp[node.right]
stack.pop()
prev = node
node = None
return mp[root]
|
evaluate-boolean-binary-tree
|
[Python3] dfs (recursive & iterative)
|
ye15
| 0
| 58
|
evaluate boolean binary tree
| 2,331
| 0.791
|
Easy
| 32,052
|
https://leetcode.com/problems/evaluate-boolean-binary-tree/discuss/2268093/Recursive-solution-80-speed
|
class Solution:
def evaluateTree(self, root: Optional[TreeNode]) -> bool:
if root.val == 0:
return False
elif root.val == 1:
return True
left_res = self.evaluateTree(root.left)
right_res = self.evaluateTree(root.right)
if root.val == 2:
return left_res or right_res
return left_res and right_res
|
evaluate-boolean-binary-tree
|
Recursive solution, 80% speed
|
EvgenySH
| 0
| 16
|
evaluate boolean binary tree
| 2,331
| 0.791
|
Easy
| 32,053
|
https://leetcode.com/problems/evaluate-boolean-binary-tree/discuss/2260360/Python-3-simple-DFS
|
class Solution:
def evaluateTree(self, root: Optional[TreeNode]) -> bool:
if root.left==root.right:
return root.val
l,r=self.evaluateTree(root.left),self.evaluateTree(root.right)
return (l or r) if root.val==2 else (l and r)
|
evaluate-boolean-binary-tree
|
[Python 3] simple DFS
|
gabhay
| 0
| 5
|
evaluate boolean binary tree
| 2,331
| 0.791
|
Easy
| 32,054
|
https://leetcode.com/problems/evaluate-boolean-binary-tree/discuss/2259492/Python
|
class Solution:
def evaluateTree(self, root: Optional[TreeNode]) -> bool:
if not root.left and not root.right:
return root.val
if root.val == 2:
return self.evaluateTree(root.left) or self.evaluateTree(root.right)
return self.evaluateTree(root.left) and self.evaluateTree(root.right)
|
evaluate-boolean-binary-tree
|
Python
|
blue_sky5
| 0
| 29
|
evaluate boolean binary tree
| 2,331
| 0.791
|
Easy
| 32,055
|
https://leetcode.com/problems/evaluate-boolean-binary-tree/discuss/2259445/Python-or-DFS-or-Tree-traversal
|
class Solution:
def evaluateTree(self, root: Optional[TreeNode]) -> bool:
def evaluateTreeHelper(root):
if root.val < 2:
return root.val
left = evaluateTreeHelper(root.left)
right = evaluateTreeHelper(root.right)
return left or right if root.val == 2 else left and right
return evaluateTreeHelper(root)
|
evaluate-boolean-binary-tree
|
Python | DFS | Tree traversal
|
divyanshugairola
| 0
| 13
|
evaluate boolean binary tree
| 2,331
| 0.791
|
Easy
| 32,056
|
https://leetcode.com/problems/evaluate-boolean-binary-tree/discuss/2259282/Python3-Simple-Recursive-Solution
|
class Solution:
def evaluateTree(self, root: Optional[TreeNode]) -> bool:
if root.left is None:
return root.val
if root.val==2:
return self.evaluateTree(root.left) or self.evaluateTree(root.right)
else:
return self.evaluateTree(root.left) and self.evaluateTree(root.right)
|
evaluate-boolean-binary-tree
|
[Python3] Simple Recursive Solution
|
__PiYush__
| 0
| 3
|
evaluate boolean binary tree
| 2,331
| 0.791
|
Easy
| 32,057
|
https://leetcode.com/problems/the-latest-time-to-catch-a-bus/discuss/2259189/Clean-and-Concise-Greedy-with-Intuitive-Explanation
|
class Solution:
def latestTimeCatchTheBus(self, buses: List[int], passengers: List[int], capacity: int) -> int:
buses.sort()
passengers.sort()
passenger = 0
for bus in buses:
maxed_out = False
cap = capacity
while passenger < len(passengers) and passengers[passenger] <= bus and cap != 0:
passenger += 1
cap -= 1
if cap == 0:
maxed_out = True
if maxed_out:
max_seat = passengers[passenger - 1]
else:
max_seat = buses[-1]
booked = set(passengers)
for seat in range(max_seat, 0, -1):
if seat not in booked:
return seat
|
the-latest-time-to-catch-a-bus
|
Clean and Concise Greedy with Intuitive Explanation
|
wickedmishra
| 5
| 472
|
the latest time to catch a bus
| 2,332
| 0.229
|
Medium
| 32,058
|
https://leetcode.com/problems/the-latest-time-to-catch-a-bus/discuss/2270092/Python3-2-pointers
|
class Solution:
def latestTimeCatchTheBus(self, buses: List[int], passengers: List[int], capacity: int) -> int:
buses.sort()
passengers.sort()
prev = -inf
queue = deque()
prefix = i = j = 0
while i < len(buses) or j < len(passengers):
if i == len(buses) or j < len(passengers) and passengers[j] <= buses[i]:
if j == 0 or passengers[j-1] + 1 < passengers[j]: prev = passengers[j]-1
prefix += 1
if prefix and prefix % capacity == 0: queue.append(prev)
j += 1
else:
if prefix < capacity:
if j == 0 or buses[i] != passengers[j-1]: ans = buses[i]
else: ans = prev
prefix = 0
elif queue:
ans = queue.popleft()
prefix -= capacity
i += 1
return ans
|
the-latest-time-to-catch-a-bus
|
[Python3] 2 pointers
|
ye15
| 0
| 20
|
the latest time to catch a bus
| 2,332
| 0.229
|
Medium
| 32,059
|
https://leetcode.com/problems/the-latest-time-to-catch-a-bus/discuss/2260421/Python-3-Sort-%2B-Two-Pointers
|
class Solution:
def latestTimeCatchTheBus(self, buses: List[int], passengers: List[int], capacity: int) -> int:
buses.sort()
passengers.sort()
ans = 0
p = 0
for departure in buses:
count = 0
while count < capacity and p < len(passengers) and passengers[p] <= departure:
count += 1
if p == 0 or passengers[p] - 1 > passengers[p - 1]:
ans = passengers[p] - 1
p += 1
if count < capacity:
if p == 0 or passengers[p - 1] < departure:
ans = departure
return ans
|
the-latest-time-to-catch-a-bus
|
[Python 3] Sort + Two Pointers
|
llggzzz
| 0
| 17
|
the latest time to catch a bus
| 2,332
| 0.229
|
Medium
| 32,060
|
https://leetcode.com/problems/the-latest-time-to-catch-a-bus/discuss/2259364/Python3-Greedy
|
class Solution:
def latestTimeCatchTheBus(self, buses: List[int], passengers: List[int], capacity: int) -> int:
p, filled = sorted(passengers, reverse=True), set(passengers)
last_p = 0
for bus in sorted(buses):
pop_cap = capacity
while len(p) and p[-1] <= bus and pop_cap > 0:
last_p = p.pop()
pop_cap -= 1
for spot in range(bus + 1 if pop_cap else last_p)[::-1]:
if spot not in filled:
return spot
return -1
|
the-latest-time-to-catch-a-bus
|
[Python3] Greedy
|
0xRoxas
| 0
| 23
|
the latest time to catch a bus
| 2,332
| 0.229
|
Medium
| 32,061
|
https://leetcode.com/problems/the-latest-time-to-catch-a-bus/discuss/2259309/Python3-Deque-Solution
|
class Solution:
def latestTimeCatchTheBus(self, buses: List[int], passengers: List[int], capacity: int) -> int:
buses = sorted(buses)
passengers = deque(sorted(passengers))
res = buses[-1]
s = set(passengers)
prev = passengers[0]
for i, bus in enumerate(buses):
cap = capacity
while cap and passengers and passengers[0] <= bus:
val = passengers.popleft()
prev = val
cap -= 1
if val-1 not in s:
res = val-1
if cap:
for k in range(bus, prev, -1):
if k not in s:
res = k
break
return res
|
the-latest-time-to-catch-a-bus
|
[Python3] Deque Solution
|
mike840609
| 0
| 17
|
the latest time to catch a bus
| 2,332
| 0.229
|
Medium
| 32,062
|
https://leetcode.com/problems/minimum-sum-of-squared-difference/discuss/2259712/Python-Easy-to-understand-binary-search-solution
|
class Solution:
def minSumSquareDiff(self, nums1: List[int], nums2: List[int], k1: int, k2: int) -> int:
n = len(nums1)
k = k1+k2 # can combine k's because items can be turned negative
diffs = sorted((abs(x - y) for x, y in zip(nums1, nums2)))
# First binary search to find our new max for our diffs array
l, r = 0, max(diffs)
while l < r:
mid = (l+r)//2
# steps needed to reduce all nums greater than newMax
steps = sum(max(0, num-mid) for num in diffs)
if steps <= k:
r = mid
else:
l = mid+1
newMax = l
k -= sum(max(0, num-newMax) for num in diffs) # remove used k
# Second binary search to find first index to replace with max val
l, r = 0, n-1
while l < r:
mid = (l+r)//2
if diffs[mid] < newMax:
l = mid+1
else:
r = mid
# Replace items at index >= l with newMax
diffs = diffs[:l]+[newMax]*(n-l)
# Use remaining steps to reduce overall score
for i in range(len(diffs)-1,-1,-1):
if k == 0 or diffs[i] == 0: break
diffs[i] -= 1
k -= 1
return sum(diff*diff for diff in diffs)
|
minimum-sum-of-squared-difference
|
[Python] Easy to understand binary search solution
|
fomiee
| 1
| 106
|
minimum sum of squared difference
| 2,333
| 0.255
|
Medium
| 32,063
|
https://leetcode.com/problems/minimum-sum-of-squared-difference/discuss/2791380/Python-Bucket-Sort-Easy-and-Intuitive-Solution.
|
class Solution:
def minSumSquareDiff(self, nums1: List[int], nums2: List[int], k1: int, k2: int) -> int:
differences = [ abs(x - y) for x, y in zip(nums1, nums2)]
if sum(differences) <= k1 + k2:
return 0
if k1 + k2 == 0:
return sum([x**2 for x in differences])
diff = defaultdict(int)
for num in differences:
diff[num] += 1
total = k1 + k2
maxK = max(diff.keys())
for k in range(maxK, 0, -1):
if diff[k] > 0:
temp = min(total, diff[k])
diff[k] -= temp
diff[k - 1] += temp
total-= temp
res = 0
for k, v in diff.items():
res += (v * (k **2))
return res
|
minimum-sum-of-squared-difference
|
Python Bucket Sort Easy & Intuitive Solution.
|
MaverickEyedea
| 0
| 3
|
minimum sum of squared difference
| 2,333
| 0.255
|
Medium
| 32,064
|
https://leetcode.com/problems/minimum-sum-of-squared-difference/discuss/2699814/Python-O(N-%2B-KlogN)-O(N)
|
class Solution:
def minSumSquareDiff(self, nums1: List[int], nums2: List[int], k1: int, k2: int) -> int:
heap = [-abs(n1 - n2) for n1, n2 in zip(nums1, nums2)]
total = k1 + k2
if -sum(heap) <= total:
return 0
heapq.heapify(heap)
while total > 0:
val = heapq.heappop(heap)
diff = max(min(heap[0] - val, total), 1)
heapq.heappush(heap, val + diff)
total -= diff
return sum(pow(e,2) for e in heap)
|
minimum-sum-of-squared-difference
|
Python - O(N + KlogN), O(N)
|
Teecha13
| 0
| 2
|
minimum sum of squared difference
| 2,333
| 0.255
|
Medium
| 32,065
|
https://leetcode.com/problems/minimum-sum-of-squared-difference/discuss/2696069/Python3-Binary-Search-Solution-O(nlogn)
|
class Solution:
def minSumSquareDiff(self, nums1: List[int], nums2: List[int], k1: int, k2: int) -> int:
k = k1 + k2
diff_data = [abs(x - y) for x,y in zip(nums1, nums2)]
left, right = 0, max(diff_data)
while left < right:
mid = floor((left + right)/2)
k_needed = sum([max(0, x - mid) for x in diff_data])
if k_needed <= k:
right = mid
else:
left = mid + 1
if left == 0: return 0
else:
return sum([min(x, left)**2 for x in diff_data]) \
- (left**2 - (left-1)**2)*(k - sum([max(0, x - left) for x in diff_data]))
|
minimum-sum-of-squared-difference
|
Python3 Binary Search Solution O(nlogn)
|
xxHRxx
| 0
| 4
|
minimum sum of squared difference
| 2,333
| 0.255
|
Medium
| 32,066
|
https://leetcode.com/problems/minimum-sum-of-squared-difference/discuss/2270106/Python3-priority-queue
|
class Solution:
def minSumSquareDiff(self, nums1: List[int], nums2: List[int], k1: int, k2: int) -> int:
freq = Counter(abs(x1-x2) for x1, x2 in zip(nums1, nums2) if x1 != x2)
pq = [(-k, v) for k, v in freq.items()]
heapify(pq)
k1 += k2
while pq and k1:
x, v = heappop(pq)
if pq: xx, vv = heappop(pq)
else: xx = vv = 0
diff = xx - x
if diff * v <= k1:
k1 -= diff * v
if vv: heappush(pq, (xx, v+vv))
else:
q, r = divmod(k1, v)
k1 = 0
heappush(pq, (x+q+1, r))
heappush(pq, (x+q, v-r))
if vv: heappush(pq, (xx, vv))
return sum(x*x*v for x, v in pq)
|
minimum-sum-of-squared-difference
|
[Python3] priority queue
|
ye15
| 0
| 17
|
minimum sum of squared difference
| 2,333
| 0.255
|
Medium
| 32,067
|
https://leetcode.com/problems/minimum-sum-of-squared-difference/discuss/2265258/Python-3-SIMPLE-with-comments
|
class Solution:
def minSumSquareDiff(self, nums1: List[int], nums2: List[int], k1: int, k2: int) -> int:
diffs = []
for i in range(0, len(nums1)): diffs.append(abs(nums1[i]-nums2[i]))
count = k1+k2
if count >= sum(diffs): return 0
diffs.sort(reverse=True) # high -> low
L = len(diffs)
upper = 1 # upper = the number of values in the array which will be symbolically decremented simultaineously
val = diffs[0] # the value of diffs[0:upper]
while count > 0:
for i in range(upper, L):
if val == diffs[i]:
upper+=1
else:
break
count -= (upper)
val -= 1
# if count < 0 there are abs(count) values in diffs which must be val+1
# there are upper+count values if diffs which are val
res = abs(count)*(val+1)*(val+1) + (upper+count)*val*val
for i in range(upper, L): # square all values remaining in diffs which are < val
res += diffs[i]*diffs[i]
return res
|
minimum-sum-of-squared-difference
|
Python 3 SIMPLE with comments
|
manuel_lemos
| 0
| 32
|
minimum sum of squared difference
| 2,333
| 0.255
|
Medium
| 32,068
|
https://leetcode.com/problems/minimum-sum-of-squared-difference/discuss/2260284/Python-3Heap%2BCounter
|
class Solution:
def minSumSquareDiff(self, nums1: List[int], nums2: List[int], k1: int, k2: int) -> int:
nums = [abs(a - b) for a, b in zip(nums1, nums2) if a != b]
if k1 + k2 >= sum(nums): return 0
cnt = Counter(nums)
q = []
for k in cnt:
heappush(q, -k)
tot = sum(pow(x, 2) for x in nums)
k = k1 + k2
# ops on largest diff
while k > 0 and q:
cur = -heappop(q)
diff = cur + q[0] if q else cur
# reduce current diff to next smaller diff
if diff * cnt[cur] <= k:
k -= diff * cnt[cur]
cnt[-q[0]] += cnt[cur]
tot += (pow(-q[0], 2) - pow(cur, 2)) * cnt[cur]
# apply all remaining ops
else:
a, b = divmod(k, cnt[cur])
tot += (pow(cur - a - 1, 2) * b + pow(cur - a, 2) * (cnt[cur] - b)) - pow(cur, 2) * cnt[cur]
k = 0
return tot
|
minimum-sum-of-squared-difference
|
[Python 3]Heap+Counter
|
chestnut890123
| 0
| 36
|
minimum sum of squared difference
| 2,333
| 0.255
|
Medium
| 32,069
|
https://leetcode.com/problems/subarray-with-elements-greater-than-varying-threshold/discuss/2260689/Python3.-oror-Stack-9-lines-oror-TM-%3A-986-ms28-MB
|
class Solution:
def validSubarraySize(self, nums: List[int], threshold: int) -> int:
# Stack elements are the array's indices idx, and montonic with respect to nums[idx].
# When the index of the nearest smaller value to nums[idx] comes to the top of the
# stack, we check whether the threshold criterion is satisfied. If so, we are done.
# If not, we continue. Return -1 if we reach the end of nums without a winner.
nums.append(0)
stack = deque()
for idx in range(len(nums)):
while stack and nums[idx] <= nums[stack[-1]]:
n = nums[stack.pop()] # n is the next smaller value for nums[idx]
k = idx if not stack else idx - stack[-1] -1
if n > threshold //k: return k # threshold criterion. if n passes, all
# elements of the interval pass
stack.append(idx)
return -1
|
subarray-with-elements-greater-than-varying-threshold
|
Python3. || Stack, 9 lines || T/M : 986 ms/28 MB
|
warrenruud
| 7
| 101
|
subarray with elements greater than varying threshold
| 2,334
| 0.404
|
Hard
| 32,070
|
https://leetcode.com/problems/subarray-with-elements-greater-than-varying-threshold/discuss/2270096/Python3-monotonic-stack
|
class Solution:
def validSubarraySize(self, nums: List[int], threshold: int) -> int:
stack = []
for hi, x in enumerate(nums + [0]):
while stack and stack[-1][1] > x:
val = stack.pop()[1]
lo = stack[-1][0] if stack else -1
if val > threshold // (hi - lo - 1): return hi - lo - 1
stack.append((hi, x))
return -1
|
subarray-with-elements-greater-than-varying-threshold
|
[Python3] monotonic stack
|
ye15
| 1
| 43
|
subarray with elements greater than varying threshold
| 2,334
| 0.404
|
Hard
| 32,071
|
https://leetcode.com/problems/subarray-with-elements-greater-than-varying-threshold/discuss/2260267/Python-3Hint-solution
|
class Solution:
def validSubarraySize(self, nums: List[int], t: int) -> int:
n = len(nums)
if t / n >= max(nums):
return -1
left = list(range(n))
right = list(range(n))
# leftmost boundary for the subarray for each index
stack = []
for i in range(n):
while stack and nums[stack[-1]] >= nums[i]:
left[i] = left[stack.pop()]
stack.append(i)
# rightmost boundary for the subarray for each index
stack = []
for i in reversed(range(n)):
while stack and nums[stack[-1]] >= nums[i]:
right[i] = right[stack.pop()]
stack.append(i)
# get size of subarray and if eligible then output
for i in range(n):
size = right[i] - left[i] + 1
if nums[i] > t / size:
return size
return -1
|
subarray-with-elements-greater-than-varying-threshold
|
[Python 3]Hint solution
|
chestnut890123
| 1
| 55
|
subarray with elements greater than varying threshold
| 2,334
| 0.404
|
Hard
| 32,072
|
https://leetcode.com/problems/subarray-with-elements-greater-than-varying-threshold/discuss/2346909/Python-3-Monotonic-stack
|
class Solution:
def validSubarraySize(self, nums: List[int], threshold: int) -> int:
l,n=[],len(nums)
stack=[]
for i,x in enumerate(nums):
while stack and nums[stack[-1]]>=x:
stack.pop()
if stack:
l.append(stack[-1])
else:
l.append(-1)
stack.append(i)
stack=[]
for i in range(n-1,-1,-1):
while stack and nums[stack[-1]]>=nums[i]:
stack.pop()
if stack:
k=stack[-1]-l[i]-1
else:
k=n-l[i]-1
if k*nums[i]>threshold:
return k
stack.append(i)
return -1
|
subarray-with-elements-greater-than-varying-threshold
|
[Python 3] Monotonic stack
|
gabhay
| 0
| 65
|
subarray with elements greater than varying threshold
| 2,334
| 0.404
|
Hard
| 32,073
|
https://leetcode.com/problems/subarray-with-elements-greater-than-varying-threshold/discuss/2328931/Short-Python3-implementation-in-linear-time-faster-than-83
|
class Solution:
def validSubarraySize(self, nums: List[int], threshold: int) -> int:
nums.append(0)
stack = [(0, -1)]
for i, v in enumerate(nums):
while len(stack) > 1 and v <= stack[-1][0]:
if stack[-1][0] > threshold / (i - 1 - stack[-2][1]):
return i - 1 - stack[-2][1]
stack.pop()
stack.append((v, i))
return -1
|
subarray-with-elements-greater-than-varying-threshold
|
Short Python3 implementation in linear time, faster than 83%
|
metaphysicalist
| 0
| 41
|
subarray with elements greater than varying threshold
| 2,334
| 0.404
|
Hard
| 32,074
|
https://leetcode.com/problems/minimum-amount-of-time-to-fill-cups/discuss/2262041/Python-or-Straightforward-MaxHeap-Solution
|
class Solution:
def fillCups(self, amount: List[int]) -> int:
pq = [-q for q in amount if q != 0]
heapq.heapify(pq)
ret = 0
while len(pq) > 1:
first = heapq.heappop(pq)
second = heapq.heappop(pq)
first += 1
second += 1
ret += 1
if first:
heapq.heappush(pq, first)
if second:
heapq.heappush(pq, second)
if pq:
return ret - pq[0]
else:
return ret
|
minimum-amount-of-time-to-fill-cups
|
Python | Straightforward MaxHeap Solution
|
lukefall425
| 7
| 563
|
minimum amount of time to fill cups
| 2,335
| 0.555
|
Easy
| 32,075
|
https://leetcode.com/problems/minimum-amount-of-time-to-fill-cups/discuss/2265447/Python3-oror-one-line-wexplanation-oror-TM%3A-41ms-13.5-MB
|
class Solution:
# Because only one of any type can be filled per second,
# the min cannot be less than the max(amount)-- see Ex 1.
# The min also cannot be less than ceil(sum(amount)/2)--see Ex 2.
# The min cannot be greater than both of these two
# quantities, so... tada
def fillCups(self, amount: List[int]) -> int:
return max(max(amount), ceil(sum(amount)/2))
|
minimum-amount-of-time-to-fill-cups
|
Python3 || one line w/explanation || T/M: 41ms/ 13.5 MB
|
warrenruud
| 4
| 116
|
minimum amount of time to fill cups
| 2,335
| 0.555
|
Easy
| 32,076
|
https://leetcode.com/problems/minimum-amount-of-time-to-fill-cups/discuss/2262018/Memoization-or-Python-3
|
class Solution:
def fillCups(self, amount: List[int]) -> int:
mp={}
def solve(x1,x2,x3):
if x1<=0 or x2<=0 or x3<=0:
return max(x1,x2,x3)
if (x1,x2,x3) in mp :
return mp[(x1,x2,x3)]
mp[(x1,x2,x3)]=1+min(solve(x1-1,x2-1,x3),solve(x1,x2-1,x3-1),solve(x1-1,x2,x3-1))
return mp[(x1,x2,x3)]
return solve(amount[0],amount[1],amount[2])
|
minimum-amount-of-time-to-fill-cups
|
Memoization | Python 3
|
chaurasiya_g
| 1
| 30
|
minimum amount of time to fill cups
| 2,335
| 0.555
|
Easy
| 32,077
|
https://leetcode.com/problems/minimum-amount-of-time-to-fill-cups/discuss/2261742/Python3-solution-using-sort
|
class Solution:
def fillCups(self, a: List[int]) -> int:
result = 0
while sum(a)!=0:
result+=1
a = sorted(a, reverse=True)
if a[0] > 0:
a[0] -= 1
if a[1] > 0:
a[1] -=1
elif a[2] > 0:
a[2] -= 1
return result
|
minimum-amount-of-time-to-fill-cups
|
📌 Python3 solution using sort
|
Dark_wolf_jss
| 1
| 20
|
minimum amount of time to fill cups
| 2,335
| 0.555
|
Easy
| 32,078
|
https://leetcode.com/problems/minimum-amount-of-time-to-fill-cups/discuss/2261380/Python3-priority-queue
|
class Solution:
def fillCups(self, amount: List[int]) -> int:
pq = [-x for x in amount]
heapify(pq)
ans = 0
while pq[0]:
x = heappop(pq)
if pq[0]: heapreplace(pq, pq[0]+1)
heappush(pq, x+1)
ans += 1
return ans
|
minimum-amount-of-time-to-fill-cups
|
[Python3] priority queue
|
ye15
| 1
| 27
|
minimum amount of time to fill cups
| 2,335
| 0.555
|
Easy
| 32,079
|
https://leetcode.com/problems/minimum-amount-of-time-to-fill-cups/discuss/2261380/Python3-priority-queue
|
class Solution:
def fillCups(self, amount: List[int]) -> int:
return max(max(amount), (sum(amount)+1)//2)
|
minimum-amount-of-time-to-fill-cups
|
[Python3] priority queue
|
ye15
| 1
| 27
|
minimum amount of time to fill cups
| 2,335
| 0.555
|
Easy
| 32,080
|
https://leetcode.com/problems/minimum-amount-of-time-to-fill-cups/discuss/2797634/Easy-Task-Scheduler-using-Heap-in-Python
|
class Solution:
def fillCups(self, amount: List[int]) -> int:
maxHeap =[]
for val in amount:
if val:
maxHeap.append(-val)
heapq.heapify(maxHeap)
count = 0
val1 = -1
val2= -1
while maxHeap:
val1 = heapq.heappop(maxHeap)
if maxHeap:
val2 = heapq.heappop(maxHeap)
if (val1 + 1):
heapq.heappush(maxHeap,val1+1)
if (val2 + 1):
heapq.heappush(maxHeap,val2+1)
count +=1
return count
|
minimum-amount-of-time-to-fill-cups
|
Easy Task Scheduler using Heap in Python
|
DebojitBiswas
| 0
| 1
|
minimum amount of time to fill cups
| 2,335
| 0.555
|
Easy
| 32,081
|
https://leetcode.com/problems/minimum-amount-of-time-to-fill-cups/discuss/2393567/Easy-and-Clear-Python3-Solution
|
class Solution:
def fillCups(self, amount: List[int]) -> int:
amount.sort()
res=0
while amount[1]>0:
x=amount[1]-amount[0]
if x<1:
x=1
amount[2]-=x
amount[1]-=x
amount.sort()
res+=1=x
res+=amount[2]
return res
|
minimum-amount-of-time-to-fill-cups
|
Easy & Clear Python3 Solution
|
moazmar
| 0
| 78
|
minimum amount of time to fill cups
| 2,335
| 0.555
|
Easy
| 32,082
|
https://leetcode.com/problems/minimum-amount-of-time-to-fill-cups/discuss/2266989/Simulate-the-selection-to-pickup-the-bigger-two
|
class Solution:
def fillCups(self, amount: List[int]) -> int:
count = 0
amount = list(filter(lambda e: e > 0, sorted(amount, reverse=True)))
while len(amount) == 3:
count += 1
# Always pickup the bigger two to do deduction
amount[0] -= 1
amount[1] -= 1
amount = list(filter(lambda e: e > 0, sorted(amount, reverse=True)))
# It is simple and straight forward to deal with only 0/1/2 number left.
if len(amount) == 1: count += amount[0]
elif len(amount) == 2: count += max(amount)
return count
|
minimum-amount-of-time-to-fill-cups
|
Simulate the selection to pickup the bigger two
|
puremonkey2001
| 0
| 4
|
minimum amount of time to fill cups
| 2,335
| 0.555
|
Easy
| 32,083
|
https://leetcode.com/problems/minimum-amount-of-time-to-fill-cups/discuss/2264552/Python-smart-solution
|
class Solution:
def fillCups(self, amount: List[int]) -> int:
amount.sort()
to_add_to_max = max(amount[0] - (amount[2] - amount[1]), 0)
return amount[2] + (to_add_to_max + 1) // 2
|
minimum-amount-of-time-to-fill-cups
|
Python, smart solution
|
blue_sky5
| 0
| 31
|
minimum amount of time to fill cups
| 2,335
| 0.555
|
Easy
| 32,084
|
https://leetcode.com/problems/minimum-amount-of-time-to-fill-cups/discuss/2264318/Python3-Simple-Solution
|
class Solution:
def fillCups(self, amount: List[int]) -> int:
counter = 0
while max(amount) > 0 :
amount[amount.index(sorted(amount)[-2])] -= 1
amount[amount.index(sorted(amount)[-1])] -= 1
counter += 1
return counter
|
minimum-amount-of-time-to-fill-cups
|
Python3 Simple Solution
|
jasoriasaksham01
| 0
| 21
|
minimum amount of time to fill cups
| 2,335
| 0.555
|
Easy
| 32,085
|
https://leetcode.com/problems/minimum-amount-of-time-to-fill-cups/discuss/2261671/Python-Greedy-Solution-by-Sort
|
class Solution:
def fillCups(self, amount: List[int]) -> int:
ans = 0
while True:
amount.sort(reverse=True)
if amount[0] > 0 and amount[1] > 0:
amount[0] -= 1
amount[1] -= 1
ans += 1
elif amount[0] > 0:
amount[0] -= 1
ans += 1
else:
break
return ans
|
minimum-amount-of-time-to-fill-cups
|
[Python] Greedy Solution by Sort
|
nightybear
| 0
| 15
|
minimum amount of time to fill cups
| 2,335
| 0.555
|
Easy
| 32,086
|
https://leetcode.com/problems/minimum-amount-of-time-to-fill-cups/discuss/2261651/Priority-Queue-Heap-Python-Solution
|
class Solution:
def fillCups(self, am: List[int]) -> int:
import heapq
arr = [-i for i in am]
heapq.heapify(arr)
res = 0
while arr:
ele = - heapq.heappop(arr)
if arr:
ele2 = - heapq.heappop(arr)
if ele == 0:
return res
if ele2 == 0:
res += ele
return res
else:
res += 1
heapq.heappush(arr, - 1 * (ele - 1))
heapq.heappush(arr, - 1 * (ele2 - 1))
return res
|
minimum-amount-of-time-to-fill-cups
|
Priority Queue / Heap - Python Solution
|
codingteam225
| 0
| 20
|
minimum amount of time to fill cups
| 2,335
| 0.555
|
Easy
| 32,087
|
https://leetcode.com/problems/minimum-amount-of-time-to-fill-cups/discuss/2261604/Python-or-Sort-%2B-Any-or-7-lines
|
class Solution:
def fillCups(self, amount: List[int]) -> int:
ans = 0
while any(amount):
amount.sort()
amount[2] -= 1
amount[1] -= amount[1] > 0
ans += 1
return ans
|
minimum-amount-of-time-to-fill-cups
|
Python | Sort + Any | 7 lines
|
leeteatsleep
| 0
| 18
|
minimum amount of time to fill cups
| 2,335
| 0.555
|
Easy
| 32,088
|
https://leetcode.com/problems/minimum-amount-of-time-to-fill-cups/discuss/2261482/Python-Optimized-Solution-or-Mathematics-logic-or-Best-time-complexity-or
|
class Solution:
def fillCups(self, amount: List[int]) -> int:
amount.sort()
a = amount[-1]
b = amount[0] + amount[1]
if b>a:
if (b-a)%2==0:
return a + (b-a)//2
else:
return a + 1 + (b-a)//2
return a
|
minimum-amount-of-time-to-fill-cups
|
Python Optimized Solution | Mathematics logic | Best time complexity |
|
AkashHooda
| 0
| 24
|
minimum amount of time to fill cups
| 2,335
| 0.555
|
Easy
| 32,089
|
https://leetcode.com/problems/move-pieces-to-obtain-a-string/discuss/2274805/Python3-oror-10-lines-w-explanation-oror-TM%3A-96-44
|
class Solution:
# Criteria for a valid transormation:
# 1) The # of Ls, # of Rs , and # of _s must be equal between the two strings
#
# 2) The ordering of Ls and Rs in the two strings must be the same.
#
# 3) Ls can only move left and Rs can only move right, so each L in start
# cannot be to the left of its corresponding L in target, and each R cannot
# be to the right of its corresponding R in target.
def canChange(self, start: str, target: str) -> bool:
if (len(start) != len(target) or
start.count('_') != target.count('_')): return False # <-- Criterion 1
s = [(ch,i) for i, ch in enumerate(start ) if ch != '_']
t = [(ch,i) for i, ch in enumerate(target) if ch != '_']
for i in range(len(s)):
(sc, si), (tc,ti) = s[i], t[i]
if sc != tc: return False # <-- Criteria 1 & 2
if sc == 'L' and si < ti: return False # <-- Criterion 3
if sc == 'R' and si > ti: return False # <--/
return True # <-- It's a winner!
|
move-pieces-to-obtain-a-string
|
Python3 || 10 lines, w/ explanation || T/M: 96%/ 44%
|
warrenruud
| 3
| 127
|
move pieces to obtain a string
| 2,337
| 0.481
|
Medium
| 32,090
|
https://leetcode.com/problems/move-pieces-to-obtain-a-string/discuss/2261365/Python3-greedy
|
class Solution:
def canChange(self, s: str, e: str) -> bool:
dl = dr = 0
for ss, ee in zip(s, e):
if dl > 0 or dl < 0 and ss == 'R' or dr < 0 or dr > 0 and ss == 'L': return False
dl += int(ss == 'L') - int(ee == 'L')
dr += int(ss == 'R') - int(ee == 'R')
return dl == dr == 0
|
move-pieces-to-obtain-a-string
|
[Python3] greedy
|
ye15
| 2
| 52
|
move pieces to obtain a string
| 2,337
| 0.481
|
Medium
| 32,091
|
https://leetcode.com/problems/move-pieces-to-obtain-a-string/discuss/2287834/Python3-or-Easy-to-understand-solution-O(N)
|
class Solution:
def canChange(self, start: str, target: str) -> bool:
i = self.findNextChar(0, start) ## starting position of the valid chacters in "Start"
j = self.findNextChar(0, target) ## starting position of the valid characters in "target"
if i < 0 and j < 0:
return True
if i < 0 or j < 0:
return False
while True:
if start[i]!=target[j]: return False ## if they dont match return False
if start[i]=='R' and i > j: return False ## since we are at 'R", we can only move right. if i >j then there is no way we can get the result. Example. Start : _R Target=R_ in this case i=1 > j=0
if start[i] == 'L' and i < j: return False ## since we are at "L", we can only move left. if i<j then ther eis no way we can get the result. Example Start : L_ Target =_L . in this case i=0 < j=1
i = self.findNextChar(i+1,start) ## check for the next character ('R' or 'L') in the starting string string
j = self.findNextChar(j + 1, target) ## check for the next character ('R' or 'L') in the Target string
if i < 0 and j < 0: ## if both i and j are negative then we have explored all characters
return True
if i < 0 or j < 0: ## if this happens then return False.
return False
def findNextChar(self, startingPosition, String):
i = startingPosition
while i < len(String) and String[i] == '_':
i += 1
if i == len(String):
return -1
return i
|
move-pieces-to-obtain-a-string
|
Python3 | Easy to understand solution O(N)
|
mavericktopGun
| 1
| 56
|
move pieces to obtain a string
| 2,337
| 0.481
|
Medium
| 32,092
|
https://leetcode.com/problems/move-pieces-to-obtain-a-string/discuss/2287623/Check-indexes-of-letters-80-speed
|
class Solution:
letters = {"L", "R"}
def canChange(self, start: str, target: str) -> bool:
start_idx = [(c, i) for i, c in enumerate(start)
if c in Solution.letters]
target_idx = [(c, i) for i, c in enumerate(target)
if c in Solution.letters]
if len(start_idx) != len(target_idx):
return False
for (s, i), (t, j) in zip(start_idx, target_idx):
if s == t:
if s == "L" and i < j:
return False
elif s == "R" and i > j:
return False
else:
return False
return True
|
move-pieces-to-obtain-a-string
|
Check indexes of letters, 80% speed
|
EvgenySH
| 0
| 29
|
move pieces to obtain a string
| 2,337
| 0.481
|
Medium
| 32,093
|
https://leetcode.com/problems/move-pieces-to-obtain-a-string/discuss/2273260/python-3-or-simple-solution-or-O(n)O(1)
|
class Solution:
def canChange(self, start: str, target: str) -> bool:
def pieces(s):
for i, c in enumerate(s):
if c != '_':
yield i, c
yield -1, ' '
for (si, sc), (ti, tc) in zip(pieces(start), pieces(target)):
if sc != tc or (sc == 'L' and si < ti) or (sc == 'R' and si > ti):
return False
return True
|
move-pieces-to-obtain-a-string
|
python 3 | simple solution | O(n)/O(1)
|
dereky4
| 0
| 27
|
move pieces to obtain a string
| 2,337
| 0.481
|
Medium
| 32,094
|
https://leetcode.com/problems/move-pieces-to-obtain-a-string/discuss/2269450/Python-or-explained-solution
|
class Solution:
def canChange(self, start: str, target: str) -> bool:
'''
Time complexity O(N)
Space complexity O(N)
where N is the number of characters in start
'''
s = [(v, i) for i, v in enumerate(start) if v != '_']
t = [(v, i) for i, v in enumerate(target) if v != '_']
if len(s) != len(t): return False
for i in range(len(s)):
sv, si = s[i]; tv, ti = t[i]
if (sv != tv) or\
(sv == "L" and si < ti) or\
(sv == "R" and si > ti):
return False
return True
|
move-pieces-to-obtain-a-string
|
Python | explained solution
|
ilyas_01
| 0
| 19
|
move pieces to obtain a string
| 2,337
| 0.481
|
Medium
| 32,095
|
https://leetcode.com/problems/move-pieces-to-obtain-a-string/discuss/2264155/Python-3Binary-Search
|
class Solution:
def canChange(self, s: str, t: str) -> bool:
n = len(s)
if "".join(s.split('_')) != "".join(t.split('_')):
return False
loc = defaultdict(list)
for i in range(n):
if t[i] != '_':
loc[t[i]].append(i)
pl = pr = 0
for i in range(n):
if s[i] == 'L':
target = loc['L'][pl]
idx = bisect.bisect(loc['R'], i)
# with all right letters fixed, how far could current left go
far_left = loc['R'][idx - 1] if idx else -1
# target could not go left beyond far_left or go right to current index
if target <= far_left or target > i: return False
pl += 1
elif s[i] == 'R':
target = loc['R'][pr]
idx = bisect.bisect(loc['L'], i)
far_right = loc['L'][idx] if idx < len(loc['L']) else n
if target >= far_right or target < i: return False
pr += 1
return True
|
move-pieces-to-obtain-a-string
|
[Python 3]Binary Search
|
chestnut890123
| 0
| 17
|
move pieces to obtain a string
| 2,337
| 0.481
|
Medium
| 32,096
|
https://leetcode.com/problems/move-pieces-to-obtain-a-string/discuss/2263169/Simple-Python-O(n%2Bk)
|
class Solution:
def canChange(self, start: str, target: str) -> bool:
s1,s2="",""
l1,l2=[],[]
c1,c2=0,0
#Removing _ from the strings and storing number or _ before each elements
for i in range(len(start)):
if start[i]=="_":
c1+=1
else:
s1+=start[i]
l1.append(c1)
c1=0
if target[i]=="_":
c2+=1
else:
s2+=target[i]
l2.append(c2)
c2=0
#After removing _ from both the strings if they are not equal they can never be equal
if s1!=s2:
return False
#Traversing through string and finding if we can move 'L' and 'R' as needed in the target
for i in range(len(l1)):
if s1[i]=="L":
#If we need to move 'L' to right then return False
if l1[i]<l2[i]:
return False
#Add extra _ to the right element
if i!=len(l1)-1:
l1[i+1]+=l1[i]-l2[i]
elif s1[i]=="R":
#If we need to move 'R' to left then return False
if l1[i]>l2[i]:
return False
#Remove _ from the right element
if i!=len(l1)-1:
l1[i+1]-=l2[i]-l1[i]
return True
|
move-pieces-to-obtain-a-string
|
Simple Python O(n+k)
|
chinmay_06
| 0
| 8
|
move pieces to obtain a string
| 2,337
| 0.481
|
Medium
| 32,097
|
https://leetcode.com/problems/move-pieces-to-obtain-a-string/discuss/2261972/Python-Straightforward-Solution-with-Explanation
|
class Solution:
def canChange(self, start: str, target: str) -> bool:
# if the order of L, R of the start string is different from that of the target string, there's no way we can reform it to obtain the target string.
if start.replace('_', '') != target.replace('_', ''):
return False
n = len(start)
# given that the orders of L, R in both strings are the same, two remaining things we need to check to make sure we can obtain the target string are:
# 1. there is no L in target that occurs after its counterpart in the start string
# 2. there is no R in target that occurs before its counterpart in the start string
start_L = [i for i in range(n) if start[i] == 'L']
start_R = [i for i in range(n) if start[i] == 'R']
end_L = [i for i in range(n) if target[i] == 'L']
end_R = [i for i in range(n) if target[i] == 'R']
return not any(start_L[idx] < end_L[idx] for idx in range(len(start_L))) and not any(start_R[idx] > end_R[idx] for idx in range(len(start_R)))
``
|
move-pieces-to-obtain-a-string
|
Python Straightforward Solution with Explanation
|
lukefall425
| 0
| 24
|
move pieces to obtain a string
| 2,337
| 0.481
|
Medium
| 32,098
|
https://leetcode.com/problems/move-pieces-to-obtain-a-string/discuss/2261442/Python3-7-Lines
|
class Solution:
def canChange(self, start: str, target: str) -> bool:
start_idx, target_idx = [(c, idx) for idx, c in enumerate(start) if c != '_'], [(c, idx) for idx, c in enumerate(target) if c != '_']
if len(start_idx) != len(target_idx):
return False
for (s_val, s_idx), (t_val, t_idx) in zip(start_idx, target_idx):
if (s_val != t_val) or (s_val == 'L' and t_idx > s_idx) or (s_val == 'R' and t_idx < s_idx):
return False
return True
|
move-pieces-to-obtain-a-string
|
[Python3] 7 Lines
|
0xRoxas
| 0
| 31
|
move pieces to obtain a string
| 2,337
| 0.481
|
Medium
| 32,099
|
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.