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/check-if-word-equals-summation-of-two-words/discuss/1240165/Easy-python-solution(100)
|
class Solution:
def isSumEqual(self, firstWord: str, secondWord: str, targetWord: str) -> bool:
d1={'a':0,'b':1,'c':2,'d':3,'e':4,'f':5,'g':6,'h':7,'i':8,'j':9}
a=0
x=[0]
y=[0]
z=[0]
for i,v in enumerate(firstWord):
if d1[v]==0 and a==0:
continue
x.append(d1[v])
a=1
b=0
for i,v in enumerate(secondWord):
if d1[v]==0 and b==0:
continue
y.append(d1[v])
b=1
c=0
for i,v in enumerate(targetWord):
if d1[v]==0 and c==0:
continue
z.append(d1[v])
c=1
if a==1:
x=int("".join(map(str,x)))
else:
x=0
if b==1:
y=int("".join(map(str,y)))
else:
y=0
if c==1:
z=int("".join(map(str,z)))
else:
z=0
print(x,y,z)
if(x+y==z):
return True
return False
|
check-if-word-equals-summation-of-two-words
|
Easy python solution(100%)
|
Sneh17029
| 0
| 144
|
check if word equals summation of two words
| 1,880
| 0.738
|
Easy
| 26,700
|
https://leetcode.com/problems/maximum-value-after-insertion/discuss/1240010/Python-oror-simple-O(N)-iteration
|
class Solution:
def maxValue(self, n: str, x: int) -> str:
if int(n)>0:
ans = ""
flag = False
for i in range(len(n)):
if int(n[i])>=x:
ans += n[i]
else:
a = n[:i]
b = n[i:]
ans = a+str(x)+b
flag = True
break
if not flag:
ans += str(x)
else:
n = n[1:]
ans = ""
flag = False
for i in range(len(n)):
if int(n[i])<=x:
ans += n[i]
else:
a = n[:i]
b = n[i:]
ans = a+str(x)+b
flag = True
break
if not flag:
ans += str(x)
ans = "-"+ans
return ans
|
maximum-value-after-insertion
|
Python || simple O(N) iteration
|
harshhx
| 5
| 536
|
maximum value after insertion
| 1,881
| 0.366
|
Medium
| 26,701
|
https://leetcode.com/problems/maximum-value-after-insertion/discuss/1360286/One-pass-98-speed
|
class Solution:
def maxValue(self, n: str, x: int) -> str:
digit = str(x)
if n[0] == "-":
for i, d in enumerate(n[1:]):
if d > digit:
return f"{n[:i + 1]}{digit}{n[i + 1:]}"
else:
for i, d in enumerate(n):
if d < digit:
return f"{n[:i]}{digit}{n[i:]}"
return n + digit
|
maximum-value-after-insertion
|
One pass, 98% speed
|
EvgenySH
| 1
| 205
|
maximum value after insertion
| 1,881
| 0.366
|
Medium
| 26,702
|
https://leetcode.com/problems/maximum-value-after-insertion/discuss/1243122/Python
|
class Solution:
def maxValue(self, n: str, x: int) -> str:
for i,val in enumerate(n):
if n[0] != "-":
if int(val) < x:
return n[:i] + str(x) + n[i:]
else:
if val !='-' and int(val) > x:
return n[:i] + str(x) + n[i:]
return n + str(x)
|
maximum-value-after-insertion
|
Python
|
zoro_55
| 1
| 79
|
maximum value after insertion
| 1,881
| 0.366
|
Medium
| 26,703
|
https://leetcode.com/problems/maximum-value-after-insertion/discuss/1240141/Straightforward-Python3-O(n)-greedy-solution-with-brief-explanation
|
class Solution:
def maxValue(self, n: str, x: int) -> str:
# if positive, insert when x > leading digit
# --> ensure we can obtain benefit from the leftmost (indicates largest improvement)
# if negative, .. < leading digit
# --> similar logic
# special case: 0
if n == '0':
return str(x)
# positive
if n[0] != '-':
for i in range(len(n)):
if x > int(n[i]):
return n[:i] + str(x) + n[i:]
return n + str(x)
# negative
else:
for i in range(1, len(n)):
if x < int(n[i]):
return n[:i] + str(x) + n[i:]
return n + str(x)
|
maximum-value-after-insertion
|
Straightforward Python3 O(n) greedy solution with brief explanation
|
tkuo-tkuo
| 1
| 53
|
maximum value after insertion
| 1,881
| 0.366
|
Medium
| 26,704
|
https://leetcode.com/problems/maximum-value-after-insertion/discuss/2766146/Python-simple-solution-Beats-94.89
|
class Solution:
def maxValue(self, n: str, x: int) -> str:
if n[0] == '-':
for i in range(1,len(n)):
if int(n[i]) > x:
return n[:i] + str(x) + n[i:]
else: return n + str(x)
else:
if int(n[0]) < x:
return str(x) + n
for i in range(len(n)):
if int(n[i]) < x:
return n[:i] + str(x) + n[i:]
return n + str(x)
|
maximum-value-after-insertion
|
Python simple solution, Beats 94.89%
|
kizag
| 0
| 4
|
maximum value after insertion
| 1,881
| 0.366
|
Medium
| 26,705
|
https://leetcode.com/problems/maximum-value-after-insertion/discuss/1709292/Python3-accepted-solution
|
class Solution:
def maxValue(self, m: str, x: int) -> str:
if(m[0]=="-"):
m = m[1:]
flag = True
for i in range(len(m)):
if(m[i]>str(x)):
m = m[:i] + str(x) + m[i:]
flag = False
break
if(flag==True): m+=str(x)
return "-"+m
else:
flag = True
for i in range(len(m)):
if(m[i]<str(x)):
m = m[:i] + str(x) + m[i:]
flag = False
break
if(flag==True): m+=str(x)
return m
|
maximum-value-after-insertion
|
Python3 accepted solution
|
sreeleetcode19
| 0
| 65
|
maximum value after insertion
| 1,881
| 0.366
|
Medium
| 26,706
|
https://leetcode.com/problems/maximum-value-after-insertion/discuss/1597954/Python3%3A-60ms-faster-than-100-Python3-solutions
|
class Solution:
def maxValue(self, n: str, x: int) -> str:
x = str(x)
is_negative = n[0] == '-'
for index, digit in enumerate(n):
if is_negative and x < digit or not is_negative and x > digit:
return n[:index] + x + n[index:]
return n + x
|
maximum-value-after-insertion
|
Python3: 60ms, faster than 100% Python3 solutions
|
arian-sadeghi
| 0
| 131
|
maximum value after insertion
| 1,881
| 0.366
|
Medium
| 26,707
|
https://leetcode.com/problems/maximum-value-after-insertion/discuss/1320222/Python-3-or-Simple-code
|
class Solution:
def maxValue(self, n: str, x: int) -> str:
if int(n)>=0:
if x > int(n[0]):
return str(x)+n
else:
for i in range(1,len(n)):
if (x <= int(n[i-1])) and (x > int(n[i])):
return n[:i] + str(x) + n[i:]
else:
return n + str(x)
else:
if x < int(n[1]):
return "-"+str(x)+n[1:]
else:
for i in range(2,len(n)):
if (x >= int(n[i-1])) and (x < int(n[i])):
return n[:i] + str(x) + n[i:]
else:
return n + str(x)
|
maximum-value-after-insertion
|
Python 3 | Simple code
|
Shreevasatantry
| 0
| 101
|
maximum value after insertion
| 1,881
| 0.366
|
Medium
| 26,708
|
https://leetcode.com/problems/maximum-value-after-insertion/discuss/1293534/Python-simple-and-pythonic
|
class Solution:
def maxValue(self, n: str, x: int) -> str:
for index, value in enumerate(n):
if str(x) < value if n[0] == '-' else str(x) > value:
return n[:index] + str(x) + n[index:]
return n + str(x)
|
maximum-value-after-insertion
|
[Python] simple and pythonic
|
cruim
| 0
| 88
|
maximum value after insertion
| 1,881
| 0.366
|
Medium
| 26,709
|
https://leetcode.com/problems/maximum-value-after-insertion/discuss/1241650/PythonPython3-solution-with-explanation
|
class Solution:
def maxValue(self, n: str, x: int) -> str:
if n[0] == '-': # To process negative case elements
for i in range(1,len(n)): #traverse from 1 to len(n)
if x < int(n[i]): #if x is lesser the current n[i] value then return n by inserting the x in the index I have done it by using split index concept
return n[:i] + str(x) + n[i:]
return n + str(x) #if x is equal to or greater than the given num in the string then simply add to the last and return the value
else: # To process positive case elements
for i in range(len(n)): #traverse from 0 to len(n)
if x > int(n[i]):#if x is greater the current n[i] value then return n by inserting the x in the index I have done it by using split index concept
return n[:i] + str(x) + n[i:]
return n + str(x) #if x is equal to or lesser than the given num in the string then simply add to the last and return the value
|
maximum-value-after-insertion
|
Python/Python3 solution with explanation
|
prasanthksp1009
| 0
| 42
|
maximum value after insertion
| 1,881
| 0.366
|
Medium
| 26,710
|
https://leetcode.com/problems/maximum-value-after-insertion/discuss/1239825/Python3-greedy
|
class Solution:
def maxValue(self, n: str, x: int) -> str:
x = str(x)
if n[0] == "-":
for i in range(1, len(n)):
if x < n[i]: return n[:i] + x + n[i:]
else:
for i in range(0, len(n)):
if x > n[i]: return n[:i] + x + n[i:]
return n + x
|
maximum-value-after-insertion
|
[Python3] greedy
|
ye15
| 0
| 31
|
maximum value after insertion
| 1,881
| 0.366
|
Medium
| 26,711
|
https://leetcode.com/problems/process-tasks-using-servers/discuss/1240147/Python-oror-Heap-oror-O(n%2Bmlogn)-oror-easy-and-well-explained
|
class Solution:
def assignTasks(self, servers: List[int], tasks: List[int]) -> List[int]:
# sort the servers in order of weight, keeping index
server_avail = [(w,i) for i,w in enumerate(servers)]
heapify(server_avail)
tasks_in_progress = []
res = []
st=0
for j,task in enumerate(tasks):
#starting time of task
st = max(st,j)
# if any server is not free then we can take start-time equal to end-time of task
if not server_avail:
st = tasks_in_progress[0][0]
# pop the completed task's server and push inside the server avail
while tasks_in_progress and tasks_in_progress[0][0]<=st:
heapq.heappush(server_avail,heappop(tasks_in_progress)[1])
# append index of used server in res
res.append(server_avail[0][1])
# push the first available server in "server_avail" heap to "tasks_in_progress" heap
heapq.heappush(tasks_in_progress,(st+task,heappop(server_avail)))
return res
|
process-tasks-using-servers
|
🐍 {Python} || Heap || O(n+mlogn) || easy and well-explained
|
abhi9Rai
| 5
| 227
|
process tasks using servers
| 1,882
| 0.396
|
Medium
| 26,712
|
https://leetcode.com/problems/process-tasks-using-servers/discuss/1239888/Python3-priority-queue
|
class Solution:
def assignTasks(self, servers: List[int], tasks: List[int]) -> List[int]:
busy = []
free = [(wt, i) for i, wt in enumerate(servers)]
heapify(free)
ans = []
for t, task in enumerate(tasks):
while busy and busy[0][0] == t:
_, wt, i = heappop(busy)
heappush(free, (wt, i))
if free: wt, i = heappop(free)
else: t, wt, i = heappop(busy)
ans.append(i)
heappush(busy, (t+task, wt, i))
return ans
|
process-tasks-using-servers
|
[Python3] priority queue
|
ye15
| 1
| 66
|
process tasks using servers
| 1,882
| 0.396
|
Medium
| 26,713
|
https://leetcode.com/problems/process-tasks-using-servers/discuss/2704277/Python-Two-Heaps-Solution-with-Explanation
|
class Solution:
def assignTasks(self, servers: List[int], tasks: List[int]) -> List[int]:
ns = len(servers)
nt = len(tasks)
free = [] # (weight, index, time), sort by weight
for i in range(ns):
heapq.heappush(free, (servers[i], i, 0))
busy = [] # (time, weight, index), sort by time
result = []
for j in range(nt):
# move finished server from busy to free
while len(busy)> 0 and busy[0][0] <= j:
time, weight, index = heapq.heappop(busy)
heapq.heappush(free, (weight, index, time))
# assign new task
if len(free) > 0:
weight, index, time = heapq.heappop(free)
else:
time, weight, index = heapq.heappop(busy)
result.append(index)
# why time = max(time, j)?
# case1:
# there are free servers, add time to the first free server
# e.g. j = 2, tasks[j] = 3,
# free[0] = (3, 0, 0) -> busy[0] = (5, 3, 0)
# case2:
# no free server, the first server in busy is still working, add time to the first busy server
# e.g. j = 2, tasks[j] = 3,
# busy[0] = (3, 3, 0), still working
# -> busy[0] = (6, 3, 0)
time = max(time, j)
# move assigned server from free to busy
heapq.heappush(busy, (time + tasks[j], weight, index))
return result
|
process-tasks-using-servers
|
[Python] Two Heaps Solution with Explanation
|
bbshark
| 0
| 21
|
process tasks using servers
| 1,882
| 0.396
|
Medium
| 26,714
|
https://leetcode.com/problems/process-tasks-using-servers/discuss/2699176/Clean-Fast-Python3-or-2-Heaps
|
class Solution:
def assignTasks(self, servers: List[int], tasks: List[int]) -> List[int]:
ans, avail, busy = [], [], []
for i, w in enumerate(servers):
avail.append([0, w, i])
heapq.heapify(avail)
for time, task in enumerate(tasks):
while busy and busy[0][0] <= time:
serv = heapq.heappop(busy)
serv[0] = 0
heapq.heappush(avail, serv)
assign = heapq.heappop(avail) if avail else heapq.heappop(busy)
ans.append(assign[2])
assign[0] = max(time, assign[0]) + task
heapq.heappush(busy, assign)
return ans
|
process-tasks-using-servers
|
Clean, Fast Python3 | 2 Heaps
|
ryangrayson
| 0
| 4
|
process tasks using servers
| 1,882
| 0.396
|
Medium
| 26,715
|
https://leetcode.com/problems/process-tasks-using-servers/discuss/2567193/Python-or-Two-Heaps-w-comments
|
class Solution:
def assignTasks(self, servers: List[int], tasks: List[int]) -> List[int]:
ans = []
freeServers = []
usedServers = []
# push all available severs into free server heap, smallest server weight on top
for idx, serverWeight in enumerate(servers):
heapq.heappush(freeServers, (serverWeight, idx))
# iterate through each task
for idx, taskTime in enumerate(tasks):
curTime = idx
# while a servers completion time is less than or equal to curTime, pop it and add to free
while usedServers and usedServers[0][0] <= curTime:
_, w, i = heapq.heappop(usedServers)
heapq.heappush(freeServers, (w, i))
# if there is a free server, use it
if freeServers:
weight, i = heapq.heappop(freeServers)
ans.append(i)
taskCompletion = curTime + taskTime
heapq.heappush(usedServers, (taskCompletion, weight, i))
else:
# if no free server, top most used server will be next free, so update completion time
tCompletion, weight, i = heapq.heappop(usedServers)
tCompletion += taskTime
heapq.heappush(usedServers, (tCompletion, weight, i))
ans.append(i)
return ans
|
process-tasks-using-servers
|
Python | Two Heaps w/ comments
|
Mark5013
| 0
| 59
|
process tasks using servers
| 1,882
| 0.396
|
Medium
| 26,716
|
https://leetcode.com/problems/process-tasks-using-servers/discuss/1679506/Python-91-faster-Two-heaps
|
class Solution:
def assignTasks(self, servers: List[int], tasks: List[int]) -> List[int]:
free = []
ans = []
busy = []
for i, wt in enumerate(servers):
heapq.heappush(free, (wt,i))
for t, task in enumerate(tasks):
f = t + task
while busy and busy[0][0]<=t:
_, wt, i = heapq.heappop(busy)
heapq.heappush(free, (wt, i))
if free:
s_wt, s_i = heapq.heappop(free)
ans.append(s_i)
heapq.heappush(busy, (f, s_wt, s_i))
else:
# if not free , get the next server which will become free,
# and add the task time to it and insert back
bt, s_wt, s_i = heapq.heappop(busy)
ans.append(s_i)
heapq.heappush(busy, (bt+task, s_wt, s_i))
return ans
|
process-tasks-using-servers
|
Python , 91% faster, Two heaps
|
user8266H
| 0
| 185
|
process tasks using servers
| 1,882
| 0.396
|
Medium
| 26,717
|
https://leetcode.com/problems/process-tasks-using-servers/discuss/1362015/Manipulate-two-heaps
|
class Solution:
def assignTasks(self, servers: List[int], tasks: List[int]) -> List[int]:
ans = [0] * len(tasks)
free_servers = []
busy_servers = []
for idx, weight in enumerate(servers):
heappush(free_servers, (weight, idx))
for sec, task_len in enumerate(tasks):
if busy_servers:
sec_free, weight, idx = heappop(busy_servers)
while sec_free <= sec:
heappush(free_servers, (weight, idx))
if busy_servers:
sec_free, weight, idx = heappop(busy_servers)
else:
break
if sec_free > sec:
heappush(busy_servers, (sec_free, weight, idx))
if free_servers:
weight, idx = heappop(free_servers)
ans[sec] = idx
heappush(busy_servers, (sec + task_len, weight, idx))
else:
sec_free, weight, idx = heappop(busy_servers)
ans[sec] = idx
heappush(busy_servers, (sec_free + task_len, weight, idx))
return ans
|
process-tasks-using-servers
|
Manipulate two heaps
|
EvgenySH
| 0
| 72
|
process tasks using servers
| 1,882
| 0.396
|
Medium
| 26,718
|
https://leetcode.com/problems/minimum-skips-to-arrive-at-meeting-on-time/discuss/1242138/Python3-top-down-dp
|
class Solution:
def minSkips(self, dist: List[int], speed: int, hoursBefore: int) -> int:
if sum(dist)/speed > hoursBefore: return -1 # impossible
@cache
def fn(i, k):
"""Return min time (in distance) of traveling first i roads with k skips."""
if k < 0: return inf # impossible
if i == 0: return 0
return min(ceil((fn(i-1, k) + dist[i-1])/speed) * speed, dist[i-1] + fn(i-1, k-1))
for k in range(len(dist)):
if fn(len(dist)-1, k) + dist[-1] <= hoursBefore*speed: return k
|
minimum-skips-to-arrive-at-meeting-on-time
|
[Python3] top-down dp
|
ye15
| 1
| 59
|
minimum skips to arrive at meeting on time
| 1,883
| 0.385
|
Hard
| 26,719
|
https://leetcode.com/problems/egg-drop-with-2-eggs-and-n-floors/discuss/1248069/Recursive-Iterative-Generic
|
class Solution:
@cache
def twoEggDrop(self, n: int) -> int:
return min((1 + max(i - 1, self.twoEggDrop(n - i)) for i in range (1, n)), default = 1)
|
egg-drop-with-2-eggs-and-n-floors
|
Recursive, Iterative, Generic
|
votrubac
| 194
| 11,600
|
egg drop with 2 eggs and n floors
| 1,884
| 0.703
|
Medium
| 26,720
|
https://leetcode.com/problems/egg-drop-with-2-eggs-and-n-floors/discuss/1247673/Python3-egg-dropping-problem
|
class Solution:
def twoEggDrop(self, n: int) -> int:
@cache
def fn(n, k):
"""Return min moves for n floors and k eggs."""
if k == 1: return n
if n == 0: return 0
ans = inf
for x in range(1, n+1):
ans = min(ans, 1 + max(fn(x-1, k-1), fn(n-x, k)))
return ans
return fn(n, 2)
|
egg-drop-with-2-eggs-and-n-floors
|
[Python3] egg dropping problem
|
ye15
| 4
| 229
|
egg drop with 2 eggs and n floors
| 1,884
| 0.703
|
Medium
| 26,721
|
https://leetcode.com/problems/egg-drop-with-2-eggs-and-n-floors/discuss/1247673/Python3-egg-dropping-problem
|
class Solution:
def twoEggDrop(self, n: int) -> int:
return ceil((sqrt(1 + 8*n)-1)/2)
|
egg-drop-with-2-eggs-and-n-floors
|
[Python3] egg dropping problem
|
ye15
| 4
| 229
|
egg drop with 2 eggs and n floors
| 1,884
| 0.703
|
Medium
| 26,722
|
https://leetcode.com/problems/egg-drop-with-2-eggs-and-n-floors/discuss/2845038/1-liner
|
class Solution:
def twoEggDrop(self, n: int) -> int:
return ceil(((8*n+1)**0.5-1)/2)
|
egg-drop-with-2-eggs-and-n-floors
|
1 liner
|
droj
| 0
| 1
|
egg drop with 2 eggs and n floors
| 1,884
| 0.703
|
Medium
| 26,723
|
https://leetcode.com/problems/egg-drop-with-2-eggs-and-n-floors/discuss/2844611/Greedy-O(1)-math-solution-python-simple-solution
|
class Solution:
def twoEggDrop(self, n: int) -> int:
# 100 -> 99 97 94 90 85 79 72 64 55 45 34 22 9 0
# 14 -> 13 11 8 4 0
# 6 -> 5 3 0
remain = n
cur = 1
ret = 0
while remain > 0:
remain -= cur
ret += 1
cur += 1
return ret
|
egg-drop-with-2-eggs-and-n-floors
|
Greedy / O(1) math solution / python simple solution
|
Lara_Craft
| 0
| 1
|
egg drop with 2 eggs and n floors
| 1,884
| 0.703
|
Medium
| 26,724
|
https://leetcode.com/problems/egg-drop-with-2-eggs-and-n-floors/discuss/2814364/Python-(Simple-Dynamic-Programming)
|
class Solution:
def twoEggDrop(self, n):
dp = [float("inf")]*(n+1)
dp[0] = 0
for i in range(1,n+1):
for j in range(1,i+1):
dp[i] = min(dp[i],max(dp[i-j]+1,j))
return dp[-1]
|
egg-drop-with-2-eggs-and-n-floors
|
Python (Simple Dynamic Programming)
|
rnotappl
| 0
| 4
|
egg drop with 2 eggs and n floors
| 1,884
| 0.703
|
Medium
| 26,725
|
https://leetcode.com/problems/egg-drop-with-2-eggs-and-n-floors/discuss/2579191/find-the-rule-and-evolve-to-O(1)
|
class Solution:
def twoEggDrop(self, n: int) -> int:
total = 0
i = 1
while total < n:
total += i
i += 1
return i-1
|
egg-drop-with-2-eggs-and-n-floors
|
find the rule and evolve to O(1)
|
FrankYJY
| 0
| 30
|
egg drop with 2 eggs and n floors
| 1,884
| 0.703
|
Medium
| 26,726
|
https://leetcode.com/problems/egg-drop-with-2-eggs-and-n-floors/discuss/2579191/find-the-rule-and-evolve-to-O(1)
|
class Solution:
def twoEggDrop(self, n: int) -> int:
return math.ceil(math.sqrt(2*n+1/4)-1/2)
|
egg-drop-with-2-eggs-and-n-floors
|
find the rule and evolve to O(1)
|
FrankYJY
| 0
| 30
|
egg drop with 2 eggs and n floors
| 1,884
| 0.703
|
Medium
| 26,727
|
https://leetcode.com/problems/egg-drop-with-2-eggs-and-n-floors/discuss/2579191/find-the-rule-and-evolve-to-O(1)
|
class Solution:
def twoEggDrop(self, n: int) -> int:
return math.ceil((-1 + math.sqrt(1+8*n))/2)
|
egg-drop-with-2-eggs-and-n-floors
|
find the rule and evolve to O(1)
|
FrankYJY
| 0
| 30
|
egg drop with 2 eggs and n floors
| 1,884
| 0.703
|
Medium
| 26,728
|
https://leetcode.com/problems/egg-drop-with-2-eggs-and-n-floors/discuss/2470569/Python-O(N)-5-line-95-time
|
class Solution:
def twoEggDrop(self, n: int) -> int:
#The pattern:
#strategy: 1 2 2 3 3 3 4 4 4 4 ...
#n = 1 2 3 4 5 6 7 8 9 10...
start,step = 1,1
while n > start:
step += 1
start += step
return step
|
egg-drop-with-2-eggs-and-n-floors
|
Python O(N) 5-line 95% time
|
honey_grapes
| 0
| 84
|
egg drop with 2 eggs and n floors
| 1,884
| 0.703
|
Medium
| 26,729
|
https://leetcode.com/problems/egg-drop-with-2-eggs-and-n-floors/discuss/2374592/Python3-Solution-with-using-dp
|
class Solution:
def solver(self, cache, cur_n):
if cache[cur_n] == 0:
for i in range(1, cur_n + 1):
if cache[cur_n] == 0:
cache[cur_n] = cur_n
# max() - because we are interested in the worst case
# + 1 - drop from cur floor
# drop egg -> egg is break => worst case : validate every floor with help second egg: i - 1 steps
# drom egg -> egg is not break => worst case: validate worst case for cur_n - i floors
val = max(i - 1, self.solver(cache, cur_n - i)) + 1
#print(i, "--->", cur_n, "--->", cache[cur_n], val)
cache[cur_n] = min(cache[cur_n], val)
return cache[cur_n]
def twoEggDrop(self, n: int) -> int:
cache = [0] * (n + 1)
return self.solver(cache, n)
|
egg-drop-with-2-eggs-and-n-floors
|
[Python3] Solution with using dp
|
maosipov11
| 0
| 67
|
egg drop with 2 eggs and n floors
| 1,884
| 0.703
|
Medium
| 26,730
|
https://leetcode.com/problems/egg-drop-with-2-eggs-and-n-floors/discuss/2095230/Python-Solution-oror-DP
|
class Solution:
def twoEggDrop(self, n: int) -> int:
e=2
dp=[[-1 for i in range(n+1)] for j in range(e+1)]
def solve(e,n):
if n==0 or n==1:
return n
if e==1:
return n
if dp[e][n]!=-1:
return dp[e][n]
m=float("inf")
ans=0
for k in range(1,n+1):
ans=max(solve(e-1,k-1),solve(e,n-k))
m=min(m,ans)
dp[e][n]=m+1
return m+1
return solve(e,n)
|
egg-drop-with-2-eggs-and-n-floors
|
Python Solution || DP
|
a_dityamishra
| 0
| 134
|
egg drop with 2 eggs and n floors
| 1,884
| 0.703
|
Medium
| 26,731
|
https://leetcode.com/problems/egg-drop-with-2-eggs-and-n-floors/discuss/2028412/Python3-A-very-straight-forward-solution
|
class Solution:
def twoEggDrop(self, n: int) -> int:
count = 1
minus = 1
while n > count:
n -= minus
count += 1
minus += 1
return count
|
egg-drop-with-2-eggs-and-n-floors
|
[Python3] A very straight forward solution
|
terrencetang
| 0
| 126
|
egg drop with 2 eggs and n floors
| 1,884
| 0.703
|
Medium
| 26,732
|
https://leetcode.com/problems/egg-drop-with-2-eggs-and-n-floors/discuss/1267644/Python3-simple-O(log(n))-with-comments-and-explanation
|
class Solution:
def twoEggDrop(self, n: int) -> int:
N = 0
res = 0
# find k = 1+2+3+...+i , where i is the maximum number that allows k <= n then return k
while res < n:
N += 1
res += N
return N
|
egg-drop-with-2-eggs-and-n-floors
|
Python3 simple O(log(n)) with comments and explanation
|
anonymousmk
| -2
| 397
|
egg drop with 2 eggs and n floors
| 1,884
| 0.703
|
Medium
| 26,733
|
https://leetcode.com/problems/determine-whether-matrix-can-be-obtained-by-rotation/discuss/1253880/Python3-rotate-matrix
|
class Solution:
def findRotation(self, mat: List[List[int]], target: List[List[int]]) -> bool:
for _ in range(4):
if mat == target: return True
mat = [list(x) for x in zip(*mat[::-1])]
return False
|
determine-whether-matrix-can-be-obtained-by-rotation
|
[Python3] rotate matrix
|
ye15
| 86
| 4,800
|
determine whether matrix can be obtained by rotation
| 1,886
| 0.554
|
Easy
| 26,734
|
https://leetcode.com/problems/determine-whether-matrix-can-be-obtained-by-rotation/discuss/1266035/Python-Very-detailed-explanation-of-one-liner-solution-(for-python-beginners)
|
class Solution:
def findRotation(self, mat: List[List[int]], target: List[List[int]]) -> bool:
for _ in range(4):
if mat == target: return True
mat = [list(x) for x in zip(*mat[::-1])]
return False
|
determine-whether-matrix-can-be-obtained-by-rotation
|
Python - Very detailed explanation of one liner solution (for python beginners)
|
swatishukla
| 44
| 1,500
|
determine whether matrix can be obtained by rotation
| 1,886
| 0.554
|
Easy
| 26,735
|
https://leetcode.com/problems/determine-whether-matrix-can-be-obtained-by-rotation/discuss/1394662/python3-solution
|
class Solution:
def findRotation(self, mat: List[List[int]], target: List[List[int]]) -> bool:
for _ in range(4):
if mat == target:
return True
mat = [list(m[::-1]) for m in zip(*mat)]
return False
|
determine-whether-matrix-can-be-obtained-by-rotation
|
python3 solution
|
terrencetang
| 2
| 141
|
determine whether matrix can be obtained by rotation
| 1,886
| 0.554
|
Easy
| 26,736
|
https://leetcode.com/problems/determine-whether-matrix-can-be-obtained-by-rotation/discuss/2398365/Python-Transpose-and-Reflect
|
class Solution:
def findRotation(self, mat: List[List[int]], target: List[List[int]]) -> bool:
# check if matrix is already equal
if mat == target:
return True
# 90 degree rotation clockwise can be achieved by transposing and reflecting
# do this 3 times for degrees 90,180 and 270 and compare with original
for i in range(3):
self.transpose(mat)
self.reflect(mat)
if mat == target:
return True
return False
def transpose(self, matrix):
for i in range(len(matrix)):
for j in range(i + 1, len(matrix)):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
def reflect(self, matrix):
for i in range(len(matrix)):
matrix[i].reverse()
|
determine-whether-matrix-can-be-obtained-by-rotation
|
Python Transpose and Reflect
|
RaiyanC
| 1
| 98
|
determine whether matrix can be obtained by rotation
| 1,886
| 0.554
|
Easy
| 26,737
|
https://leetcode.com/problems/determine-whether-matrix-can-be-obtained-by-rotation/discuss/1255727/Python3-solution-by-rotating-maxtrix
|
class Solution:
def findRotation(self, mat: List[List[int]], target: List[List[int]]) -> bool:
for i in range(3):
if mat == target:
return True
mat = [list(x[::-1]) for x in zip(*mat)]
return mat == target
|
determine-whether-matrix-can-be-obtained-by-rotation
|
[Python3] solution by rotating maxtrix
|
iamlegend123
| 1
| 239
|
determine whether matrix can be obtained by rotation
| 1,886
| 0.554
|
Easy
| 26,738
|
https://leetcode.com/problems/determine-whether-matrix-can-be-obtained-by-rotation/discuss/2790684/Python-solution-(faster-than-99)
|
class Solution:
def rotate(self, mat: List[List[int]]) -> None:
mat[:] = [list(x)[::-1] for x in zip(*mat)]
def findRotation(self, mat: List[List[int]], target: List[List[int]]) -> bool:
if mat==target:
return True
for i in range(3):
self.rotate(target)
if(mat==target):
return True
return False
|
determine-whether-matrix-can-be-obtained-by-rotation
|
Python solution (faster than 99%)
|
denfedex
| 0
| 7
|
determine whether matrix can be obtained by rotation
| 1,886
| 0.554
|
Easy
| 26,739
|
https://leetcode.com/problems/determine-whether-matrix-can-be-obtained-by-rotation/discuss/2740516/Python-solution
|
class Solution:
def findRotation(self, mat: List[List[int]], target: List[List[int]]) -> bool:
def rotate(mat):
res = []
for i in range(len(mat)):
col = [x[i] for x in mat]
res.append([x for x in col[::-1]])
return res
def equal(mat1, mat2):
for i in range(len(mat1)):
for j in range(len(mat1)):
if mat1[i][j] != mat2[i][j]:
return False
return True
for i in range(4):
if equal(mat, target):
return True
mat = rotate(mat)
return False
|
determine-whether-matrix-can-be-obtained-by-rotation
|
Python solution
|
michaelniki
| 0
| 2
|
determine whether matrix can be obtained by rotation
| 1,886
| 0.554
|
Easy
| 26,740
|
https://leetcode.com/problems/determine-whether-matrix-can-be-obtained-by-rotation/discuss/2739010/Python-easy-solution.-Extended-version-of-rotate-image-problem
|
class Solution:
def findRotation(self, mat: List[List[int]], target: List[List[int]]) -> bool:
if mat ==target:
return True
def rotate(matrix):
l,r=0,len(matrix)-1
while l< r:
for i in range(r-l):
top,bottom=l,r
temp=matrix[top][l+i]
matrix[top][l+i]=matrix[bottom-i][l]
matrix[bottom-i][l]=matrix[bottom][r-i]
matrix[bottom][r-i]=matrix[top+i][r]
matrix[top+i][r]=temp
l+=1
r-=1
return matrix
for i in range(3):
if rotate(mat)==target:
return True
else:
continue
return False
|
determine-whether-matrix-can-be-obtained-by-rotation
|
Python easy solution. Extended version of rotate image problem
|
Navaneeth7
| 0
| 3
|
determine whether matrix can be obtained by rotation
| 1,886
| 0.554
|
Easy
| 26,741
|
https://leetcode.com/problems/determine-whether-matrix-can-be-obtained-by-rotation/discuss/2644969/Fast-and-easy
|
class Solution:
def findRotation(self, mat: List[List[int]], target: List[List[int]]) -> bool:
def rotate(matrix):
l,r=0,len(matrix)-1
while l< r:
for i in range(r-l):
top,bottom=l,r
temp=matrix[top][l+i]
matrix[top][l+i]=matrix[bottom-i][l]
matrix[bottom-i][l]=matrix[bottom][r-i]
matrix[bottom][r-i]=matrix[top+i][r]
matrix[top+i][r]=temp
l+=1
r-=1
return matrix
for i in range(4):
if rotate(mat)==target:
return True
else:
continue
return False
|
determine-whether-matrix-can-be-obtained-by-rotation
|
Fast and easy
|
HeyAnirudh
| 0
| 39
|
determine whether matrix can be obtained by rotation
| 1,886
| 0.554
|
Easy
| 26,742
|
https://leetcode.com/problems/determine-whether-matrix-can-be-obtained-by-rotation/discuss/2406192/Simple.py3
|
class Solution:
def findRotation(self, mat: List[List[int]], target: List[List[int]]) -> bool:
for i in range(4):
if self.same(mat, target):
# Checking each time⌚ whether the martrices are equal or not
return True
mat = self.rotate(mat)
# calling the 'same' function 3 times cuz after 4 rotation it'll be 360 rotation which will give us the default matrix
return False
def rotate(self, mat) -> [list[list]]:
"""This takes matrix as an input and rotates it."""
n = len(mat)
m = len(mat[0])
matb = [[0 for _ in range(n)] for _ in range(m)] # O(m * n)
for i in range(n): # O(m * n)
for j in range(m):
matb[j][n - i - 1] = mat[i][j]
return matb
def same(self, mat, target):
"""This function checks whether the given two matrices are same or not?"""
if len(mat) == len(target) and len(mat[0]) == len(target[0]):
for i in range(len(mat)):
for j in range(len(mat[0])):
if mat[i][j] != target[i][j]:
return False
return True
|
determine-whether-matrix-can-be-obtained-by-rotation
|
Simple.py3
|
aman-senpai
| 0
| 31
|
determine whether matrix can be obtained by rotation
| 1,886
| 0.554
|
Easy
| 26,743
|
https://leetcode.com/problems/determine-whether-matrix-can-be-obtained-by-rotation/discuss/2100186/Python-oror-Easy-Solution-oror-100
|
* class Solution:
def findRotation(self, mat: List[List[int]], target: List[List[int]]) -> bool:
def rote(mat):
n=len(mat)
for i in range(n):
for j in range(i, n,1):
temp=mat[i][j];
mat[i][j]=mat[j][i];
mat[j][i]=temp
start=0
end=n-1
while(start<end):
for i in range(n):
temp=mat[i][start];
mat[i][start]=mat[i][end]
mat[i][end]=temp
start+=1;
end-=1;
def check(mat):
n=len(mat);
for i in range(n):
for j in range(n):
if(mat[i][j]!=target[i][j]):
return False
return True
for i in range(4):
if(check(mat)):
return True
rote(mat)
return False
|
determine-whether-matrix-can-be-obtained-by-rotation
|
✅ Python || Easy Solution || 100%
|
keyxk
| 0
| 161
|
determine whether matrix can be obtained by rotation
| 1,886
| 0.554
|
Easy
| 26,744
|
https://leetcode.com/problems/determine-whether-matrix-can-be-obtained-by-rotation/discuss/2068518/Python-Solution-(Intuitive-Easy-to-understand)
|
class Solution:
def findRotation(self, mat: List[List[int]], target: List[List[int]]) -> bool:
if mat == target:
return True
# create a zero matrix identical to mat
ans = [[0 for _ in range(len(mat[0]))] for _ in range(len(mat))]
# If it has the target we can find in 3 rotations.
for _ in range(3):
# col
for j in range(len(mat[0])):
k = 0 # ans's column index
# row
for i in range(len(mat) - 1, -1, -1):
ans[j][k] = mat[i][j]
k += 1
# Check for equality
if ans == target:
return True
# Copy the contents of previously rotated array
for k in range(len(mat)):
for l in range(len(mat[0])):
mat[k][l] = ans[k][l]
return False
|
determine-whether-matrix-can-be-obtained-by-rotation
|
Python Solution (Intuitive, Easy to understand)
|
sirpiyugendarr
| 0
| 66
|
determine whether matrix can be obtained by rotation
| 1,886
| 0.554
|
Easy
| 26,745
|
https://leetcode.com/problems/determine-whether-matrix-can-be-obtained-by-rotation/discuss/1980880/Python-Short-python-indexing-based-solution-or-non-modifying-matrix
|
class Solution:
def findRotation(self, mat: List[List[int]], target: List[List[int]]) -> bool:
pos_rots = set([0, 1, 2, 3])
n = len(mat)
for i in range(n):
for j in range(n):
if mat[i][j] != target[i][j]:
pos_rots.discard(0)
if mat[i][j] != target[j][n - i - 1]:
pos_rots.discard(1)
if mat[i][j] != target[n - i - 1][n - j - 1]:
pos_rots.discard(2)
if mat[i][j] != target[n - j - 1][i]:
pos_rots.discard(3)
if not pos_rots:
return False
return True
|
determine-whether-matrix-can-be-obtained-by-rotation
|
[Python] Short python indexing based solution | non modifying matrix
|
user5382x
| 0
| 85
|
determine whether matrix can be obtained by rotation
| 1,886
| 0.554
|
Easy
| 26,746
|
https://leetcode.com/problems/determine-whether-matrix-can-be-obtained-by-rotation/discuss/1941592/Python-3
|
class Solution:
def findRotation(self, mat: list[list[int]],
target: list[list[int]]) -> bool:
rotate90 = [list(c)[::-1] for c in zip(*mat)]
rotate180 = [list(c) for c in zip(*mat)][::-1]
rotate270 = [r[::-1] for r in mat][::-1]
return any(r == target for r in (mat, rotate90, rotate180, rotate270))
|
determine-whether-matrix-can-be-obtained-by-rotation
|
Python 3
|
cerocha
| 0
| 49
|
determine whether matrix can be obtained by rotation
| 1,886
| 0.554
|
Easy
| 26,747
|
https://leetcode.com/problems/determine-whether-matrix-can-be-obtained-by-rotation/discuss/1871911/Python-dollarolution
|
class Solution:
def findRotation(self, mat: List[List[int]], target: List[List[int]]) -> bool:
for i in range(4):
mat = list(map(list, zip(*mat)))[::-1]
if mat == target:
return True
return False
|
determine-whether-matrix-can-be-obtained-by-rotation
|
Python $olution
|
AakRay
| 0
| 84
|
determine whether matrix can be obtained by rotation
| 1,886
| 0.554
|
Easy
| 26,748
|
https://leetcode.com/problems/determine-whether-matrix-can-be-obtained-by-rotation/discuss/1866082/Python-Rotate-and-compare-or-Easy-to-Understand
|
class Solution:
def findRotation(self, mat, target):
N = len(mat)
for _ in range(4):
mat = [[mat[N - 1 - c][r] for c in range(N)] for r in range(N)] # rotate
if mat == target: return True # compare
return False
|
determine-whether-matrix-can-be-obtained-by-rotation
|
Python Rotate and compare | Easy to Understand
|
steve-jokes
| 0
| 123
|
determine whether matrix can be obtained by rotation
| 1,886
| 0.554
|
Easy
| 26,749
|
https://leetcode.com/problems/determine-whether-matrix-can-be-obtained-by-rotation/discuss/1540015/Rotate-with-zip-96-speed
|
class Solution:
def findRotation(self, mat: List[List[int]], target: List[List[int]]) -> bool:
if mat == target:
return True
for _ in range(3):
mat = [list(col)[::-1] for col in zip(*mat)]
if mat == target:
return True
return False
|
determine-whether-matrix-can-be-obtained-by-rotation
|
Rotate with zip, 96% speed
|
EvgenySH
| 0
| 119
|
determine whether matrix can be obtained by rotation
| 1,886
| 0.554
|
Easy
| 26,750
|
https://leetcode.com/problems/determine-whether-matrix-can-be-obtained-by-rotation/discuss/1487367/Python3-easy-matrix-rotate-and-check
|
class Solution(object):
def findRotation(self, matrix, target):
"""
:type mat: List[List[int]]
:type target: List[List[int]]
:rtype: bool
"""
k = 0
while k < 4:
for i in range(len(matrix)):
for j in range(i):
matrix[i][j],matrix[j][i] = matrix[j][i],matrix[i][j]
n = len(matrix)
for i in range(n):
for j in range(n // 2):
matrix[i][j], matrix[i][-j - 1] = matrix[i][-j - 1], matrix[i][j]
if matrix==target:
return matrix==target
k+=1
return False
|
determine-whether-matrix-can-be-obtained-by-rotation
|
[Python3] easy matrix rotate and check
|
avigupta10
| 0
| 136
|
determine whether matrix can be obtained by rotation
| 1,886
| 0.554
|
Easy
| 26,751
|
https://leetcode.com/problems/determine-whether-matrix-can-be-obtained-by-rotation/discuss/1434204/Python-solution-with-formula-for-rotation-of-matrix-by-90-degrees
|
class Solution:
def findRotation(self, mat: List[List[int]], target: List[List[int]]) -> bool:
n = len(mat)
if n == 1:
if mat[0] == target[0]:
return True
elif mat[0] != target[0]:
return False
count = 0
while count <= 4: # check notes for explaination for this 4
for r in range(0,n):
for c in range(0,r):
mat[r][c],mat[c][r] = mat[c][r],mat[r][c]
for x in range(0,len(mat)):
mat[x] = mat[x][::-1]
if mat == target:
return True
count += 1
return False
|
determine-whether-matrix-can-be-obtained-by-rotation
|
Python solution with formula for rotation of matrix by 90 degrees
|
Saura_v
| 0
| 206
|
determine whether matrix can be obtained by rotation
| 1,886
| 0.554
|
Easy
| 26,752
|
https://leetcode.com/problems/determine-whether-matrix-can-be-obtained-by-rotation/discuss/1354474/Python-fast-and-simple
|
class Solution:
def findRotation(self, mat: List[List[int]], target: List[List[int]]) -> bool:
n = len(mat)
r0 = r1 = r2 = r3 = True
for i in range(n):
for j in range(n):
if r0 and target[i][j] != mat[i][j]:
r0 = False
if r1 and target[i][j] != mat[j][n - i - 1]:
r1 = False
if r2 and target[i][j] != mat[n - i - 1][n - j - 1]:
r2 = False
if r3 and target[i][j] != mat[n - j - 1][i]:
r3 = False
if r0 or r1 or r2 or r3:
continue
else:
return False
return True
```
|
determine-whether-matrix-can-be-obtained-by-rotation
|
Python, fast and simple
|
MihailP
| 0
| 207
|
determine whether matrix can be obtained by rotation
| 1,886
| 0.554
|
Easy
| 26,753
|
https://leetcode.com/problems/determine-whether-matrix-can-be-obtained-by-rotation/discuss/1254204/Python-Rotate-is-Flip-%2B-Fold!-(100-runtime)
|
class Solution:
def findRotation(self, mat: List[List[int]], target: List[List[int]]) -> bool:
if mat == target:
return True
for i in range(3):
self.flip(mat)
self.fold(mat)
if mat == target:
return True
return False
def flip(self, mat):
for i in range(len(mat) // 2):
mat[i], mat[len(mat) - 1 - i] = mat[len(mat) - 1 - i], mat[i]
def fold(self, mat):
for i in range(len(mat)):
for j in range(i + 1, len(mat[i])):
mat[i][j], mat[j][i] = mat[j][i], mat[i][j]
|
determine-whether-matrix-can-be-obtained-by-rotation
|
[Python] Rotate is Flip + Fold! (100% runtime)
|
LydLydLi
| 0
| 101
|
determine whether matrix can be obtained by rotation
| 1,886
| 0.554
|
Easy
| 26,754
|
https://leetcode.com/problems/determine-whether-matrix-can-be-obtained-by-rotation/discuss/1254181/rotate-and-compare-python
|
class Solution:
def findRotation(self, mat: List[List[int]], target: List[List[int]]) -> bool:
n=len(mat)
l,r=0,n-1
def rotate():
l,r=0,n-1
while l<r:
for i in range(r-l):
t=l
b=r
temp=mat[t][l+i]
mat[t][l+i]=mat[b-i][l]
mat[b-i][l]=mat[b][r-i]
mat[b][r-i]=mat[t+i][r]
mat[t+i][r]=temp
l+=1
r-=1
return mat
for i in range(4):
if target==rotate():
return True
return False
|
determine-whether-matrix-can-be-obtained-by-rotation
|
rotate & compare [python]
|
TarunAn
| 0
| 77
|
determine whether matrix can be obtained by rotation
| 1,886
| 0.554
|
Easy
| 26,755
|
https://leetcode.com/problems/determine-whether-matrix-can-be-obtained-by-rotation/discuss/1254033/Fast-%2B-Easy-%2B-Clean-Python
|
class Solution:
def findRotation(self, mat: List[List[int]], target: List[List[int]]) -> bool:
if mat == target:
return True
rots = 0
target = [tuple(x) for x in target]
while rots < 4:
if mat == target:
return True
mat = list(zip(*mat))[::-1]
rots += 1
return False
|
determine-whether-matrix-can-be-obtained-by-rotation
|
Fast + Easy + Clean Python
|
Pythagoras_the_3rd
| 0
| 122
|
determine whether matrix can be obtained by rotation
| 1,886
| 0.554
|
Easy
| 26,756
|
https://leetcode.com/problems/determine-whether-matrix-can-be-obtained-by-rotation/discuss/1254018/Python3-Simple-Zip-Function
|
class Solution:
def findRotation(self, mat: List[List[int]], target: List[List[int]]) -> bool:
if mat == target:
return True
new = [tuple(i) for i in target]
for _ in range(3):
mat[:] = zip(*mat[::-1])
if mat == new:
return True
return False
|
determine-whether-matrix-can-be-obtained-by-rotation
|
Python3 Simple Zip Function
|
omkar-nag
| 0
| 32
|
determine whether matrix can be obtained by rotation
| 1,886
| 0.554
|
Easy
| 26,757
|
https://leetcode.com/problems/determine-whether-matrix-can-be-obtained-by-rotation/discuss/1254002/Python-oror-Simple-approach-oror-rotating-3-times-oror
|
class Solution:
def findRotation(self, matrix: List[List[int]], target: List[List[int]]) -> bool:
def transpose(mat):
n=len(mat)
for i in range(n):
for j in range(i,n):
mat[i][j],mat[j][i]=mat[j][i],mat[i][j]
def reverse(mat):
n=len(mat)
for i in range(n):
for j in range(n//2+n%2):
mat[i][j],mat[i][n-j-1]=mat[i][n-j-1],mat[i][j]
if target==matrix:
return True
# Rotating 1st time
transpose(matrix)
reverse(matrix)
if target==matrix:
return True
# Rotating 2nd time
transpose(matrix)
reverse(matrix)
if target==matrix:
return True
# Rotating 3rd time
transpose(matrix)
reverse(matrix)
if target==matrix:
return True
return False
|
determine-whether-matrix-can-be-obtained-by-rotation
|
🐍 Python || Simple approach || rotating 3-times ||
|
abhi9Rai
| 0
| 126
|
determine whether matrix can be obtained by rotation
| 1,886
| 0.554
|
Easy
| 26,758
|
https://leetcode.com/problems/reduction-operations-to-make-the-array-elements-equal/discuss/1253889/Python3-greedy
|
class Solution:
def reductionOperations(self, nums: List[int]) -> int:
ans = val = 0
nums.sort()
for i in range(1, len(nums)):
if nums[i-1] < nums[i]: val += 1
ans += val
return ans
|
reduction-operations-to-make-the-array-elements-equal
|
[Python3] greedy
|
ye15
| 20
| 963
|
reduction operations to make the array elements equal
| 1,887
| 0.624
|
Medium
| 26,759
|
https://leetcode.com/problems/reduction-operations-to-make-the-array-elements-equal/discuss/1254446/python-solution
|
class Solution:
def reductionOperations(self, nums: List[int]) -> int:
cnt = 0
n = len(nums)
nums.sort()
i=1
prev = nums[0]
while i<n:
while i<n and nums[i]==prev:
i+=1
cnt = cnt + n-i
if i<n:
prev = nums[i]
return cnt
|
reduction-operations-to-make-the-array-elements-equal
|
python solution
|
rishabkhawad
| 1
| 48
|
reduction operations to make the array elements equal
| 1,887
| 0.624
|
Medium
| 26,760
|
https://leetcode.com/problems/reduction-operations-to-make-the-array-elements-equal/discuss/1255791/Python3-Two-Liners-and-Faster-than-100
|
class Solution:
def reductionOperations(self, nums: List[int]) -> int:
nums, n = sorted(nums), len(nums)
return sum([n-i if nums[i-1] != nums[i] else 0 for i in range(1, n)])
|
reduction-operations-to-make-the-array-elements-equal
|
[Python3] Two Liners and Faster than 100%
|
iamlegend123
| 0
| 55
|
reduction operations to make the array elements equal
| 1,887
| 0.624
|
Medium
| 26,761
|
https://leetcode.com/problems/reduction-operations-to-make-the-array-elements-equal/discuss/1255418/Python3-Fast-Easy-to-Understand-100
|
class Solution:
def reductionOperations(self, nums: List[int]) -> int:
nums= sorted(nums)
res, val = 0, 0
for i in range(1,len(nums)):
if nums[i] > nums[i-1] :
res +=1
val += res
return val
|
reduction-operations-to-make-the-array-elements-equal
|
Python3 - Fast - Easy to Understand - 100%
|
sp27
| 0
| 46
|
reduction operations to make the array elements equal
| 1,887
| 0.624
|
Medium
| 26,762
|
https://leetcode.com/problems/reduction-operations-to-make-the-array-elements-equal/discuss/1255357/Straightforward-Python3-6-line-dictionary-Solution-with-clear-explanation
|
class Solution:
def reductionOperations(self, nums: List[int]) -> int:
# Let's re-interpret this question
# --> for each value, we would like to sum-up values smaller than itself (without double count)
# e.g., [5, 1, 3]
# 5 is larger than 1, 3 --> 2
# 1 is the smallest --> 0
# 3 is larger than 1 --> 1
# ------------------------------------------------------------
# When we iterate value in the loop,
# we want to quickly know how many smaller values compared to certain given value
# --> we would sort array & build a dictionary for this
# ------------------------------------------------------------
# Time Complexity: O(n*log(n))
uniq_nums = list(set(nums))
uniq_sorted_nums = sorted(uniq_nums)
#i stands for index, but here it also presents number of unique values smaller than current value
d = {v: i for i, v in enumerate(uniq_sorted_nums)}
return sum([d[num] for num in nums])
|
reduction-operations-to-make-the-array-elements-equal
|
Straightforward Python3 6-line dictionary Solution with clear explanation
|
tkuo-tkuo
| 0
| 23
|
reduction operations to make the array elements equal
| 1,887
| 0.624
|
Medium
| 26,763
|
https://leetcode.com/problems/reduction-operations-to-make-the-array-elements-equal/discuss/1254417/Python-Why-my-set-logic-is-failing
|
class Solution:
def reductionOperations(self, nums: List[int]) -> int:
nums_set = list(set(nums)) #making set of nums a list again so that operations will be easier
ans = 0
for num in nums:
ans = ans+nums_set.index(num) # here we can get the number of changes for a count by the index of element in the set list.
return ans
|
reduction-operations-to-make-the-array-elements-equal
|
[Python] Why my set logic is failing?
|
arkumari2000
| 0
| 27
|
reduction operations to make the array elements equal
| 1,887
| 0.624
|
Medium
| 26,764
|
https://leetcode.com/problems/reduction-operations-to-make-the-array-elements-equal/discuss/1254328/python3-Sort-stack-and-reverse-traversal-sol-for-reference.
|
class Solution:
def reductionOperations(self, nums: List[int]) -> int:
nums.sort()
stack = [nums[-1]]
ans = 0
for x in range(len(nums)-2, -1, -1):
if nums[x] < stack[-1]:
ans += len(nums)-x-1
stack = [nums[x]]
elif nums[x] == stack[-1]:
stack.append(nums[x])
return ans
|
reduction-operations-to-make-the-array-elements-equal
|
[python3] Sort, stack and reverse traversal sol for reference.
|
vadhri_venkat
| 0
| 27
|
reduction operations to make the array elements equal
| 1,887
| 0.624
|
Medium
| 26,765
|
https://leetcode.com/problems/reduction-operations-to-make-the-array-elements-equal/discuss/1254207/Python-Super-Simple-Sort-and-Dictionary-Solution
|
class Solution:
def reductionOperations(self, nums: List[int]) -> int:
count = collections.Counter(nums)
nums.sort(reverse=True)
num_op = 0
for i in range(1, len(nums)):
if nums[i] != nums[i - 1]:
num_op += count[nums[i - 1]]
count[nums[i]] += count[nums[i - 1]]
count[nums[i - 1]] = 0
return num_op
|
reduction-operations-to-make-the-array-elements-equal
|
[Python] Super Simple Sort & Dictionary Solution
|
LydLydLi
| 0
| 28
|
reduction operations to make the array elements equal
| 1,887
| 0.624
|
Medium
| 26,766
|
https://leetcode.com/problems/reduction-operations-to-make-the-array-elements-equal/discuss/1254074/Sort-Dictionary-and-Count-Python-Faster-than-100
|
class Solution:
def reductionOperations(self, nums: List[int]) -> int:
reductions = {num: i for i, num in enumerate(sorted(set(nums)))}
return sum(reductions[num] for num in nums)
|
reduction-operations-to-make-the-array-elements-equal
|
Sort, Dictionary, and Count [Python] Faster than 100%
|
chowdmut
| 0
| 30
|
reduction operations to make the array elements equal
| 1,887
| 0.624
|
Medium
| 26,767
|
https://leetcode.com/problems/reduction-operations-to-make-the-array-elements-equal/discuss/1253952/96-faster-oror-Easy-to-understand-oror-Well-explained-oror
|
class Solution:
def reductionOperations(self, nums: List[int]) -> int:
dic=Counter(nums)
s=sorted(list(set(nums)))
if len(s)==1:
return 0
# defining 1-array dp (putting value according to the set of number)
v=[0]*len(s)
for i in range(len(s)):
v[i]=dic[s[i]]
for i in range(len(s)-2,-1,-1):
v[i]+=v[i+1]
return sum(v[1:])
|
reduction-operations-to-make-the-array-elements-equal
|
🐍 96% faster || Easy to understand || Well-explained ||
|
abhi9Rai
| 0
| 28
|
reduction operations to make the array elements equal
| 1,887
| 0.624
|
Medium
| 26,768
|
https://leetcode.com/problems/reduction-operations-to-make-the-array-elements-equal/discuss/1253905/Counter-%2B-Sort-or-Python
|
class Solution:
def reductionOperations(self, nums: List[int]) -> int:
f = Counter(nums)
s,ans=0,0
for i in sorted(f.keys(), reverse=True)[:-1]:
s += f[i]
ans += s
return ans
|
reduction-operations-to-make-the-array-elements-equal
|
Counter + Sort | Python
|
_naaz
| 0
| 39
|
reduction operations to make the array elements equal
| 1,887
| 0.624
|
Medium
| 26,769
|
https://leetcode.com/problems/reduction-operations-to-make-the-array-elements-equal/discuss/1362209/One-multi-line-with-groupby
|
class Solution:
def reductionOperations(self, nums: List[int]) -> int:
return sum(i * len(tuple(g)) for i, (_, g)
in enumerate(groupby(sorted(nums))))
|
reduction-operations-to-make-the-array-elements-equal
|
One multi-line with groupby
|
EvgenySH
| -1
| 36
|
reduction operations to make the array elements equal
| 1,887
| 0.624
|
Medium
| 26,770
|
https://leetcode.com/problems/minimum-number-of-flips-to-make-the-binary-string-alternating/discuss/1259837/Python-Simple-DP-(beats-99.52)
|
class Solution:
def minFlips(self, s: str) -> int:
prev = 0
start_1, start_0, start_1_odd, start_0_odd = 0,0,sys.maxsize,sys.maxsize
odd = len(s)%2
for val in s:
val = int(val)
if val == prev:
if odd:
start_0_odd = min(start_0_odd, start_1)
start_1_odd += 1
start_1 += 1
else:
if odd:
start_1_odd = min(start_1_odd, start_0)
start_0_odd += 1
start_0 += 1
prev = 1 - prev
return min([start_1, start_0, start_1_odd, start_0_odd])
|
minimum-number-of-flips-to-make-the-binary-string-alternating
|
[Python] Simple DP (beats 99.52%)
|
cloverpku
| 6
| 640
|
minimum number of flips to make the binary string alternating
| 1,888
| 0.381
|
Medium
| 26,771
|
https://leetcode.com/problems/minimum-number-of-flips-to-make-the-binary-string-alternating/discuss/1254138/Python-oror-easy-sliding-window-based-solutiion
|
class Solution(object):
def minFlips(self, s):
n=len(s) # we save this length as it is length of window
s+=s #we add this string because we can have any possibility like s[0]->s[n-1] or s[2]->s[n+1]meaning is that any continous variation with n length ...
ans=sys.maxint #assiging the answer max possible value as want our answer to be minimum so while comparing min answer will be given
ans1,ans2=0,0#two answer variables telling amount of changes we require to make it alternative
s1=""#dummy string like 10010101
s2=""#dummy string like 01010101
for i in range(len(s)):
if i%2==0:
s1+="1"
s2+="0"
else :
s1+="0"
s2+="1"
for i in range(len(s)):
if s[i]!=s1[i]:#if they dont match we want a change so ++1
ans1+=1
if s[i]!=s2[i]:
ans2+=1
if i>=n:
if s[i-n]!=s1[i-n]:#now we have gone ahead so removing the intial element but wait if that element needed a change we added ++ earlier but now he is not our part so why we have his ++ so to nullify its ++ we did a -- in string
ans1-=1
if s[i-n]!=s2[i-n]:
ans2-=1
if i>=n-1#when i reaches n-1 we have n length so we check answer first time and after that we always keep seeing if we get a less answer value and after the loop we get
ans=min([ans,ans1,ans2])
return ans
|
minimum-number-of-flips-to-make-the-binary-string-alternating
|
Python || easy sliding window based solutiion
|
aayush_chhabra
| 5
| 751
|
minimum number of flips to make the binary string alternating
| 1,888
| 0.381
|
Medium
| 26,772
|
https://leetcode.com/problems/minimum-number-of-flips-to-make-the-binary-string-alternating/discuss/1253911/Python3-circular-window
|
class Solution:
def minFlips(self, s: str) -> int:
s = deque(int(x) for x in s)
def fn(s, val=0):
"""Return min type-2 op to make s alternating."""
ans = int(s[0] != val)
for i in range(1, len(s)):
val ^= 1
if val != s[i]: ans += 1
return ans
x0, x1 = fn(s, 0), fn(s, 1)
ans = min(x0, x1)
for _ in range(len(s)):
if len(s)&1: x0, x1 = x1 + s[0] - (s[0]^1), x0 - s[0] + (s[0]^1)
else: x0, x1 = x1, x0
s.append(s.popleft())
ans = min(ans, x0, x1)
return ans
|
minimum-number-of-flips-to-make-the-binary-string-alternating
|
[Python3] circular window
|
ye15
| 3
| 486
|
minimum number of flips to make the binary string alternating
| 1,888
| 0.381
|
Medium
| 26,773
|
https://leetcode.com/problems/minimum-number-of-flips-to-make-the-binary-string-alternating/discuss/1253911/Python3-circular-window
|
class Solution:
def minFlips(self, s: str) -> int:
s = [int(x) for x in s]
ans = inf
x01 = x10 = 0
for i in range(2*len(s)):
x01 += s[i%len(s)]^i&1
x10 += s[i%len(s)]^(i+1)&1
if i+1 >= len(s):
if i >= len(s):
x01 -= s[i-len(s)]^(i-len(s))&1
x10 -= s[i-len(s)]^(i-len(s)+1)&1
ans = min(ans, x01, x10)
return ans
|
minimum-number-of-flips-to-make-the-binary-string-alternating
|
[Python3] circular window
|
ye15
| 3
| 486
|
minimum number of flips to make the binary string alternating
| 1,888
| 0.381
|
Medium
| 26,774
|
https://leetcode.com/problems/minimum-number-of-flips-to-make-the-binary-string-alternating/discuss/1256298/Easy-to-understand-O(n)-time-and-O(1)-space-solution
|
class Solution:
def minFlips(self, s: str) -> int:
ret = len(s)
onesOdd = 0
onesEven = 0
for i, digit in enumerate(s):
if i % 2 == 0 and digit == "1":
onesEven += 1
elif i % 2 == 1 and digit == "1":
onesOdd += 1
total = onesEven + onesOdd
for i in range(len(s)):
#target: 010101...
flips = onesEven + (len(s)//2 - onesOdd)
ret = min(ret, flips)
#target: 101010...
flips = (len(s)-len(s)//2 - onesEven) + onesOdd
ret = min(ret, flips)
if len(s) % 2 == 0:
break
else:
onesEven = onesOdd + (1 if s[i] == "1" else 0)
onesOdd = total - onesEven
return ret
|
minimum-number-of-flips-to-make-the-binary-string-alternating
|
Easy to understand O(n) time and O(1) space solution
|
azheanda
| 2
| 106
|
minimum number of flips to make the binary string alternating
| 1,888
| 0.381
|
Medium
| 26,775
|
https://leetcode.com/problems/minimum-number-of-flips-to-make-the-binary-string-alternating/discuss/1255338/Python-3-Counter-swap-for-odd-length-string-(384ms)
|
class Solution:
def minFlips(self, s: str) -> int:
odd, even = defaultdict(int), defaultdict(int)
for i in range(len(s)):
if i % 2:
odd[s[i]] += 1
else:
even[s[i]] += 1
ans = min(odd['1'] + even['0'], odd['0'] + even['1'])
# if even length string, odd and even position will not swap after each type-1 op
if len(s) % 2 == 0: return ans
# if odd length string:
# 1. even and odd will swap after type-1 op
# 2. index 0 will still be even after type-1 op
for i in range(len(s)):
even[s[i]] -= 1
odd[s[i]] += 1
even, odd = odd, even
ans = min(ans, min(odd['1'] + even['0'], odd['0'] + even['1']))
return ans
|
minimum-number-of-flips-to-make-the-binary-string-alternating
|
[Python 3] Counter swap for odd length string (384ms)
|
chestnut890123
| 1
| 90
|
minimum number of flips to make the binary string alternating
| 1,888
| 0.381
|
Medium
| 26,776
|
https://leetcode.com/problems/minimum-number-of-flips-to-make-the-binary-string-alternating/discuss/1254409/Python-oror-Easy-understanding-oror-well-Explained-oror-Sliding-window
|
class Solution:
def minFlips(self, s: str) -> int:
n=len(s)
cp=s+s
s1=""
s2=""
for i in range(len(cp)):
if i%2==0:
s1+='1'
s2+='0'
else:
s1+='0'
s2+='1'
res1=0
res2=0
res =10**6
for i in range(len(cp)):
if cp[i]!=s1[i]:
res1+=1
if cp[i]!=s2[i]:
res2+=1
if i>=n:
if cp[i-n]!=s1[i-n]:
res1-=1
if cp[i-n]!=s2[i-n]:
res2-=1
if i>=n-1:
res=min(res,res1,res2)
return res
|
minimum-number-of-flips-to-make-the-binary-string-alternating
|
🐍 Python || Easy-understanding || well-Explained || Sliding-window
|
abhi9Rai
| 1
| 193
|
minimum number of flips to make the binary string alternating
| 1,888
| 0.381
|
Medium
| 26,777
|
https://leetcode.com/problems/minimum-number-of-flips-to-make-the-binary-string-alternating/discuss/2830871/Python-(Simple-DP)
|
class Solution:
def minFlips(self, s):
result = n = len(s)
s1, s2 = "01"*n, "10"*n
if n%2 == 1:
s += s
r1 = r2 = 0
for i in range(len(s)):
if s1[i] == s[i]:
r1 += 1
if s2[i] == s[i]:
r2 += 1
if i>=n and s1[i-n] == s[i-n]:
r1 -= 1
if i>=n and s2[i-n] == s[i-n]:
r2 -= 1
if i>=n-1:
result = min(result,r1,r2)
return result
|
minimum-number-of-flips-to-make-the-binary-string-alternating
|
Python (Simple DP)
|
rnotappl
| 0
| 2
|
minimum number of flips to make the binary string alternating
| 1,888
| 0.381
|
Medium
| 26,778
|
https://leetcode.com/problems/minimum-number-of-flips-to-make-the-binary-string-alternating/discuss/2268441/Python-Sliding-window
|
class Solution:
def minFlips(self, s: str) -> int:
n = len(s)
s = s+s
fip1 = [('0' if i%2==0 else '1') for i in range(len(s))]
fip2 = [('1' if i%2==0 else '0') for i in range(len(s))]
i = 0
min1 = 0
min2 = 0
final = len(s)
for j in range(len(s)):
if fip1[j]!=(s[j]):
min1+=1
if fip2[j]!= (s[j]):
min2+=1
if (j-i+1) == n:
final = min(final,min1,min2)
if (s[i]) != fip1[i]:
min1-=1
if (s[i]) != fip2[i]:
min2-=1
i+=1
return final
|
minimum-number-of-flips-to-make-the-binary-string-alternating
|
Python Sliding window
|
Abhi_009
| 0
| 183
|
minimum number of flips to make the binary string alternating
| 1,888
| 0.381
|
Medium
| 26,779
|
https://leetcode.com/problems/minimum-space-wasted-from-packaging/discuss/1253918/Python3-prefix-sum-and-binary-search
|
class Solution:
def minWastedSpace(self, packages: List[int], boxes: List[List[int]]) -> int:
packages.sort()
prefix = [0]
for x in packages: prefix.append(prefix[-1] + x)
ans = inf
for box in boxes:
box.sort()
if packages[-1] <= box[-1]:
kk = val = 0
for x in box:
k = bisect_right(packages, x)
val += (k - kk) * x - (prefix[k] - prefix[kk])
kk = k
ans = min(ans, val)
return ans % 1_000_000_007 if ans < inf else -1
|
minimum-space-wasted-from-packaging
|
[Python3] prefix sum & binary search
|
ye15
| 5
| 330
|
minimum space wasted from packaging
| 1,889
| 0.307
|
Hard
| 26,780
|
https://leetcode.com/problems/minimum-space-wasted-from-packaging/discuss/1253918/Python3-prefix-sum-and-binary-search
|
class Solution:
def minWastedSpace(self, packages: List[int], boxes: List[List[int]]) -> int:
packages.sort()
ans = inf
for box in boxes:
box.sort()
if packages[-1] <= box[-1]:
kk = val = 0
for x in box:
k = bisect_right(packages, x)
val += (k - kk) * x
kk = k
ans = min(ans, val)
return (ans - sum(packages)) % 1_000_000_007 if ans < inf else -1
|
minimum-space-wasted-from-packaging
|
[Python3] prefix sum & binary search
|
ye15
| 5
| 330
|
minimum space wasted from packaging
| 1,889
| 0.307
|
Hard
| 26,781
|
https://leetcode.com/problems/minimum-space-wasted-from-packaging/discuss/1255321/Python-3-Binary-Search-%2B-Prefix-Sum-(1576-ms)
|
class Solution:
def minWastedSpace(self, packages: List[int], boxes: List[List[int]]) -> int:
# prefix sum to save time
acc = [0] + [*accumulate(packages)]
packages.sort()
ans = float('inf')
for box in boxes:
tmp = 0
# deal with smallest box first
box.sort()
# record number of packages already dealt with
start = 0
for b in box:
loc = bisect.bisect(packages, b)
if loc == 0: continue
tmp += b * (loc - start) - (acc[loc] - acc[start])
# all are packaged
if loc == len(packages):
ans = min(ans, tmp)
break
start = loc
return ans % (10 **9+7) if ans != float('inf') else -1
|
minimum-space-wasted-from-packaging
|
[Python 3] Binary Search + Prefix Sum (1576 ms)
|
chestnut890123
| 2
| 170
|
minimum space wasted from packaging
| 1,889
| 0.307
|
Hard
| 26,782
|
https://leetcode.com/problems/check-if-all-the-integers-in-a-range-are-covered/discuss/1444310/PYTHON3-Noob-Friendly-Easy-inuitive-naturally-occuring-solution
|
class Solution:
def isCovered(self, ranges: List[List[int]], left: int, right: int) -> bool:
ranges = sorted(ranges)
for s,e in ranges:
if s<=left<=e:
if s<=right<=e:
return True
else:
left=e+1
return False
|
check-if-all-the-integers-in-a-range-are-covered
|
PYTHON3- Noob Friendly Easy inuitive naturally occuring solution
|
mathur17021play
| 2
| 138
|
check if all the integers in a range are covered
| 1,893
| 0.508
|
Easy
| 26,783
|
https://leetcode.com/problems/check-if-all-the-integers-in-a-range-are-covered/discuss/1267375/Python3-brute-force
|
class Solution:
def isCovered(self, ranges: List[List[int]], left: int, right: int) -> bool:
covered = [0]*(right-left+1)
for st, ed in ranges:
for x in range(st, ed+1):
if left <= x <= right: covered[x - left] = 1
return all(covered)
|
check-if-all-the-integers-in-a-range-are-covered
|
[Python3] brute-force
|
ye15
| 2
| 208
|
check if all the integers in a range are covered
| 1,893
| 0.508
|
Easy
| 26,784
|
https://leetcode.com/problems/check-if-all-the-integers-in-a-range-are-covered/discuss/1267375/Python3-brute-force
|
class Solution:
def isCovered(self, ranges: List[List[int]], left: int, right: int) -> bool:
cover = [False] * 51
for start, end in ranges:
for x in range(start, end+1):
cover[x] = True
return all(cover[x] for x in range(left, right+1))
|
check-if-all-the-integers-in-a-range-are-covered
|
[Python3] brute-force
|
ye15
| 2
| 208
|
check if all the integers in a range are covered
| 1,893
| 0.508
|
Easy
| 26,785
|
https://leetcode.com/problems/check-if-all-the-integers-in-a-range-are-covered/discuss/1267375/Python3-brute-force
|
class Solution:
def isCovered(self, ranges: List[List[int]], left: int, right: int) -> bool:
vals = [0]*52
for x, y in ranges:
vals[x] += 1
vals[y+1] -= 1
prefix = 0
for i, x in enumerate(vals):
prefix += x
if left <= i <= right and prefix == 0: return False
return True
|
check-if-all-the-integers-in-a-range-are-covered
|
[Python3] brute-force
|
ye15
| 2
| 208
|
check if all the integers in a range are covered
| 1,893
| 0.508
|
Easy
| 26,786
|
https://leetcode.com/problems/check-if-all-the-integers-in-a-range-are-covered/discuss/1267375/Python3-brute-force
|
class Solution:
def isCovered(self, ranges: List[List[int]], left: int, right: int) -> bool:
merge = []
for start, end in sorted(ranges):
if merge and start <= merge[-1][1]+1:
merge[-1][1] = max(merge[-1][1], end)
else: merge.append([start, end])
return any(x <= left <= right <= y for x, y in merge)
|
check-if-all-the-integers-in-a-range-are-covered
|
[Python3] brute-force
|
ye15
| 2
| 208
|
check if all the integers in a range are covered
| 1,893
| 0.508
|
Easy
| 26,787
|
https://leetcode.com/problems/check-if-all-the-integers-in-a-range-are-covered/discuss/2485553/Python-simple-solution
|
class Solution:
def isCovered(self, ranges: List[List[int]], left: int, right: int) -> bool:
ans = 0
for i in range(left, right+1):
for x,y in ranges:
if i in [x for x in range(x,y+1)]:
ans += 1
break
return ans == right-left+1
|
check-if-all-the-integers-in-a-range-are-covered
|
Python simple solution
|
StikS32
| 1
| 120
|
check if all the integers in a range are covered
| 1,893
| 0.508
|
Easy
| 26,788
|
https://leetcode.com/problems/check-if-all-the-integers-in-a-range-are-covered/discuss/2330388/Python-Simplest-Solution-With-Explanation-or-Beg-to-adv-or-Prefix-sum
|
class Solution:
def isCovered(self, ranges: List[List[int]], left: int, right: int) -> bool:
count = 0 # taking a counter
for i in range(left, right + 1): # running loop till right+1, as right is also inclusive.
for l, r in ranges: # all the sub list will be sorted in the provided ranges.
if l <= i <= r: # so will check if left be in the provided ranges, if yes will increase the counter else we`ll go to the next range i.e 1 2, 3 4, 3 4, 5 6.
count += 1
break
return count == right - left + 1 # in first example it`ll be 4==4 -> True
|
check-if-all-the-integers-in-a-range-are-covered
|
Python Simplest Solution With Explanation | Beg to adv | Prefix sum
|
rlakshay14
| 1
| 108
|
check if all the integers in a range are covered
| 1,893
| 0.508
|
Easy
| 26,789
|
https://leetcode.com/problems/check-if-all-the-integers-in-a-range-are-covered/discuss/2150216/Python3-Faster-than-99.63
|
class Solution:
def isCovered(self, ranges: List[List[int]], left: int, right: int) -> bool:
cross_off_list = [i for i in range(left, right+1)]
for rnge in ranges:
for i in range(rnge[0], rnge[1]+1):
if i in cross_off_list:
cross_off_list.remove(i)
return True if len(cross_off_list) == 0 else False
|
check-if-all-the-integers-in-a-range-are-covered
|
✅✅✅ Python3 - Faster than 99.63% ✅✅✅
|
thesauravs
| 1
| 81
|
check if all the integers in a range are covered
| 1,893
| 0.508
|
Easy
| 26,790
|
https://leetcode.com/problems/check-if-all-the-integers-in-a-range-are-covered/discuss/1270801/Intuitive-approach-by-keeping-integers-in-set-for-searching
|
class Solution:
def isCovered(self, ranges: List[List[int]], left: int, right: int) -> bool:
int_set = set()
''' set to keep all integers in ranges'''
# 1) Add all intergers in int_set from ranges
for s, e in ranges:
int_set.update(list(range(s, e+1)))
# 2) Check if integers between left and right inclusive
# to be covered by int_set
for i in range(left, right+1):
if i not in int_set:
return False
return True
|
check-if-all-the-integers-in-a-range-are-covered
|
Intuitive approach by keeping integers in set for searching
|
puremonkey2001
| 1
| 74
|
check if all the integers in a range are covered
| 1,893
| 0.508
|
Easy
| 26,791
|
https://leetcode.com/problems/check-if-all-the-integers-in-a-range-are-covered/discuss/1267784/Python-Solution-(N2)
|
class Solution:
def isCovered(self, ranges: List[List[int]], left: int, right: int) -> bool:
for i in range(left, right + 1):
good = False
for start, end in ranges:
if start <= i <= end:
good = True
break
if not good:
return False
return True
|
check-if-all-the-integers-in-a-range-are-covered
|
Python Solution (N^2)
|
mariandanaila01
| 1
| 48
|
check if all the integers in a range are covered
| 1,893
| 0.508
|
Easy
| 26,792
|
https://leetcode.com/problems/check-if-all-the-integers-in-a-range-are-covered/discuss/2747886/Easy-and-Faster
|
class Solution:
def isCovered(self, ranges: List[List[int]], left: int, right: int) -> bool:
res=[False]*60
for i,j in ranges:
for x in range(i,j+1):
res[x]=True
for x in range(left,right+1):
if(not res[x]):
return False
return True
|
check-if-all-the-integers-in-a-range-are-covered
|
Easy and Faster
|
Raghunath_Reddy
| 0
| 9
|
check if all the integers in a range are covered
| 1,893
| 0.508
|
Easy
| 26,793
|
https://leetcode.com/problems/check-if-all-the-integers-in-a-range-are-covered/discuss/2627259/Python3-or-Solved-Using-Sorting-And-Prefix-Sum-O(nlogn)-Runtime-and-O(n)-Space!
|
class Solution:
#Let n = len(ranges)!
#Time-Complexity: O(nlogn + n * 1 + n * 1) - > O(nlogn)
#Space-Complexity: O(n), if there are n intervals side by side non overlapping!
def isCovered(self, ranges: List[List[int]], left: int, right: int) -> bool:
#Approach: I will iterate through each range 1-d array element in order to
#find all inclusive ranges that are distinct!
#Then, I will iterate through each and every inclusive range and see if both left and right
#interval within values are all contained in at least one of such ranges!
#If so, I return T! Otherwise, I return F!
#We can extend the last interval inserted if its end value is off by no more than 1 compared
#to current interval we are iterating on! -> This way I can utilize prefix sum technique
#to extend already inserted array!
#sort by the start point of each range first!
ranges.sort(key = lambda x: x[0])
inclusive_arr = []
#initially, add the first interval!
inclusive_arr.append(ranges[0])
for i in range(1, len(ranges)):
cur = ranges[i]
cur_start = cur[0]
last = inclusive_arr[-1]
last_end = last[1]
#if current interval start comes before the most recently inserted range's end value!
if(cur_start <= last_end):
if(cur[1] > last_end):
inclusive_arr[-1][1] = cur[1]
continue
#if current interval end point is encompassed within already existing interval, then
#simply don't modify most recently inserted interval!
else:
continue
else:
#if current interval's start value is no more than 1 greater than most recently
#inserted interval's last value, then we can simply extend the already inserted one!
if(abs(cur_start - last_end) <= 1):
inclusive_arr[-1][1] = cur[1]
continue
#otherwise, add on a new inclusive array!
else:
inclusive_arr.append(cur)
#then, we have to check if [left, right] is contained in at least one such interval!
for inc_arr in inclusive_arr:
inc_start, inc_end = inc_arr[0], inc_arr[1]
if((inc_start <= left <= inc_end) and
(inc_start <= right <= inc_end)):
return True
return False
|
check-if-all-the-integers-in-a-range-are-covered
|
Python3 | Solved Using Sorting And Prefix Sum O(nlogn) Runtime and O(n) Space!
|
JOON1234
| 0
| 51
|
check if all the integers in a range are covered
| 1,893
| 0.508
|
Easy
| 26,794
|
https://leetcode.com/problems/check-if-all-the-integers-in-a-range-are-covered/discuss/2467879/Python-Solution-or-99-Faster-or-Check-in-each-range-based-or-Clean-Code
|
class Solution:
def isCovered(self, ranges: List[List[int]], left: int, right: int) -> bool:
for num in range(left,right+1):
for l,r in ranges:
# if valid range, break and move to next integer
if l <= num <= r:
break
# if loop didnt break that means its a violation
else:
return False
return True
|
check-if-all-the-integers-in-a-range-are-covered
|
Python Solution | 99% Faster | Check in each range based | Clean Code
|
Gautam_ProMax
| 0
| 46
|
check if all the integers in a range are covered
| 1,893
| 0.508
|
Easy
| 26,795
|
https://leetcode.com/problems/check-if-all-the-integers-in-a-range-are-covered/discuss/2440922/Simple-python-O(n%2Bm)-using-a-set
|
class Solution:
def isCovered(self, ranges: List[List[int]], left: int, right: int) -> bool:
every = set()
for each in ranges:
every = every | {i for i in range(each[0], each[1]+1)}
for i in range(left, right+1):
if i not in every:
return False
return True
|
check-if-all-the-integers-in-a-range-are-covered
|
Simple python O(n+m) using a set
|
ikiselewski
| 0
| 32
|
check if all the integers in a range are covered
| 1,893
| 0.508
|
Easy
| 26,796
|
https://leetcode.com/problems/check-if-all-the-integers-in-a-range-are-covered/discuss/2345277/python-O(n*n)
|
class Solution:
def isCovered(self, ranges: List[List[int]], left: int, right: int) -> bool:
for i in range(left , right + 1):
flag = False
for j in ranges:
if j[0] <= i and j[1] >= i:
flag = True
break
if not flag:
return False
return True
|
check-if-all-the-integers-in-a-range-are-covered
|
python O(n*n)
|
akashp2001
| 0
| 37
|
check if all the integers in a range are covered
| 1,893
| 0.508
|
Easy
| 26,797
|
https://leetcode.com/problems/check-if-all-the-integers-in-a-range-are-covered/discuss/2024852/Python-Clean-and-Simple!
|
class Solution:
def isCovered(self, ranges, left, right):
covered = [False] * ((right-left)+1)
for s,e in ranges:
for i in range(s,e+1):
if left <= i <= right:
covered[i-left] = True
return all(covered)
|
check-if-all-the-integers-in-a-range-are-covered
|
Python - Clean and Simple!
|
domthedeveloper
| 0
| 97
|
check if all the integers in a range are covered
| 1,893
| 0.508
|
Easy
| 26,798
|
https://leetcode.com/problems/check-if-all-the-integers-in-a-range-are-covered/discuss/1871953/Python-dollarolution
|
class Solution:
def isCovered(self, ranges: List[List[int]], left: int, right: int) -> bool:
for i in range(left,right+1):
for j in ranges:
if i in range(j[0],j[1]+1):
flag = True
break
else:
flag = False
if flag == False:
return False
return True
|
check-if-all-the-integers-in-a-range-are-covered
|
Python $olution
|
AakRay
| 0
| 45
|
check if all the integers in a range are covered
| 1,893
| 0.508
|
Easy
| 26,799
|
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.