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/product-of-array-except-self/discuss/2690293/Simple-python-Soln | class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
product = 1
zero_i = set()
for i in range(len(nums)):
if nums[i] != 0:
product*= nums[i]
else:
zero_i.add(i)
if len(zero_i) == 1:
item = [0]*len(nums)
item[zero_i.pop()] = product
return item
if len(zero_i) > 1:
return [0]*len(nums)
return [product//a for a in nums] | product-of-array-except-self | Simple python Soln | user1090g | 0 | 5 | product of array except self | 238 | 0.648 | Medium | 4,500 |
https://leetcode.com/problems/product-of-array-except-self/discuss/2682318/Python-Solution-Constant-Space-89-Fast | class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
n=len(nums)
ans=[1]*n
lP=1
for i in range(n):
ans[i]*=lP
lP*=nums[i]
rP=1
for i in range(len(ans)-1,-1,-1):
ans[i]*=rP
rP*=nums[i]
return ans | product-of-array-except-self | Python Solution Constant Space 89% Fast | pranjalmishra334 | 0 | 82 | product of array except self | 238 | 0.648 | Medium | 4,501 |
https://leetcode.com/problems/product-of-array-except-self/discuss/2674298/Efficient-way-of-finding-product-is-elements-in-a-list-excluding-self | class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
prod=1
flag=0
if len(nums)>=2:
for i in range(len(nums)):
if nums[i] == 0:
flag+=1
else:
prod*=nums[i]
for i in range(len(nums)):
if flag == 0:
nums[i] = prod//nums[i]
elif flag == 1:
if nums[i]!=0:
nums[i]=0
else:
nums[i]=prod
else:
nums[i]=0
else:
nums=[]
return nums | product-of-array-except-self | Efficient way of finding product is elements in a list excluding self | deepanjan234 | 0 | 5 | product of array except self | 238 | 0.648 | Medium | 4,502 |
https://leetcode.com/problems/product-of-array-except-self/discuss/2667706/Simple-and-Straight-Forward-Solution-using-Python | class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
n = len(nums)
left = [1]*n
right = [1]*n
answer = [1]*n
left[0]=1
right[n-1]=1
for i in range(1,n):
left[i] = nums[i-1]*left[i-1]
for j in range(n-2,-1,-1):
right[j] = nums[j+1]*right[j+1]
for k in range(0,n):
answer[k] = left[k]*right[k]
return answer | product-of-array-except-self | Simple and Straight Forward Solution using Python | anusha_anil | 0 | 43 | product of array except self | 238 | 0.648 | Medium | 4,503 |
https://leetcode.com/problems/product-of-array-except-self/discuss/2667521/Python-Easy-solution | class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
finlist = []
pre = 1
prelist = [1]
post = 1
postlist = [1]
for num in nums:
pre *= num
prelist.append(pre)
for num in nums[::-1]:
post *= num
postlist.append(post)
postlist = postlist[:-1]
postlist = postlist[::-1]
for i in range(len(postlist)):
prod = postlist[i] * prelist[i]
finlist.append(prod)
return finlist | product-of-array-except-self | [Python] Easy solution | natscripts | 0 | 5 | product of array except self | 238 | 0.648 | Medium | 4,504 |
https://leetcode.com/problems/product-of-array-except-self/discuss/2656304/Python3-or-Prefix-Product-in-Both-Directions-(Use-2)-O(N)-TIME-AND-SPACE-SOL! | class Solution:
#Time-Complexity: O(2n + n * O(1)) -> O(N)
#Space-Complexity: O(2N) -> O(N)
def productExceptSelf(self, nums: List[int]) -> List[int]:
#Approach: Allocate two prefix sum, one starting from left and one starting from right.
#For every index i, we can get the prefix and suffix product and multiply those to get answer!
#Do this for all n indices!
ans = []
prefix_prod = []
prefix_prod.append(nums[0])
for a in range(1, len(nums)):
prefix_prod.append(prefix_prod[a-1] * nums[a])
suffix_prod = []
suffix_prod.append(nums[len(nums)-1])
iterator = 0
for b in range(len(nums)-2, -1, -1):
suffix_prod.append(suffix_prod[iterator] * nums[b])
iterator += 1
#now, answer for each index position i!
for i in range(len(nums)):
if(i == 0):
prefix_product = 1
else:
prefix_product = prefix_prod[i-1]
#we know we have to start multiplying from index i + 1 onwards!
diff = len(nums) - 1 - (i+1)
if(i < len(nums)-1):
suffix_product = suffix_prod[diff]
else:
suffix_product = 1
res = prefix_product * suffix_product
ans.append(res)
return ans | product-of-array-except-self | Python3 | Prefix Product in Both Directions (Use 2) O(N) TIME AND SPACE SOL! | JOON1234 | 0 | 110 | product of array except self | 238 | 0.648 | Medium | 4,505 |
https://leetcode.com/problems/product-of-array-except-self/discuss/2641988/Simple-Approach | class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
import math
n = len(nums)
res = [1 for _ in range(n)]
for i in range(1,n):
res[i] = res[i-1] * nums[i-1]
prod = nums[n-1]
for i in range(n-2,-1,-1):
res[i] = res[i] * prod
prod *= nums[i]
return res | product-of-array-except-self | Simple Approach | vkmaurya | 0 | 2 | product of array except self | 238 | 0.648 | Medium | 4,506 |
https://leetcode.com/problems/product-of-array-except-self/discuss/2551062/Python-simple-solution-using-prefix-and-suffix | class Solution:
def productExceptSelf(self, nums):
p, s, p_arr, s_arr = 1, 1, [], []
for i in range(len(nums)):
p, s = p * nums[i], s * nums[-i - 1]
p_arr.append(p)
s_arr.append(s)
for j in range(1, len(nums) - 1):
nums[j] = p_arr[j - 1] * s_arr[-j - 2]
nums[0], nums[-1] = s_arr[-2], p_arr[-2]
return nums | product-of-array-except-self | Python simple solution using prefix and suffix | Mark_computer | 0 | 99 | product of array except self | 238 | 0.648 | Medium | 4,507 |
https://leetcode.com/problems/product-of-array-except-self/discuss/2551062/Python-simple-solution-using-prefix-and-suffix | class Solution:
def productExceptSelf(self, nums):
p, s, p_arr, s_arr = 1, 1, [], []
for i in range(len(nums)):
p, s = p * nums[i], s * nums[-i - 1] # p is going from left to right; s -- from right to left
p_arr.append(p)
s_arr.append(s)
for j in range(1, len(nums) - 1):
nums[j] = p_arr[j - 1] * s_arr[-j - 2] # multiplying two products
# the reason for the negative index of *s_arr* is that it should be reversed
# but since we want to reduce the execution time we will just change indices to the needed ones
nums[0], nums[-1] = s_arr[-2], p_arr[-2] # edge cases
# for the first number there is no prefix and for the last number there is no suffix
return nums | product-of-array-except-self | Python simple solution using prefix and suffix | Mark_computer | 0 | 99 | product of array except self | 238 | 0.648 | Medium | 4,508 |
https://leetcode.com/problems/product-of-array-except-self/discuss/2540301/Python-It | class Solution:
def productExceptSelf(self, n: List[int]) -> List[int]:
ans = [1] * len(n)
pre, pos = 1, 1
for i in range(len(n)):
ans[i] = pre
pre *= n[i]
for i in range(len(n)-1, -1, -1):
ans[i] *= pos
pos *= n[i]
return ans | product-of-array-except-self | Python It ✅ | Khacker | 0 | 211 | product of array except self | 238 | 0.648 | Medium | 4,509 |
https://leetcode.com/problems/sliding-window-maximum/discuss/1624633/Python-3-O(n) | class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
res = []
window = collections.deque()
for i, num in enumerate(nums):
while window and num >= nums[window[-1]]:
window.pop()
window.append(i)
if i + 1 >= k:
res.append(nums[window[0]])
if i - window[0] + 1 == k:
window.popleft()
return res | sliding-window-maximum | Python 3 O(n) | dereky4 | 3 | 772 | sliding window maximum | 239 | 0.466 | Hard | 4,510 |
https://leetcode.com/problems/sliding-window-maximum/discuss/755538/Python3-mono-queue | class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
queue = deque() # decreasing queue
ans = []
for i, x in enumerate(nums):
while queue and queue[-1][1] <= x: queue.pop()
queue.append((i, x))
if queue and queue[0][0] <= i-k: queue.popleft()
if i >= k-1: ans.append(queue[0][1])
return ans | sliding-window-maximum | [Python3] mono-queue | ye15 | 3 | 132 | sliding window maximum | 239 | 0.466 | Hard | 4,511 |
https://leetcode.com/problems/sliding-window-maximum/discuss/1738137/Python-Deque-solution-explained | class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
# this deque will hold the
# index of the max element
# in a sliding window
queue = deque()
res = []
for i, curr_val in enumerate(nums):
# remove all those elements in the queue
# which are smaller than the current element
# this should maintain that the largest element
# in a window would be at the beginning of the
# queue
while queue and nums[queue[-1]] <= curr_val:
queue.pop()
# add the index of the
# current element always
queue.append(i)
# check if the first element in the queue
# is still within the bounds of the window
# i.e. the current index - k, if not
# remove it (popleft)
#
# here, storing the index instead of the
# element itself becomes apparent, since
# we're going linearly, we can check the
# index of the first element in the queue
# to see if it's within the current window
# or not
if queue[0] == i-k:
queue.popleft()
# simple check to ensure that we
# take into account the max element
# only when the window is of size >= k
# and since we're starting with an empty
# queue, we'll initially have a window
# of size 1,2,3....k-1 which are not valid
if i >= k-1:
res.append(nums[queue[0]])
return res | sliding-window-maximum | [Python] Deque solution explained | buccatini | 2 | 377 | sliding window maximum | 239 | 0.466 | Hard | 4,512 |
https://leetcode.com/problems/sliding-window-maximum/discuss/1505368/Py3Py-Solution-using-monotonically-decreasing-sequence-w-comment | class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
# Init
q = [] # This is queue of indexes not num queue of values
n = len(nums)
output = []
# Base Case: If window size is 1
if k == 1:
return nums
# Base Case: If window size is greater or equal to n
if n <= k:
return [max(nums)]
# Fill the first k elements
for i in range(k):
# Pop till q is a monotonicall decreasing seq
while q and nums[q[-1]] < nums[i]:
q.pop()
# Add the current index
q.append(i)
# First max value for window of size k
output.append(nums[q[0]])
# Fill elements with index starting from k
for i in range(k, n):
# Remove out of window elements
window_start_index = (i-k) + 1
while q and q[0] < window_start_index:
q.pop(0)
# Pop till q is a monotonicall decreasing seq
while q and nums[q[-1]] < nums[i]:
q.pop()
# Add the current index
q.append(i)
# queue is not empty then append the current max
if q:
output.append(nums[q[0]])
return output | sliding-window-maximum | [Py3/Py] Solution using monotonically decreasing sequence w/ comment | ssshukla26 | 2 | 230 | sliding window maximum | 239 | 0.466 | Hard | 4,513 |
https://leetcode.com/problems/sliding-window-maximum/discuss/536588/Python3-Easy-Solution.-Slicing | class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
rlist = []
for i in range(len(nums)):
if (i+k) > len(nums):
break
int_list = nums[i:(i+k)]
max_element = max(int_list)
rlist.append(max_element)
return rlist | sliding-window-maximum | Python3 Easy Solution. Slicing | cppygod | 2 | 186 | sliding window maximum | 239 | 0.466 | Hard | 4,514 |
https://leetcode.com/problems/sliding-window-maximum/discuss/2505411/Python-3-Monotonic-Deque-Approach-Explained | class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
N = len(nums)
mono_deque = collections.deque()
result = []
for i, num in enumerate(nums):
while mono_deque and mono_deque[0] < i - k + 1:
mono_deque.popleft()
while mono_deque and nums[mono_deque[-1]] < num:
mono_deque.pop()
mono_deque.append(i)
if i - k + 1 >= 0:
result.append(nums[mono_deque[0]])
return result | sliding-window-maximum | Python 3 Monotonic Deque Approach Explained | sebikawa | 1 | 122 | sliding window maximum | 239 | 0.466 | Hard | 4,515 |
https://leetcode.com/problems/sliding-window-maximum/discuss/2505411/Python-3-Monotonic-Deque-Approach-Explained | class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
N = len(nums)
mono_deque = collections.deque()
result = []
for i, num in enumerate(nums):
while mono_deque and mono_deque[-1] < i - k + 1:
mono_deque.pop()
while mono_deque and nums[mono_deque[0]] < num:
mono_deque.popleft()
mono_deque.appendleft(i)
if i - k + 1 >= 0:
result.append(nums[mono_deque[-1]])
return result | sliding-window-maximum | Python 3 Monotonic Deque Approach Explained | sebikawa | 1 | 122 | sliding window maximum | 239 | 0.466 | Hard | 4,516 |
https://leetcode.com/problems/sliding-window-maximum/discuss/2342547/GoPython-Devide-and-Conquer-Solution-and-Deque-Solution | class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
res, dq = [], deque()
for i, v in enumerate(nums):
if i > k-1 and dq[0] < i - k + 1:
dq.popleft()
while dq and v > nums[dq[-1]]:
dq.pop()
dq += i,
if i > k-2:
res += nums[dq[0]],
return res | sliding-window-maximum | [Go][Python] Devide & Conquer Solution and Deque Solution | larashion | 1 | 68 | sliding window maximum | 239 | 0.466 | Hard | 4,517 |
https://leetcode.com/problems/sliding-window-maximum/discuss/2342547/GoPython-Devide-and-Conquer-Solution-and-Deque-Solution | class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
res, left, right = [0 for _ in range(len(nums) - k + 1)], defaultdict(int), defaultdict(int)
for i in range(len(nums)):
if i % k == 0:
left[i] = nums[i]
else:
left[i] = max(nums[i], left[i - 1])
j = len(nums) - 1 - i
if j % k == k - 1 or j == len(nums) - 1:
right[j] = nums[j]
else:
right[j] = max(nums[j], right[j + 1])
for i in range(len(nums) - k + 1):
res[i] = max(right[i], left[i + k - 1])
return res | sliding-window-maximum | [Go][Python] Devide & Conquer Solution and Deque Solution | larashion | 1 | 68 | sliding window maximum | 239 | 0.466 | Hard | 4,518 |
https://leetcode.com/problems/sliding-window-maximum/discuss/2211348/Python-or-Easy-to-Understand | class Solution:
def maxSlidingWindow(self, A: List[int], B: int) -> List[int]:
# SO as we can imagine we have to find maximum as we slide through the window
# and we can achieve by maintaining a maxx variable and compairing it with each addition of j
# and when window reaches k will append maxx to result array
# but there is catch, what if maxx is first value of previous window,
# ie as window moves we cant determine what will be next max, is it from remaining i to j
# ie remaining array or is new number added ie new j
# so for that we need to store that info in some data structure
from collections import deque
i,j,res=0,0,[]
dq=deque()
#sliding window loop
while j<len(A):
# if new element is greater than previous elements
# then now we dont need previous elements
# as until this becomes the element to be removed, its lower elements
# ie next numbers will be next maxx which will be added and until then this will be max
# and everytime some greater number adds, previous numbers will be deprecated
while dq and dq[-1]<A[j]:
dq.pop()
dq.append(A[j])
# print(dq)
#sliding window condition for reaching window
if j-i+1==B:
# the element at front will always be max element
res.append(dq[0])
# when the max element is first to be removed as window will slide,
# we will also pop that value from dq so, its next maxx will be at front of dq
if dq[0]==A[i]:
dq.popleft()
# print(res)
i+=1
j+=1
return res | sliding-window-maximum | Python | Easy to Understand | varun21vaidya | 1 | 178 | sliding window maximum | 239 | 0.466 | Hard | 4,519 |
https://leetcode.com/problems/sliding-window-maximum/discuss/2030080/Python-Simple-and-Easy-Solution | class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
res = []
queue = collections.deque()
l = r = 0
while r < len(nums):
while queue and nums[queue[-1]] < nums[r]:
queue.pop()
queue.append(r)
if l > queue[0]:
queue.popleft()
if r+ 1 >= k:
res.append(nums[queue[0]])
l += 1
r += 1
return res | sliding-window-maximum | Python - Simple and Easy Solution | dayaniravi123 | 1 | 123 | sliding window maximum | 239 | 0.466 | Hard | 4,520 |
https://leetcode.com/problems/sliding-window-maximum/discuss/1570913/Python-Simple-deque-solution | class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
n = len(nums)
from queue import deque
deq = deque()
ans = []
for i in range(n):
while deq and i - deq[0][1] >= k:
deq.popleft()
while deq and deq[-1][0] <= nums[i]:
deq.pop()
deq.append((nums[i], i))
if i >= k-1:
ans.append(deq[0][0])
return ans | sliding-window-maximum | [Python] Simple deque solution | nomofika | 1 | 338 | sliding window maximum | 239 | 0.466 | Hard | 4,521 |
https://leetcode.com/problems/sliding-window-maximum/discuss/1051342/Python3-faster-than-98-and-easy-understanding | class Solution:
#monotonic queue
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
if len(nums) == 0:
return []
res,mqueue=[],collections.deque() #deque much faster than list
for i,e in enumerate(nums):
#monotonic queue push
while mqueue and mqueue[-1] < e:
mqueue.pop()
mqueue.append(e)
# result save and monotonic queue popp
if i >k-2:
res.append(mqueue[0])
if nums[i-k+1] == mqueue[0]:
mqueue.popleft() # here not list.pop(0) due to O(n) complexity
return res | sliding-window-maximum | Python3 faster than 98% & easy understanding | 695051665 | 1 | 154 | sliding window maximum | 239 | 0.466 | Hard | 4,522 |
https://leetcode.com/problems/sliding-window-maximum/discuss/247137/Python3-104-ms-beats-97.58.-O(nk)-O(n)-time-complexity. | class Solution:
def maxSlidingWindow(self, nums: 'List[int]', k: 'int') -> 'List[int]':
n = len(nums)
if n * k == 0:
return []
# O(nk) in the worst case of sorted descending array
# O(n) in the best case of sorted ascending array
output = []
max_idx = -1
for i in range(n - k + 1):
# max_idx is out of sliding window
if max_idx < i:
max_idx = i
for j in range(i, i + k):
if nums[j] > nums[max_idx]:
max_idx = j
# max element is smaller than the last
# element in the window
elif nums[max_idx] < nums[i + k - 1]:
max_idx = i + k - 1
output.append(nums[max_idx])
return output | sliding-window-maximum | Python3, 104 ms, beats 97.58%. O(nk) / O(n) time complexity. | andvary | 1 | 633 | sliding window maximum | 239 | 0.466 | Hard | 4,523 |
https://leetcode.com/problems/sliding-window-maximum/discuss/2833821/Python-Solution-using-deque-or-O(n) | class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
output = []
q = collections.deque() # index
l = r = 0
# O(n) O(n)
while r < len(nums):
# pop smaller values from q
while q and nums[q[-1]] < nums[r]:
q.pop()
q.append(r)
# remove left val from window
if l > q[0]:
q.popleft()
if (r + 1) >= k:
output.append(nums[q[0]])
l += 1
r += 1
return output | sliding-window-maximum | Python Solution using deque | O(n) | nikhitamore | 0 | 9 | sliding window maximum | 239 | 0.466 | Hard | 4,524 |
https://leetcode.com/problems/sliding-window-maximum/discuss/2825356/Python-super-fast-easy-solution-linear-time-and-space. | class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
arr, ans = deque([]), []
for i in range(len(nums)):
if arr and arr[0] == i - k: arr.popleft()
while arr and nums[ arr[-1] ] < nums[i]:
arr.pop()
arr.append(i)
if i>=k-1: ans.append(nums[ arr[0] ])
return ans | sliding-window-maximum | Python super fast easy solution linear time and space. | Samuelabatneh | 0 | 7 | sliding window maximum | 239 | 0.466 | Hard | 4,525 |
https://leetcode.com/problems/sliding-window-maximum/discuss/2807438/Faster-than-100-using-deque | class Solution:
def maxSlidingWindow(self, arr: List[int], k: int) -> List[int]:
ans=[]
s = []
n=len(arr)
maxi=-1e9
i=j=0
while j<n:
while s and s[-1]<arr[j]:
s.pop()
s.append(arr[j])
if j-i+1<k:
j+=1
elif j-i+1==k:
ans.append(s[0])
if s[0]==arr[i]:s.pop(0)
i+=1
j+=1
return ans | sliding-window-maximum | Faster than 100% using deque | sanskar_ | 0 | 5 | sliding window maximum | 239 | 0.466 | Hard | 4,526 |
https://leetcode.com/problems/sliding-window-maximum/discuss/2764058/Descending-Queue | class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
q = []
res = []
# R points to the 'to-be-added' elem
for R in range(len(nums)):
# Pop nums[R-k] (if it is the head of the window !)
if q and R >= k and q[0] == nums[R-k]:
q.pop(0)
# Push nums[R]
# 1) pop all that are less than nums[R]
while q and q[-1] < nums[R]:
q.pop(-1)
# 2) append nums[R]
q.append(nums[R])
# Save result, q[0] always is the largest in the window
if R >= k-1:
res.append(q[0])
return res | sliding-window-maximum | Descending Queue | KKCrush | 0 | 5 | sliding window maximum | 239 | 0.466 | Hard | 4,527 |
https://leetcode.com/problems/sliding-window-maximum/discuss/2764057/Descending-Queue | class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
q = []
res = []
# R points to the 'to-be-added' elem
for R in range(len(nums)):
# Pop nums[R-k] (if it is the head of the window !)
if q and R >= k and q[0] == nums[R-k]:
q.pop(0)
# Push nums[R]
# 1) pop all that are less than nums[R]
while q and q[-1] < nums[R]:
q.pop(-1)
# 2) append nums[R]
q.append(nums[R])
# Save result, q[0] always is the largest in the window
if R >= k-1:
res.append(q[0])
return res | sliding-window-maximum | Descending Queue | KKCrush | 0 | 2 | sliding window maximum | 239 | 0.466 | Hard | 4,528 |
https://leetcode.com/problems/sliding-window-maximum/discuss/2760193/Optimal-Solution-of-Sliding-Window-Maximum-with-python3. | class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
output=[]
left=right=0
q=collections.deque()
while right<len(nums):
while q and nums[q[-1]] <nums[right]:
q.pop()
q.append(right)
# remove left value from window
if left>q[0]:
q.popleft()
if(right+1) >=k:
output.append(nums[q[0]])
left+=1
right+=1
return output | sliding-window-maximum | Optimal Solution of Sliding Window Maximum with python3. | ossamarhayrhay2001 | 0 | 4 | sliding window maximum | 239 | 0.466 | Hard | 4,529 |
https://leetcode.com/problems/sliding-window-maximum/discuss/2741419/Python-solution-using-heap | class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
heap = []
for i in range(k):
heapq.heappush(heap, -nums[i])
dic = defaultdict(int)
answer = []
left, right = 0, k-1
while right < len(nums):
while -heap[0] in dic:
curr = -heapq.heappop(heap)
if dic[curr] > 1:
dic[curr] -= 1
else:
del dic[curr]
answer.append(-heap[0])
dic[nums[left]] += 1
left += 1
right += 1
if right < len(nums):
heapq.heappush(heap, -nums[right])
return answer | sliding-window-maximum | Python solution using heap | tesfish | 0 | 9 | sliding window maximum | 239 | 0.466 | Hard | 4,530 |
https://leetcode.com/problems/sliding-window-maximum/discuss/2696107/Monotonic-Queue-or | class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
queue = collections.deque()
for i in range(k-1):
while queue and queue[-1] < nums[i]:
queue.pop()
queue.append(nums[i])
rst = []
for i in range(k-1,len(nums)):
while queue and queue[-1] < nums[i]:
queue.pop()
queue.append(nums[i])
rst.append(queue[0])
if queue[0] == nums[i-k+1]:
queue.popleft()
return rst | sliding-window-maximum | Monotonic Queue | 单调队列 | wenkii | 0 | 2 | sliding window maximum | 239 | 0.466 | Hard | 4,531 |
https://leetcode.com/problems/sliding-window-maximum/discuss/2690415/Sliding-Window-Maximum | class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
res = []
deque = []
for i in range(len(nums)):
while len(deque) > 0 and nums[i] > nums[deque[len(deque) - 1]]:
deque.pop()
deque.append(i)
if i - deque[0] >= k:
deque.pop(0)
if i >= k - 1:
res.append(nums[deque[0]])
return res | sliding-window-maximum | Sliding Window Maximum | Erika_v | 0 | 4 | sliding window maximum | 239 | 0.466 | Hard | 4,532 |
https://leetcode.com/problems/sliding-window-maximum/discuss/2668740/Python-O(N)-O(N) | class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
queue = deque()
def clean(idx):
while queue and queue[-1] < nums[idx]:
queue.pop()
queue.append(nums[idx])
for idx in range(k):
clean(idx)
res = [queue[0]]
for idx in range(k, len(nums)):
if nums[idx - k] == queue[0]:
queue.popleft()
clean(idx)
res.append(queue[0])
return res | sliding-window-maximum | Python - O(N), O(N) | Teecha13 | 0 | 8 | sliding window maximum | 239 | 0.466 | Hard | 4,533 |
https://leetcode.com/problems/sliding-window-maximum/discuss/2667012/Heap-solution-or-Python3-or-Simple-and-intuitive | class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
max_hp = []
answer = []
for i in range(k):
heapq.heappush(max_hp,(-nums[i],i))
N = len(nums)
for i in range(k,N):
answer.append(-max_hp[0][0])
# Delete heap top till index less
# than current starting index are on top
while max_hp and max_hp[0][1] <= i - k:
heapq.heappop(max_hp)
heapq.heappush(max_hp,(-nums[i],i))
return answer + [-heapq.heappop(max_hp)[0]] | sliding-window-maximum | Heap solution | Python3 | Simple and intuitive | abhi-now | 0 | 3 | sliding window maximum | 239 | 0.466 | Hard | 4,534 |
https://leetcode.com/problems/sliding-window-maximum/discuss/2666463/python-or-deque-or-sliding-window | class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
# use deque to handle this sliding window problem
queue, n = collections.deque(), len(nums)
# select kth elements into queue
for i in range(k):
# ensure the left elemt have the biggest element
# e.g. [0, 1, 2] in queue <- num[0] = 3, num[1] = 2, num[2] = 1
# we want to add new element num[4] = 4, index of nums is 4
# last element of the queue is smaller than new element, and it will pop the element
# run in loop
while queue and nums[i] >= nums[queue[-1]]:
queue.pop()
queue.append(i)
# result = [nums[4]]
result = [nums[queue[0]]]
# queue with the biggest element in the left
for i in range(k, n):
# queue deletes all the elements smaller than num[i]
while queue and nums[i] >= nums[queue[-1]]:
queue.pop()
queue.append(i)
# queue[0], index of the left element is larger than i - k,
# left element is out of the left window
if queue[0] <= i - k:
queue.popleft()
result.append(nums[queue[0]])
return result
``` | sliding-window-maximum | python | deque | sliding window | MichelleZou | 0 | 36 | sliding window maximum | 239 | 0.466 | Hard | 4,535 |
https://leetcode.com/problems/sliding-window-maximum/discuss/2664906/python-deque-solotion | class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
# o(n), o(n)
output = []
q = collections.deque()
l = r = 0
while r < len(nums):
# pop smaller values from q
while q and nums[q[-1]] < nums[r]:
q.pop()
q.append(r)
# remove left val from window
if l > q[0]:
q.popleft()
if r + 1 >= k:
output.append(nums[q[0]])
l += 1
r += 1
return output | sliding-window-maximum | python deque solotion | sahilkumar158 | 0 | 3 | sliding window maximum | 239 | 0.466 | Hard | 4,536 |
https://leetcode.com/problems/sliding-window-maximum/discuss/2656355/O(n)-or-Python | class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
res = []
l = r = 0
q = collections.deque()
while r < len(nums):
while q and nums[q[-1]] < nums[r]:
q.pop()
q.append(r)
if l > q[0]:
q.popleft()
if (r+1) >= k:
res.append(nums[q[0]])
l += 1
r += 1
return res | sliding-window-maximum | O(n) | Python | normal_crayon | 0 | 11 | sliding window maximum | 239 | 0.466 | Hard | 4,537 |
https://leetcode.com/problems/sliding-window-maximum/discuss/2645070/take-a-note-to-learn | class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
d = collections.deque()
out = []
for i, n in enumerate(nums):
while d and nums[d[-1]] < n:
d.pop()
d += i,
if d[0] == i - k:
d.popleft()
if i >= k - 1:
out += nums[d[0]],
return out | sliding-window-maximum | take a note to learn | lucy_sea | 0 | 3 | sliding window maximum | 239 | 0.466 | Hard | 4,538 |
https://leetcode.com/problems/sliding-window-maximum/discuss/2643957/Python-using-monotonous-queue-or-O(N) | class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
res = []
left = 0
q = collections.deque()
# q is a monotonous queue, leftmost is the index of the max value
for right in range(len(nums)):
while q and nums[q[-1]]<nums[right]: # in decreasing order
q.pop()
q.append(right)
if left>q[0]:
q.popleft()
if (right+1)>=k:
res.append(nums[q[0]])
left += 1 # move the sliding window
return res | sliding-window-maximum | Python using monotonous queue | O(N) | gcheng81 | 0 | 4 | sliding window maximum | 239 | 0.466 | Hard | 4,539 |
https://leetcode.com/problems/sliding-window-maximum/discuss/2536352/Python3-%2B-Sliding-Window-%2B-Max-Heap | class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
start = 0
heap = []
i = 0
while i < k:
heappush(heap, (-1*nums[i], i))
i += 1
ans = []
for end in range(k, len(nums)):
ans.append(-1*heap[0][0])
while heap and heap[0][1] <= start:
heappop(heap)
start += 1
heappush(heap, (-1*nums[end], end))
ans.append(-1*heap[0][0])
return ans | sliding-window-maximum | Python3 + Sliding Window + Max Heap | leet_satyam | 0 | 118 | sliding window maximum | 239 | 0.466 | Hard | 4,540 |
https://leetcode.com/problems/sliding-window-maximum/discuss/2509732/What's-wrong-in-this-code-4451-test-cases-passing | class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
l,r = 0,0
q = []
while True:
if not q:
q.append(nums[l])
else:
while q and nums[r]>=q[-1]:
q.pop()
q.append(nums[r])
if r-l+1==k:
break
r+=1
ans = []
while r!=len(nums):
maxi = q[0]
ans.append(maxi)
if r+1<len(nums):
while q and (len(q)==0 or nums[r+1]>q[-1]):
q.pop()
q.append(nums[r+1])
if nums[l]==q[0]:
q.pop(0)
l+=1
r+=1
return ans | sliding-window-maximum | What's wrong in this code, 44/51 test cases passing | abhineetsingh192 | 0 | 41 | sliding window maximum | 239 | 0.466 | Hard | 4,541 |
https://leetcode.com/problems/search-a-2d-matrix-ii/discuss/2324351/PYTHON-oror-EXPLAINED-oror | class Solution:
def searchMatrix(self, mat: List[List[int]], target: int) -> bool:
m=len(mat)
n=len(mat[0])
i=m-1
j=0
while i>=0 and j<n:
if mat[i][j]==target:
return True
elif mat[i][j]<target:
j+=1
else:
i-=1
return False | search-a-2d-matrix-ii | ✔️ PYTHON || EXPLAINED || ; ] | karan_8082 | 48 | 1,700 | search a 2d matrix ii | 240 | 0.507 | Medium | 4,542 |
https://leetcode.com/problems/search-a-2d-matrix-ii/discuss/2324351/PYTHON-oror-EXPLAINED-oror | class Solution:
def searchMatrix(self, mat: List[List[int]], target: int) -> bool:
m=len(mat)
n=len(mat[0])
for i in range(m):
if mat[i][0]<=target and mat[i][-1]>=target:
lo=0
hi=n
while (lo<hi):
mid=(lo+hi)//2
if mat[i][mid]==target:
return True
elif mat[i][mid]<target:
lo = mid + 1
else:
hi = mid
return False | search-a-2d-matrix-ii | ✔️ PYTHON || EXPLAINED || ; ] | karan_8082 | 48 | 1,700 | search a 2d matrix ii | 240 | 0.507 | Medium | 4,543 |
https://leetcode.com/problems/search-a-2d-matrix-ii/discuss/1079178/Python.-Super-simple-O(m-%2B-n).-faster-than-93.65 | class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
row, col, num_row = 0, len(matrix[0]) - 1, len(matrix)
while col >= 0 and row < num_row:
if matrix[row][col] > target:
col -= 1
elif matrix[row][col] < target:
row += 1
else:
return True
return False | search-a-2d-matrix-ii | Python. Super simple O(m + n). faster than 93.65% | m-d-f | 11 | 504 | search a 2d matrix ii | 240 | 0.507 | Medium | 4,544 |
https://leetcode.com/problems/search-a-2d-matrix-ii/discuss/697281/Python3-O(n-%2B-m)-with-explanationproof | class Solution:
def searchMatrix(self, matrix, target):
if matrix == None or len(matrix) == 0 or len(matrix[0]) == 0:
return False
n, m = len(matrix), len(matrix[0])
i, j = 0, m - 1
while i < n and j >= 0:
if matrix[i][j] == target:
return True
elif matrix[i][j] < target:
i += 1
else:
j -= 1
return False
``` | search-a-2d-matrix-ii | Python3 O(n + m) with explanation/proof | awitten1 | 9 | 591 | search a 2d matrix ii | 240 | 0.507 | Medium | 4,545 |
https://leetcode.com/problems/search-a-2d-matrix-ii/discuss/2452328/Python-Very-clear-explanation-with-drawing-O(m%2Bn). | class Solution:
def searchMatrix(self, matrix, target):
rows, cols = len(matrix), len(matrix[0])
top = 0
right = cols-1
bottom = rows-1
left = 0
while bottom >= top and left <= right:
if matrix[bottom][left] == target:
return True
if matrix[bottom][left] > target:
bottom -= 1
elif matrix[bottom][left] < target:
left += 1
return False | search-a-2d-matrix-ii | Python Very clear explanation with drawing O(m+n). | OsamaRakanAlMraikhat | 3 | 68 | search a 2d matrix ii | 240 | 0.507 | Medium | 4,546 |
https://leetcode.com/problems/search-a-2d-matrix-ii/discuss/1419121/Easy-Python-Solution-or-Faster-than-98-Memory-less-93 | class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
for r in matrix:
if r[0] <= target and r[-1] >= target:
l, h = 0, len(r)-1
while l <= h:
m = (l+h)//2
if r[m] > target:
h = m - 1
elif r[m] < target:
l = m + 1
else:
return True
else:
continue
return False | search-a-2d-matrix-ii | Easy Python Solution | Faster than 98%, Memory < 93% | the_sky_high | 3 | 286 | search a 2d matrix ii | 240 | 0.507 | Medium | 4,547 |
https://leetcode.com/problems/search-a-2d-matrix-ii/discuss/415360/Python3-Brute-Force-Binary-Search-Search-Space-Reduction-Solutions | class Solution:
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if len(matrix) == 0:
return False
row, col = len(matrix), len(matrix[0])
for i in range(row):
for j in range(col):
if matrix[i][j] == target:
return True
return False | search-a-2d-matrix-ii | Python3 Brute Force/ Binary Search/ Search Space Reduction Solutions | yanshengjia | 3 | 302 | search a 2d matrix ii | 240 | 0.507 | Medium | 4,548 |
https://leetcode.com/problems/search-a-2d-matrix-ii/discuss/415360/Python3-Brute-Force-Binary-Search-Search-Space-Reduction-Solutions | class Solution:
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if len(matrix) == 0:
return False
row, col = len(matrix), len(matrix[0])
# iterate over matrix diagonals, from top-left to bottom-right
short_edge = min(row, col)
for i in range(short_edge):
row_found = self.binary_search(matrix, target, i, False)
col_found = self.binary_search(matrix, target, i, True)
if row_found or col_found:
return True
return False
def binary_search(self, matrix, target: int, start: int, vertical: bool) -> bool:
lo = start
hi = len(matrix) - 1 if vertical else len(matrix[0]) - 1
while lo <= hi:
mid = (lo + hi) // 2
if vertical: # search column
if matrix[mid][start] < target:
lo = mid + 1
elif matrix[mid][start] > target:
hi = mid - 1
else:
return True
else: # search row
if matrix[start][mid] < target:
lo = mid + 1
elif matrix[start][mid] > target:
hi = mid - 1
else:
return True
return False | search-a-2d-matrix-ii | Python3 Brute Force/ Binary Search/ Search Space Reduction Solutions | yanshengjia | 3 | 302 | search a 2d matrix ii | 240 | 0.507 | Medium | 4,549 |
https://leetcode.com/problems/search-a-2d-matrix-ii/discuss/2326170/Python-Beginner-Friendly-Solution-oror-Brute-Force | class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
ans = False
for i in matrix:
if target in i:
ans = True
return ans | search-a-2d-matrix-ii | Python Beginner Friendly Solution || Brute Force | Shivam_Raj_Sharma | 2 | 37 | search a 2d matrix ii | 240 | 0.507 | Medium | 4,550 |
https://leetcode.com/problems/search-a-2d-matrix-ii/discuss/1715636/Python-Simple-Python-Solution-Using-Binary-Search-and-For-Loop-!!-O(N-LogN) | class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
def search(array,target):
low = 0
high = len(array)
while low<high:
mid=(low+high)//2
if array[mid]==target:
return mid
elif array[mid]<target:
low=mid+1
elif array[mid]>target:
high=mid
return -1
for i in matrix:
if i[0] <= target:
if search(i, target)!=-1:
return True
return False | search-a-2d-matrix-ii | [ Python ] ✔🔥 Simple Python Solution Using Binary Search and For Loop !! O(N LogN) | ASHOK_KUMAR_MEGHVANSHI | 2 | 127 | search a 2d matrix ii | 240 | 0.507 | Medium | 4,551 |
https://leetcode.com/problems/search-a-2d-matrix-ii/discuss/990886/10-line-python-O(n)-solution | class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
m, n = len(matrix), len(matrix[0])
row, col = 0, n - 1
while row < m and col >= 0:
if matrix[row][col] == target:
return True
elif matrix[row][col] > target:
col -= 1
else:
row += 1
return False | search-a-2d-matrix-ii | 10 line python O(n) solution | ChiCeline | 2 | 281 | search a 2d matrix ii | 240 | 0.507 | Medium | 4,552 |
https://leetcode.com/problems/search-a-2d-matrix-ii/discuss/2326574/Python3-Runtime%3A-175ms-94.99-oror-memory%3A-20.3mb-98.38 | class Solution:
# Runtime: 175ms 94.99% || memory: 20.3mb 98.38%
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
col = len(matrix[0])-1
for item in range(len(matrix)):
while matrix[item][col] > target and col >= 0:
col-=1
if matrix[item][col] == target:
return True
return False | search-a-2d-matrix-ii | Python3 Runtime: 175ms 94.99% || memory: 20.3mb 98.38% | arshergon | 1 | 20 | search a 2d matrix ii | 240 | 0.507 | Medium | 4,553 |
https://leetcode.com/problems/search-a-2d-matrix-ii/discuss/2231277/2-pointers-approach-oror-Clean-Code | class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
m, n = len(matrix), len(matrix[0])
i, j = 0, n - 1
while i < m and j >= 0:
if matrix[i][j] == target:
return True
elif matrix[i][j] < target:
i += 1
else:
j -= 1
return False | search-a-2d-matrix-ii | 2 pointers approach || Clean Code | Vaibhav7860 | 1 | 42 | search a 2d matrix ii | 240 | 0.507 | Medium | 4,554 |
https://leetcode.com/problems/search-a-2d-matrix-ii/discuss/1761136/python-linear-time | class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
col = 0
row = len(matrix)-1
while True:
if row < 0:
return False
elif col > len(matrix[0])-1:
return False
elif matrix[row][col] == target:
return True
elif target < matrix[row][col]:
row = row-1
else:
col = col+1 | search-a-2d-matrix-ii | python linear time | gasohel336 | 1 | 72 | search a 2d matrix ii | 240 | 0.507 | Medium | 4,555 |
https://leetcode.com/problems/search-a-2d-matrix-ii/discuss/1592201/Py3Py-Simple-traversal-w-comments | class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
# Init
m = len(matrix)
n = len(matrix[0])
# Helper function tp check if row and col
# are within limits
def inLimits(r,c):
return (0 <= r < m) and (0 <= c < n)
# start at top right corner
row, col = 0, n-1
# Loop till row and col variables are within limits
while inLimits(row, col):
# If current value is less that target, move a row down
if matrix[row][col] < target:
row, col = row+1, col
# If current value is greater than target, move a col to left
elif matrix[row][col] > target:
row, col = row, col-1
else: # target found
return True
return False # default value | search-a-2d-matrix-ii | [Py3/Py] Simple traversal w/ comments | ssshukla26 | 1 | 85 | search a 2d matrix ii | 240 | 0.507 | Medium | 4,556 |
https://leetcode.com/problems/search-a-2d-matrix-ii/discuss/1079121/python-solution-O(row%2Bcol)-time | class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
row=len(matrix)
col=len(matrix[0])
i=row-1
j=0
while(i>=0 and j<col):
if matrix[i][j]==target:
return True
elif matrix[i][j]<target:
j+=1
else:
i-=1
return False
PLEASE UPVOTE IF YOU LIKE | search-a-2d-matrix-ii | python solution O(row+col) time | _Rehan12 | 1 | 32 | search a 2d matrix ii | 240 | 0.507 | Medium | 4,557 |
https://leetcode.com/problems/search-a-2d-matrix-ii/discuss/557533/Python3-binary-search-explained | class Solution:
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if not matrix: return False
# keep the current state of the search in a global variable
state = {'found': False}
memory = set()
# auxiliar function to validate the intervals
def valid(l_x, l_y, r_x, r_y):
if not 0 <= l_x < r_x <= len(matrix): return False
if not 0 <= l_y < r_y <= len(matrix[0]): return False
return True
# apply binary search to the matrix
def bs(l_x, l_y, r_x, r_y):
if state['found']: return
# no revisiting
if (l_x, l_y, r_x, r_y) in memory: return
memory.add((l_x, l_y, r_x, r_y))
if not valid(l_x, l_y, r_x, r_y): return
# get the middle... you know this part
m_x = (l_x + r_x)//2
m_y = (l_y + r_y)//2
# print(f'node: {(l_x, l_y, r_x, r_y)}, m: {(m_x, m_y)}->{matrix[m_x][m_y]}')
if matrix[m_x][m_y] == target: state['found'] = True; return
# keep exploring the matrix, here is the trick...
if target < matrix[m_x][m_y]:
# why 3 recursive calls you may ask?
bs(l_x, l_y, m_x, m_y)
bs(l_x, l_y, r_x, m_y)
bs(l_x, l_y, m_x, r_y)
else:
# with 3 is just faster, can also be 2
bs(m_x+1, m_y+1, r_x, r_y)
bs(m_x+1, l_y, r_x, r_y)
bs(l_x, m_y+1, r_x, r_y)
# launch the recursive search
bs(0, 0, len(matrix), len(matrix[0]))
return state['found'] | search-a-2d-matrix-ii | Python3 binary search explained | zetinator | 1 | 262 | search a 2d matrix ii | 240 | 0.507 | Medium | 4,558 |
https://leetcode.com/problems/search-a-2d-matrix-ii/discuss/417051/Can-anyone-tell-me-the-runtime-of-my-recursive-Python-solution | class Solution:
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if not matrix or not matrix[0]:
return False
m = len(matrix)
n = len(matrix[0])
return self.search(matrix,(0,0),(m-1,n-1),target)
def search(self,matrix, minR, maxR,val):
minM, minN = minR
maxM,maxN = maxR
i,j = minM,minN
prei,prej= None,None
if matrix[i][j] == val:
return True
elif matrix[i][j] >val:
return False
while i <maxM or j <maxN:
if i<maxM:
prei=i
i+=1
if j<maxN:
prej=j
j+=1
if matrix[i][j] == val:
return True
if matrix[i][j]>val:
if prei == None or prej==None:
return False
return self.search(matrix,(prei+1,minN),(maxM,j-1),val) or self.search(matrix,(minM,prej+1),(i-1,maxN),val)
return False | search-a-2d-matrix-ii | Can anyone tell me the runtime of my recursive Python solution? | amrmahmoud96 | 1 | 173 | search a 2d matrix ii | 240 | 0.507 | Medium | 4,559 |
https://leetcode.com/problems/search-a-2d-matrix-ii/discuss/2847406/This-Solution-Can-be-used-for-both-Search-matrix-1-and-2 | class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
n,m = len(matrix[0]),len(matrix)
a=False
for i in range(m):
if matrix[i][n-1]<target and matrix[i][0]<target:
continue
else:
for j in range(n):
if matrix[i][j]==target:
a = True
return a | search-a-2d-matrix-ii | This Solution Can be used for both Search matrix 1 and 2 | Navaneeth7 | 0 | 2 | search a 2d matrix ii | 240 | 0.507 | Medium | 4,560 |
https://leetcode.com/problems/search-a-2d-matrix-ii/discuss/2824625/Python3-O(log(m)-%2B-log(n)) | class Solution:
def searchMatrix(self, matrix, target: int):
m, n = len(matrix), len(matrix[0])
# start position
cur_x, cur_y = 0, len(matrix[0])-1
while cur_x >=0 and cur_x < m and cur_y >=0 and cur_y < n:
if matrix[cur_x][cur_y] == target:
return True
# if current value is bigger, search this row
elif matrix[cur_x][cur_y] > target:
low = -1
high = cur_y + 1
while low < high:
mid = (low + high) // 2
# "<=" means matrix[cur_x][low-1] <= target
if matrix[cur_x][mid] <= target:
low = mid + 1
else:
high = mid
cur_y = low - 1
# if current value is smaller, search this column
else:
low = cur_x - 1
high = m
while low < high:
mid = (low + high) // 2
# "<" means matrix[low][cur_y] >= target
if matrix[mid][cur_y] < target:
low = mid + 1
else:
high = mid
cur_x = low
return False | search-a-2d-matrix-ii | Python3 O(log(m) + log(n)) ? | Alex2019 | 0 | 5 | search a 2d matrix ii | 240 | 0.507 | Medium | 4,561 |
https://leetcode.com/problems/search-a-2d-matrix-ii/discuss/2800752/Python3-Simple-6-line-O(n-log-m) | class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
ROWS, COLS = len(matrix), len(matrix[0])
for r in range(ROWS):
c = min(bisect_left(matrix[r], target), COLS-1)
if matrix[r][c] == target:
return True
return False | search-a-2d-matrix-ii | [Python3] Simple 6 line O(n log m) | jonathanbrophy47 | 0 | 2 | search a 2d matrix ii | 240 | 0.507 | Medium | 4,562 |
https://leetcode.com/problems/search-a-2d-matrix-ii/discuss/2727475/Python-recursion. | class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
def helper(i1, j1, i2, j2):
if target < matrix[i1][j1] or target > matrix[i2][j2]:
return False
if i2 - i1 <= 1 and j2 - j1 <= 1:
for i in range(i1, i2 + 1):
for j in range(j1, j2 + 1):
if matrix[i][j] == target:
return True
return False
i_m = (i1 + i2) // 2
j_m = (j1 + j2) // 2
mid = matrix[i_m][j_m]
if mid == target:
return True
if mid < target:
return helper(i1, j_m, i_m, j2) or helper(i_m, j1, i2, j_m) or helper(i_m, j_m, i2, j2)
else:
return helper(i1, j1, i_m, j_m) or helper(i1, j_m, i_m, j2) or helper(i_m, j1, i2, j_m)
m, n = len(matrix), len(matrix[0])
return helper(0, 0, m - 1, n - 1) | search-a-2d-matrix-ii | Python, recursion. | yiming999 | 0 | 4 | search a 2d matrix ii | 240 | 0.507 | Medium | 4,563 |
https://leetcode.com/problems/search-a-2d-matrix-ii/discuss/2673972/Python-3-solution-explained. | class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
cursorY = len(matrix) - 1
cursorX = 0
while (cursorY >= 0) and (cursorX < len(matrix[0])):
if matrix[cursorY][cursorX] > target:
cursorY -= 1
elif matrix[cursorY][cursorX] < target:
cursorX += 1
else:
return True
return False | search-a-2d-matrix-ii | Python 3 solution, explained. | JustARendomGuy | 0 | 5 | search a 2d matrix ii | 240 | 0.507 | Medium | 4,564 |
https://leetcode.com/problems/search-a-2d-matrix-ii/discuss/2673512/Python3-Easy-Code | class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
n=len(matrix)
r=0
c=len(matrix[0])-1
while r<n and c>=0:
ele=matrix[r][c]
if ele==target:
return True
if ele>target:
c-=1
else:
r+=1
return False | search-a-2d-matrix-ii | Python3 Easy Code | pranjalmishra334 | 0 | 31 | search a 2d matrix ii | 240 | 0.507 | Medium | 4,565 |
https://leetcode.com/problems/search-a-2d-matrix-ii/discuss/2654432/faster-than-83-Python3 | class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
res = False
x = 0
y = 0
while y < len(matrix) and matrix[y][0] <= target:
x = 0
while x < len(matrix[0]) and matrix[y][x] <= target:
if matrix[y][x] == target:
res = True
x += 1
y+=1
return res | search-a-2d-matrix-ii | faster than 83% Python3 | egeergull | 0 | 22 | search a 2d matrix ii | 240 | 0.507 | Medium | 4,566 |
https://leetcode.com/problems/search-a-2d-matrix-ii/discuss/2509884/Python-and-Go | class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
for line in matrix:
if target in line:
return True
return False | search-a-2d-matrix-ii | Python and Go答え | namashin | 0 | 25 | search a 2d matrix ii | 240 | 0.507 | Medium | 4,567 |
https://leetcode.com/problems/search-a-2d-matrix-ii/discuss/2496074/Efficient-Python3-Solution-using-BInary-Search | class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
m, n = len(matrix), len(matrix[0])
col = n - 1
for row in range(m):
l, r = 0, col
while l <= r:
mid = (l + r) >> 1
if matrix[row][mid] == target: return True
elif matrix[row][mid] > target: r = mid - 1
else: l = mid + 1
return False | search-a-2d-matrix-ii | Efficient Python3 Solution using BInary Search | priyanshbordia | 0 | 76 | search a 2d matrix ii | 240 | 0.507 | Medium | 4,568 |
https://leetcode.com/problems/search-a-2d-matrix-ii/discuss/2408352/Python3-oror-CPP-oror-Java-oror-O(log-mn)-oror | class Solution:
def searchMatrix(self, nums: List[List[int]], target: int) -> bool:
r, c = len(nums), len(nums[0])
r_idx, c_idx = 0, c-1
while(r_idx < r and c_idx >= 0):
if(nums[r_idx][c_idx] == target): return True
elif(nums[r_idx][c_idx] > target): c_idx -= 1
else : r_idx += 1
return False | search-a-2d-matrix-ii | Python3 || CPP || Java || O(log mn) || | devilmind116 | 0 | 42 | search a 2d matrix ii | 240 | 0.507 | Medium | 4,569 |
https://leetcode.com/problems/search-a-2d-matrix-ii/discuss/2333321/Python3-Solution-or-Using-BinarySearch | class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
def binarySearch(arr):
l = 0
r = len(arr)-1
while l <= r:
mid = (l+r)//2
if arr[mid] == target:
return True
elif arr[mid] < target:
l = mid+1
else:
r = mid-1
return False
for i in range(0,len(matrix)):
exists = binarySearch(matrix[i])
if exists == True:
return True | search-a-2d-matrix-ii | Python3 Solution | Using BinarySearch | arvindchoudhary33 | 0 | 14 | search a 2d matrix ii | 240 | 0.507 | Medium | 4,570 |
https://leetcode.com/problems/search-a-2d-matrix-ii/discuss/2328276/2-line-solution-in-Python-or-Search-a-2D-Matrix-II | class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
res = any(target in sub for sub in matrix)
return res | search-a-2d-matrix-ii | 2 line solution in Python | Search a 2D Matrix II | nishanrahman1994 | 0 | 16 | search a 2d matrix ii | 240 | 0.507 | Medium | 4,571 |
https://leetcode.com/problems/search-a-2d-matrix-ii/discuss/2327708/Python3-oror-Short-code-completed-oror-7-lines | class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j] == target:
return True
break | search-a-2d-matrix-ii | Python3 || Short code completed || 7 lines | hustkrykx | 0 | 3 | search a 2d matrix ii | 240 | 0.507 | Medium | 4,572 |
https://leetcode.com/problems/search-a-2d-matrix-ii/discuss/2327533/Python3-148-ms-faster-than-100.00-of-Python3.-TC-O(m-log(n)) | class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
for row in matrix:
if target < row[0] or target > row[-1]:
continue
if row[bisect_left(row, target)] == target:
return True
return False | search-a-2d-matrix-ii | [Python3] 148 ms, faster than 100.00% of Python3. TC = O(m log(n)) | geka32 | 0 | 11 | search a 2d matrix ii | 240 | 0.507 | Medium | 4,573 |
https://leetcode.com/problems/search-a-2d-matrix-ii/discuss/2327428/Python-Awesome-Diagonal-Search-oror-O(m%2Bn)-oror-Documented | class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
# we will start from top-right corner of the matrix
row = 0; col = len(matrix[0])-1
# check and return True if matched, else move to bottom-left corner
while row < len(matrix) and col >= 0:
if matrix[row][col] == target: return True
# go downward, if element is less than target, else go left side
if matrix[row][col] < target: row += 1
else: col -= 1
return False | search-a-2d-matrix-ii | [Python] Awesome Diagonal Search || O(m+n) || Documented | Buntynara | 0 | 7 | search a 2d matrix ii | 240 | 0.507 | Medium | 4,574 |
https://leetcode.com/problems/search-a-2d-matrix-ii/discuss/2327404/Easy-Double-Loop-Python3-Solution-183ms-(Top-88)-20.3MB-(Top-98) | class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
match=False #Setting the default to False (1)
for i in range(len(matrix)): #2 For loops to go through each element (2)
for j in range(len(matrix[0])):
if matrix[i][j]>target:
break #Break to the next array if the pointer is greater than the target (3)
if matrix[i][j]==target: #If we hit the target switch the match to true and return (4)
match=True
return match
return match | search-a-2d-matrix-ii | Easy Double Loop Python3 Solution 183ms (Top 88%); 20.3MB (Top 98%) | Char1ton | 0 | 12 | search a 2d matrix ii | 240 | 0.507 | Medium | 4,575 |
https://leetcode.com/problems/search-a-2d-matrix-ii/discuss/2326596/PY3-BINARY-SEARCH-EASY-APPROACH-(90-RUNTIME) | class Solution:
def binarySearch(self,target,row,n):
i=0
j=n-1
while i<=j:
mid=(i+j)//2
if row[mid]==target:
return True
elif row[mid]<target:
i=mid+1
else:
j=mid-1
return False
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
n=len(matrix[0])
for row in matrix:
if row[0]>target:
return False
else:
if self.binarySearch(target,row,n):
return True
return False | search-a-2d-matrix-ii | PY3✔ BINARY SEARCH EASY APPROACH✔ (90% RUNTIME)💥 | ChinnaTheProgrammer | 0 | 15 | search a 2d matrix ii | 240 | 0.507 | Medium | 4,576 |
https://leetcode.com/problems/search-a-2d-matrix-ii/discuss/2326275/GoPython-O(m%2Bn)-time-or-O(1)-space | class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
m = len(matrix)
n = len(matrix[0])
i = 0
j = n-1
while 0<=i<m and 0<=j<n:
item = matrix[i][j]
if item == target:
return True
elif item > target:
j-=1
elif item < target:
i+=1
return False | search-a-2d-matrix-ii | Go/Python O(m+n) time | O(1) space | vtalantsev | 0 | 10 | search a 2d matrix ii | 240 | 0.507 | Medium | 4,577 |
https://leetcode.com/problems/search-a-2d-matrix-ii/discuss/2325643/Python-or-Two-solutions-using-Binary-Search-and-Brute-Force-approach | class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
# //////// Brute Force approach TC: O(M*N) ///////
for r in range(len(matrix)):
for c in range(len(matrix[0])):
if matrix[r][c] == target:
return True
return False
# ////////// TC: O(log(m*n)) ///////
m,n = len(matrix),len(matrix[0])
l,r = 0,n-1
while l < m and r >= 0:
num = matrix[l][r]
if num == target:
return True
elif num > target:
r -= 1
else:
l += 1
return False | search-a-2d-matrix-ii | Python | Two solutions using Binary Search and Brute Force approach | __Asrar | 0 | 16 | search a 2d matrix ii | 240 | 0.507 | Medium | 4,578 |
https://leetcode.com/problems/search-a-2d-matrix-ii/discuss/2325442/Using-set-in-Python-only-4-lines-code | class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
for mat in matrix:
m = set(mat)
if target in m:
return True
return False | search-a-2d-matrix-ii | Using set in Python only 4 lines code | ankurbhambri | 0 | 10 | search a 2d matrix ii | 240 | 0.507 | Medium | 4,579 |
https://leetcode.com/problems/search-a-2d-matrix-ii/discuss/2325081/Python3-or-Easy-to-Understand-or-Efficient | class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
for row in matrix:
# apply binary search
if self.binarySearch(row, target):
return True
return False
def binarySearch(self, nums: List[int], t: int) -> bool:
start = 0
end = len(nums) -1
while start <= end:
mid = (end+start)//2
if nums[mid] == t:
return True
if nums[mid] > t:
end = mid - 1
else:
start = mid + 1
return False | search-a-2d-matrix-ii | ✅Python3 | Easy to Understand | Efficient | thesauravs | 0 | 10 | search a 2d matrix ii | 240 | 0.507 | Medium | 4,580 |
https://leetcode.com/problems/search-a-2d-matrix-ii/discuss/2258993/Python3-or-Bidirectional-Binary-Search-or-Intuitive-and-Easy-to-Understand | class Solution:
found = False
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
def recurse(lo, hi, arr):
mid = (lo + hi) // 2
if arr[mid] == target:
self.found = True
return
if lo >= hi:
return
if arr[mid] < target:
recurse(mid+1, hi, arr)
else:
recurse(lo, mid-1, arr)
x = 0 # current row
y = 0 # current col
while x < len(matrix) and y < len(matrix[0]) :
if self.found:
break
h = matrix[x][y:]
v = [matrix[_x][y] for _x in range(x, len(matrix))]
recurse(0, len(h)-1, h)
recurse(0, len(v)-1, v)
x += 1
y += 1
return self.found | search-a-2d-matrix-ii | Python3 | Bidirectional Binary Search | Intuitive and Easy to Understand | Ahbar | 0 | 53 | search a 2d matrix ii | 240 | 0.507 | Medium | 4,581 |
https://leetcode.com/problems/search-a-2d-matrix-ii/discuss/2194381/Python-Faster-than-99.86-oror-Easy-Solution | class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
matrix=filter(lambda x: x[0]<=target and x[len(x)-1]>=target ,matrix)
for i in matrix:
if target in i:
return True
return False | search-a-2d-matrix-ii | Python Faster than 99.86% || Easy Solution | deshkarmm | 0 | 54 | search a 2d matrix ii | 240 | 0.507 | Medium | 4,582 |
https://leetcode.com/problems/search-a-2d-matrix-ii/discuss/2152357/Python-oneliner | class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
return True if [x for x in matrix for x in x if x == target] else False | search-a-2d-matrix-ii | Python oneliner | StikS32 | 0 | 25 | search a 2d matrix ii | 240 | 0.507 | Medium | 4,583 |
https://leetcode.com/problems/search-a-2d-matrix-ii/discuss/2110576/Python-or-Two-different-Solution-95-faster | class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
# /////// Solution 1 /////////////
# //////// Brute Force approach TC: O(M*N) ///////
for r in range(len(matrix)):
for c in range(len(matrix[0])):
if matrix[r][c] == target:
return True
return False
# /////// Solution 2 //////////
# ////////// TC: O(log(m*n)) ///////
m,n = len(matrix),len(matrix[0])
l,r = 0,n-1
while l < m and r >= 0:
num = matrix[l][r]
if num == target:
return True
elif num > target:
r -= 1
else:
l += 1
return False | search-a-2d-matrix-ii | Python | Two different Solution 95% faster | __Asrar | 0 | 69 | search a 2d matrix ii | 240 | 0.507 | Medium | 4,584 |
https://leetcode.com/problems/search-a-2d-matrix-ii/discuss/2057735/Python-or-Simple-solution | class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
for row in matrix:
if target in row:
return True
else:
return False | search-a-2d-matrix-ii | Python | Simple solution | manikanthgoud123 | 0 | 43 | search a 2d matrix ii | 240 | 0.507 | Medium | 4,585 |
https://leetcode.com/problems/search-a-2d-matrix-ii/discuss/1961689/Easy-Python-Solution-with-Explanation | class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
# determine the rows and columns in a matrix
rows = len(matrix)
cols = len(matrix[0])
def searchTarget(row,col):
while row >=0 and col<cols:
# print(row,cols, matrix[row][col])
if target == matrix[row][col]:
return True
elif target < matrix[row][col]:
row -= 1
elif target > matrix[row][col]:
col += 1
return False
# Start search from the bottom left of the matrix as all the digits will be in ascending order
return searchTarget(rows-1, 0) | search-a-2d-matrix-ii | Easy Python Solution - with Explanation | palakmehta | 0 | 80 | search a 2d matrix ii | 240 | 0.507 | Medium | 4,586 |
https://leetcode.com/problems/search-a-2d-matrix-ii/discuss/1945174/Python-(Simple-Approach-and-Beginner-Friendly) | class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
whole = []
for i in matrix:
for j in i:
whole.append(j)
if target in whole:
return True
else:
return False | search-a-2d-matrix-ii | Python (Simple Approach and Beginner-Friendly) | vishvavariya | 0 | 35 | search a 2d matrix ii | 240 | 0.507 | Medium | 4,587 |
https://leetcode.com/problems/search-a-2d-matrix-ii/discuss/1897616/Python-beginner-Friendly-(BS) | class Solution:
def binarysrc(self,arr,k):
l=0
r=len(arr)-1
while l<=r:
m=(l+r)//2
if arr[m]==k:
return m
elif k>arr[m]:
l=m+1
else:
r=m-1
else:
return -1
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
for i in range(len(matrix)):
if target>=matrix[i][0] and target<=matrix[i][-1]:
if self.binarysrc(matrix[i],target)!=-1:
return True
return False | search-a-2d-matrix-ii | Python beginner Friendly (BS) | imamnayyar86 | 0 | 70 | search a 2d matrix ii | 240 | 0.507 | Medium | 4,588 |
https://leetcode.com/problems/different-ways-to-add-parentheses/discuss/2392799/Python3-Divide-and-Conquer%3A-Recursion-%2B-Memoization | class Solution(object):
def diffWaysToCompute(self, s, memo=dict()):
if s in memo:
return memo[s]
if s.isdigit(): # base case
return [int(s)]
calculate = {'*': lambda x, y: x * y,
'+': lambda x, y: x + y,
'-': lambda x, y: x - y
}
result = []
for i, c in enumerate(s):
if c in '+-*':
left = self.diffWaysToCompute(s[:i], memo)
right = self.diffWaysToCompute(s[i+1:], memo)
for l in left:
for r in right:
result.append(calculate[c](l, r))
memo[s] = result
return result | different-ways-to-add-parentheses | [Python3] Divide and Conquer: Recursion + Memoization | mhpd | 4 | 156 | different ways to add parentheses | 241 | 0.633 | Medium | 4,589 |
https://leetcode.com/problems/different-ways-to-add-parentheses/discuss/1719419/Python-or-Recursive-or-Concise-Solution | class Solution:
def diffWaysToCompute(self, expression: str) -> List[int]:
ops = {
"+": lambda x, y : x + y,
"-": lambda x, y : x - y,
"*": lambda x, y : x * y
}
res = []
for x, char in enumerate(expression):
if char in ops:
leftResults = self.diffWaysToCompute(expression[:x])
rightResults = self.diffWaysToCompute(expression[x + 1:])
for leftNum in leftResults:
for rightNum in rightResults:
res.append(ops[char](leftNum, rightNum))
# no operations means expression is a sole number
if not res:
res.append(int(expression))
return res | different-ways-to-add-parentheses | Python | Recursive | Concise Solution | srihariv | 4 | 233 | different ways to add parentheses | 241 | 0.633 | Medium | 4,590 |
https://leetcode.com/problems/different-ways-to-add-parentheses/discuss/1469756/Python-or-99.7-(20ms)-or-Recursion-%2B-Memo-or-Clean-and-Concise | class Solution:
def diffWaysToCompute(self, expression: str) -> List[int]:
nums = '0123456789'
def op(a, b, c):
if c == '+':
return a + b
elif c == '-':
return a - b
else:
return a * b
@lru_cache(None)
def func(l, r):
if l == r:
return [expression[l]]
elif l > r:
return []
this = []
went = 0
for i in range(l, r + 1):
if expression[i] not in nums:
went = 1
left = func(l, i - 1)
right = func(i + 1, r)
for leftvals in left:
for rightvals in right:
temp = op(int(leftvals), int(rightvals), expression[i])
#print(temp)
this.append(temp)
if went:
return this
else:
return [expression[l: r + 1]]
arr = func(0, len(expression) - 1)
#print(arr)
return arr | different-ways-to-add-parentheses | Python | 99.7% (20ms) | Recursion + Memo | Clean and Concise | detective_dp | 3 | 819 | different ways to add parentheses | 241 | 0.633 | Medium | 4,591 |
https://leetcode.com/problems/different-ways-to-add-parentheses/discuss/605583/Simple-divide-and-conquer-solution-Python | class Solution:
def diffWaysToCompute(self, input: str) -> List[int]:
def helper(string):
result=[]
for i, c in enumerate(string):
if c in "+-*":
x=helper(string[:i])
y=helper(string[i+1:])
for a in x:
for b in y:
if c=='+':
result.append(a+b)
elif c=='-':
result.append(a-b)
else:
result.append(a*b)
if not result:
return [int(string)]
return result
return helper(input) | different-ways-to-add-parentheses | Simple divide and conquer solution Python | Ayu-99 | 3 | 286 | different ways to add parentheses | 241 | 0.633 | Medium | 4,592 |
https://leetcode.com/problems/different-ways-to-add-parentheses/discuss/2425384/Detailed-Python-solution-with-comments. | class Solution(object):
def diffWaysToCompute(self, expression):
res=[]
def fn(s,memo={}):
res=[]
if s in memo:
return memo[s]
if s.isdigit():
return [int(s)] #if string containsonly numbers return that
syms=['-','+','*','/']
for i in range(len(s)):
symbol=s[i]
if s[i] in syms: #if the character is a operator
left=fn(s[:i],memo) #possible values from left
right=fn(s[i+1:],memo) #possible values from right
for l in left: #Using nested for loops, calculate all possible combinations of left and right values applying exp[i] operator
for r in right:
if symbol=='+':
res.append(l+r)
elif symbol=='-':
res.append(l-r)
elif symbol=='*':
res.append(l*r)
else:
res.append(l//r)
memo[s]=res
return res
return fn(expression) | different-ways-to-add-parentheses | Detailed Python solution with comments. | babashankarsn | 1 | 147 | different ways to add parentheses | 241 | 0.633 | Medium | 4,593 |
https://leetcode.com/problems/different-ways-to-add-parentheses/discuss/2205910/Python-Memoization-Solution | class Solution:
def diffWaysToCompute(self, expression: str) -> List[int]:
def clac(a, b, operator):
if operator == "+": return a + b
if operator == "-": return a - b
if operator == "*": return a * b
memo = {}
def solve(expr):
if expr.isdigit(): return [int(expr)]
if expr in memo: return memo[expr]
res = []
for i in range(len(expr)):
if expr[i] in "+-*":
left = solve(expr[:i])
right = solve(expr[i+1:])
for a in left:
for b in right:
res.append(clac(a, b, expr[i]))
memo[expr] = res
return memo[expr]
return solve(expression) | different-ways-to-add-parentheses | [Python] Memoization Solution | samirpaul1 | 1 | 95 | different ways to add parentheses | 241 | 0.633 | Medium | 4,594 |
https://leetcode.com/problems/different-ways-to-add-parentheses/discuss/1927153/Python-easy-to-read-and-understand-or-recursion-memoization | class Solution:
def solve(self, s):
if s.isdigit():
return [int(s)]
ans = []
for i in range(len(s)):
if s[i] in ["+", "-", "*"]:
left = self.solve(s[:i])
right = self.solve(s[i + 1:])
for l in left:
for r in right:
if s[i] == "-": ans.append(l - r)
if s[i] == "+": ans.append(l + r)
if s[i] == "*": ans.append(l * r)
return ans
def diffWaysToCompute(self, expression: str) -> List[int]:
return self.solve(expression) | different-ways-to-add-parentheses | Python easy to read and understand | recursion-memoization | sanial2001 | 1 | 307 | different ways to add parentheses | 241 | 0.633 | Medium | 4,595 |
https://leetcode.com/problems/different-ways-to-add-parentheses/discuss/1927153/Python-easy-to-read-and-understand-or-recursion-memoization | class Solution:
def solve(self, s):
if s.isdigit():
return [int(s)]
if s in self.d:
return self.d[s]
ans = []
for i in range(len(s)):
if s[i] in ["+", "-", "*"]:
left = self.solve(s[:i])
right = self.solve(s[i+1:])
for l in left:
for r in right:
if s[i] == "-": ans.append(l-r)
if s[i] == "+": ans.append(l+r)
if s[i] == "*": ans.append(l*r)
self.d[s] = ans
return ans
def diffWaysToCompute(self, expression: str) -> List[int]:
self.d = {}
return self.solve(expression) | different-ways-to-add-parentheses | Python easy to read and understand | recursion-memoization | sanial2001 | 1 | 307 | different ways to add parentheses | 241 | 0.633 | Medium | 4,596 |
https://leetcode.com/problems/different-ways-to-add-parentheses/discuss/764006/Python3-dp | class Solution:
def diffWaysToCompute(self, input: str) -> List[int]:
#pre-processing to tokenize input
tokens = re.split(r'(\D)', input)
mp = {"+": add, "-": sub, "*": mul}
for i, token in enumerate(tokens):
if token.isdigit(): tokens[i] = int(token)
else: tokens[i] = mp[token]
@lru_cache(None)
def fn(lo, hi):
"""Return possible outcomes of tokens[lo:hi]"""
if lo+1 == hi: return [tokens[lo]]
ans = []
for mid in range(lo+1, hi, 2):
ans.extend(tokens[mid](x, y) for x in fn(lo, mid) for y in fn(mid+1, hi))
return ans
return fn(0, len(tokens)) | different-ways-to-add-parentheses | [Python3] dp | ye15 | 1 | 410 | different ways to add parentheses | 241 | 0.633 | Medium | 4,597 |
https://leetcode.com/problems/different-ways-to-add-parentheses/discuss/2848618/Divide-and-Conquer | class Solution:
def diffWaysToCompute(self, expression: str) -> List[int]:
res=[]
for i in range(len(expression)):
if expression[i] in ["+","-","*"]:
left=self.diffWaysToCompute(expression[:i])
right=self.diffWaysToCompute(expression[i+1:])
for x in left:
for y in right:
res.append(eval(str(x)+expression[i]+str(y)))
if not res:
res.append(int(expression))
return res | different-ways-to-add-parentheses | Divide and Conquer | lillllllllly | 0 | 1 | different ways to add parentheses | 241 | 0.633 | Medium | 4,598 |
https://leetcode.com/problems/different-ways-to-add-parentheses/discuss/2834445/Python-recursive-solution | class Solution:
def __init__(self):
self.result = []
def diffWaysToCompute(self, expression: str) -> List[int]:
n = len(expression)
signs = []
nums = []
num = 0
for i in range(n):
if expression[i] in "+-*":
signs.append(expression[i])
else:
num = num * 10 + ord(expression[i]) - ord('0')
if i < n - 1 and expression[i + 1] in "+-*":
nums.append(num)
num = 0
elif i == n - 1:
nums.append(num)
def calculate(x, y, sign):
if sign == "+":
return x + y
if sign == "-":
return x - y
if sign == "*":
return x * y
def dfs(signs, nums):
if len(nums) == 1:
return [nums[0]]
res = []
for i in range(len(signs)):
left = dfs(signs[:i], nums[:i + 1])
right = dfs(signs[i + 1:], nums[i + 1:])
for l in left:
for r in right:
res.append(calculate(l, r, signs[i]))
return res
return dfs(signs, nums) | different-ways-to-add-parentheses | Python recursive solution | SiciliaLeco | 0 | 5 | different ways to add parentheses | 241 | 0.633 | Medium | 4,599 |
Subsets and Splits