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/find-k-closest-elements/discuss/718685/Python3-two-solutions-Find-K-Closest-Elements | class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
class Wrapper:
def __getitem__(self, i):
hi = bisect.bisect(arr, x+i)
lo = bisect.bisect_left(arr, x-i)
return hi - lo
r = bisect.bisect_left(Wrapper(), k, 1, max(arr[-1]-x, x-arr[0]))
hi = bisect.bisect(arr, x+r)
lo = bisect.bisect_left(arr, x-r)
ans = arr[lo:hi]
i, j = 0, len(ans)-1
while i + k < j + 1:
if x - ans[i] > ans[j] - x:
i += 1
elif x - ans[i] <= ans[j] - x:
j -= 1
return ans[i:j+1] | find-k-closest-elements | Python3 two solutions - Find K Closest Elements | r0bertz | 1 | 453 | find k closest elements | 658 | 0.468 | Medium | 11,000 |
https://leetcode.com/problems/find-k-closest-elements/discuss/419596/Easy-to-understand-python3-solution | class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
# left pointer and right pointer
i, j = 0, len(arr)-1
while j-i+1 != k:
# will stop once we have k elements
# else keep shifting pointers towards minimum difference
left_diff = abs(arr[i] - x)
right_diff = abs(arr[j] - x)
if left_diff > right_diff:
i += 1
else:
j -= 1
return arr[i:j+1] | find-k-closest-elements | Easy to understand python3 solution | ujjwalg3 | 1 | 304 | find k closest elements | 658 | 0.468 | Medium | 11,001 |
https://leetcode.com/problems/find-k-closest-elements/discuss/2843006/python3-one-pass-O(n) | class Solution:
# think this is pretty much self explanatory
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
res, i = [], 0
for n in arr:
if k: res.append(n); k -= 1
elif res[i] == n or abs(res[i] - x) > abs(n - x):
res.append(n); i += 1
else: break
return res[i:] | find-k-closest-elements | python3 one pass O(n) | tinmanSimon | 0 | 2 | find k closest elements | 658 | 0.468 | Medium | 11,002 |
https://leetcode.com/problems/find-k-closest-elements/discuss/2819455/Python-or-Easy-or-Explained | class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
l, r = 0, len(arr) - 1
while(r - l >= k):
if(abs(x - arr[l] <= abs(x - arr[r]))):
r -= 1
else:
l += 1
result = []
for i in range(l, r + 1):
result.append(arr[l])
l += 1
return result | find-k-closest-elements | Python | Easy | Explained | rahul_mishra_ | 0 | 3 | find k closest elements | 658 | 0.468 | Medium | 11,003 |
https://leetcode.com/problems/find-k-closest-elements/discuss/2812779/Took-the-answer-and-came-up-with-something-I-could-make-sense-of. | class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
left = 0
right = len(arr) - k
out = -1
while left <= right:
mid = left + (right - left)//2
left_val = arr[mid] if mid < len(arr) else float("INF")
right_val = arr[mid+k] if (mid+k) < len(arr) else float("INF")
if x - left_val<= right_val - x:
out = mid
right = mid-1
else:
left = mid+1
return arr[out:out+k] | find-k-closest-elements | Took the answer and came up with something I could make sense of. | brownesc | 0 | 3 | find k closest elements | 658 | 0.468 | Medium | 11,004 |
https://leetcode.com/problems/find-k-closest-elements/discuss/2779089/Python-or-Easy | class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
a=len(arr)
start=0
end=a-1
y=a-k
while(y>0):
if abs(x-arr[start])<=abs(x-arr[end]):
end-=1
else:
start+=1
y-=1
lst=[0]*k
for i in range(start,end+1):
lst[i-start]=arr[i]
return lst | find-k-closest-elements | Python | Easy | Chetan_007 | 0 | 3 | find k closest elements | 658 | 0.468 | Medium | 11,005 |
https://leetcode.com/problems/find-k-closest-elements/discuss/2764468/Python-3-or-O(logN%2Bk)or-O(1)-approach-or-Well-explained | class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
l,h=0,len(arr)-1
while True:
mid=(l+h)//2
if l>=h or arr[mid]==x:
if l==h and arr[mid]<x:
arr.insert(mid+1,x)
mid+=1
else: arr.insert(mid,x)
break
elif arr[mid]>x:h=mid-1
else: l=mid+1
print(arr)
a,b=mid-1,mid+1
ele=[]
while k and (a>=0 or b<len(arr)):
aval=arr[a] if a>=0 else sys.maxsize
bval=arr[b] if b<len(arr) else sys.maxsize
choose= a if abs(aval-x)<abs(bval-x) or abs(aval-x)==abs(bval-x) and aval<bval else b
print(a,b,choose)
if a==choose:
ele.insert(0,arr[a])
a-=1
else:
ele.append(arr[b])
b+=1
k-=1
return sorted(ele) | find-k-closest-elements | Python 3 | O(logN+k)| O(1) approach | Well explained | saa_73 | 0 | 5 | find k closest elements | 658 | 0.468 | Medium | 11,006 |
https://leetcode.com/problems/find-k-closest-elements/discuss/2747668/Python3-Binary-Search-(with-comments) | class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
i = bisect_left(arr, x) # binary search, O(log n)
# handle cases where x not in arr
if i == len(arr) or (i-1 >= 0 and abs(arr[i-1]-x) <= abs(arr[i]-x)):
i -= 1
l, r = i, i
res = deque([]) # linked list implementation, O(1) left/right append
while k:
# initial position
if l == r:
res.appendleft(arr[l])
l -= 1
r += 1
# only elements to the right remain
elif l < 0:
res.append(arr[r])
r += 1
# only elements to the left remain
elif r == len(arr):
res.appendleft(arr[l])
l -= 1
# select left or right, depending on which number is smaller
else:
if abs(arr[l]-x) <= abs(arr[r]-x):
res.appendleft(arr[l])
l -= 1
else:
res.append(arr[r])
r += 1
k -= 1
return res | find-k-closest-elements | Python3 Binary Search (with comments) | jonathanbrophy47 | 0 | 4 | find k closest elements | 658 | 0.468 | Medium | 11,007 |
https://leetcode.com/problems/find-k-closest-elements/discuss/2706546/python-working-solution | class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
l = 0
diff = 0
ans = [float('inf') ,0,len(arr)-1]
for r in range(len(arr)):
diff+=(abs(arr[r] - x))
if (r+1)>=k:
if ans[0] > diff:
ans[1]=l
ans[2]=r
ans[0] = diff
diff-=(abs(arr[l] - x))
l+=1
return arr[ans[1]:ans[2]+1] | find-k-closest-elements | python working solution | Sayyad-Abdul-Latif | 0 | 5 | find k closest elements | 658 | 0.468 | Medium | 11,008 |
https://leetcode.com/problems/find-k-closest-elements/discuss/2677548/python3or-easy | class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
# preprocessing of the difference
arr2 = [None]*len(arr)
for i in range(len(arr)):
arr2[i] = abs(arr[i]-x)
# sliding window
i = 0
j = 0
while j<len(arr):
if j-i<k:
j+=1
else:
if arr2[j]<arr2[i] or arr[j]<=arr[i]:
i+=1
j+=1
else:
break
return arr[i:j] | find-k-closest-elements | python3| easy | rohannayar8 | 0 | 33 | find k closest elements | 658 | 0.468 | Medium | 11,009 |
https://leetcode.com/problems/find-k-closest-elements/discuss/2664919/pyhton-log(n)-binary-search-method | class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
l = 0
r = len(arr) - k
while l < r:
m = l + (r - l)//2
if x - arr[m] > arr[m + k] - x:
l = m + 1
else:
r = m
return arr[l:l+k] | find-k-closest-elements | pyhton log(n) binary search method | sahilkumar158 | 0 | 7 | find k closest elements | 658 | 0.468 | Medium | 11,010 |
https://leetcode.com/problems/find-k-closest-elements/discuss/2649484/Python-Solution | class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
st=0
siz=len(arr)
en=siz-1
y=set(arr)
if arr[0]>x:
i=0
elif arr[-1]<x:
i=siz-1
else:
while st<=en:
mid=st+(en-st)//2
if arr[mid]==x:
i=mid
break
elif arr[mid]<x:
st=mid+1
else:
en=mid-1
i=mid
if x not in y and k==1 and i==0 and siz>1:
return [arr[1]]
print(i)
l=i-(x not in y)
r=i
a=deque()
while k:
#print(l,r,a)
if l<0:
a.extend(arr[r:r+k])
break
if r>siz-1:
if k>l: a.extendleft(arr[:l+1][::-1]);break
if l-k+1==1: a.appendleft(arr[1]);break
a.extendleft(arr[l-(k-1):l+1][::-1])
break
if l==i:
a.append(arr[i])
l-=1
r+=1
else:
if x-arr[l]>arr[r]-x:
a.append(arr[r])
#print("h")
r+=1
else:
a.appendleft(arr[l])
l-=1
k-=1
return list(a) | find-k-closest-elements | Python Solution | sci94tune | 0 | 2 | find k closest elements | 658 | 0.468 | Medium | 11,011 |
https://leetcode.com/problems/find-k-closest-elements/discuss/2640877/Python-2-pointer-solution | class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
left = 0
right = len(arr) - 1
while right - left + 1 != k:
left_dif = abs(arr[left] - x)
right_dif = abs(arr[right] - x)
if left_dif < right_dif:
right -= 1
elif right_dif < left_dif:
left += 1
elif arr[right] > arr[left]:
right -= 1
else:
left += 1
return arr[left:right+1] | find-k-closest-elements | Python 2 pointer solution | chingisoinar | 0 | 2 | find k closest elements | 658 | 0.468 | Medium | 11,012 |
https://leetcode.com/problems/find-k-closest-elements/discuss/2640553/One-Line-Simple-and-easy-to-understand-Python-Solution | class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
return sorted(sorted(arr,key=lambda i:abs(i-x))[:k]) | find-k-closest-elements | One Line Simple and easy to understand Python Solution | afrinmahammad | 0 | 4 | find k closest elements | 658 | 0.468 | Medium | 11,013 |
https://leetcode.com/problems/find-k-closest-elements/discuss/2640332/Binary-search-and-then-scan-with-two-points-in-O(k)-short-python-soluton | class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
p = bisect_left(arr, x)
q = p
while q - p < k and p > 0 and q < len(arr):
if x - arr[p-1] <= arr[q] - x:
p -= 1
else:
q += 1
if p == 0:
return arr[:k]
if q == len(arr):
return arr[-k:]
return arr[p:p+k] | find-k-closest-elements | Binary search and then scan with two points in O(k), short python soluton | metaphysicalist | 0 | 44 | find k closest elements | 658 | 0.468 | Medium | 11,014 |
https://leetcode.com/problems/find-k-closest-elements/discuss/2639980/python-9581-shrinking-window | class Solution:
# Find idx where x SHOULD belong in the array
def makeidx(self, x, arr):
for i, n in enumerate(arr):
if n > x:
return i
return i
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
xidx = self.makeidx(x, arr)
bigidx = min(xidx + k, len(arr) - 1)
smlidx = max(xidx - k, 0)
while bigidx - smlidx >= k:
# if bottom end is further from x than top end
if x - arr[smlidx] > arr[bigidx] - x:
# shrink away bottom end in favour of top end
smlidx += 1
else:
bigidx -= 1
return arr[smlidx : bigidx + 1] | find-k-closest-elements | python 95%/81%, shrinking window | jsv | 0 | 26 | find k closest elements | 658 | 0.468 | Medium | 11,015 |
https://leetcode.com/problems/find-k-closest-elements/discuss/2639244/Sliding-Binary-Search-or-Python-or-99%2B-Speed | class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
# if len(arr) == k, solution is arr
if len(arr) == k:
return arr
# We want to search with a window, not for a specific point
l, r = 0, len(arr) - k
mid = 0
while l < r:
mid = (l + r) // 2
print(l, mid, r)
#we want to line up mid with the ideal left for our window
if (x - arr[mid]) > (arr[mid + k] - x):
l = mid + 1
else:
r = mid
#return the window we have been working with
return arr[l: l + k] | find-k-closest-elements | Sliding Binary Search | Python | 99%+ Speed | AlgosWithDylan | 0 | 155 | find k closest elements | 658 | 0.468 | Medium | 11,016 |
https://leetcode.com/problems/find-k-closest-elements/discuss/2638976/Python3-Scan-Line-%2B-Two-Pointer-O(2-*-10-**-4-%2B-k-*-log(k)) | class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
c = Counter(arr)
repeat = c.get(x, 0)
res = [x] * min(repeat, k)
l = x - 1
r = x + 1
while l >= -(10 ** 4) or r <= 10 ** 4:
if len(res) >= k:
break
repeat = c.get(l, 0)
res = res + [l] * repeat
repeat = c.get(r, 0)
res = res + [r] * repeat
l -= 1
r += 1
return sorted(res[0:k]) | find-k-closest-elements | Python3 Scan Line + Two Pointer O(2 * 10 ** 4 + k * log(k)) | MenheraCapoo | 0 | 41 | find k closest elements | 658 | 0.468 | Medium | 11,017 |
https://leetcode.com/problems/find-k-closest-elements/discuss/2636980/Python-solution-using-bisect-and-a-while-loop | class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
i = bisect_left(arr, x)
li = []
right_i = i
left_i = i - 1
while len(li) < k:
if left_i < 0:
li.append(arr[right_i])
right_i += 1
elif right_i >= len(arr):
li.append(arr[left_i])
left_i -= 1
else:
right_v = abs(arr[right_i] - x)
left_v = abs(arr[left_i] - x)
if right_v < left_v:
li.append(arr[right_i])
right_i += 1
else:
li.append(arr[left_i])
left_i -= 1
li.sort()
return li | find-k-closest-elements | Python solution using bisect and a while loop | samanehghafouri | 0 | 30 | find k closest elements | 658 | 0.468 | Medium | 11,018 |
https://leetcode.com/problems/find-k-closest-elements/discuss/2636692/python3-simple-one-liner | class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
return sorted(sorted(arr, key=lambda n:abs(n-x))[:k]) | find-k-closest-elements | python3 simple one-liner | leetavenger | 0 | 58 | find k closest elements | 658 | 0.468 | Medium | 11,019 |
https://leetcode.com/problems/find-k-closest-elements/discuss/2636604/Python-or-One-line-readable-nested-sort | class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
return sorted(sorted(arr, key = lambda y: (abs(x - y), y))[0:k]) | find-k-closest-elements | Python | One-line readable nested sort | sr_vrd | 0 | 4 | find k closest elements | 658 | 0.468 | Medium | 11,020 |
https://leetcode.com/problems/find-k-closest-elements/discuss/2636570/Python-binary-search-%2B-expansion-around-the-number.-Time%3A-O(log-N)-%2B-O(k) | class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
result = deque()
i = bisect_left(arr, x)
left = i - 1
right = i
for _ in range(k):
if left >= 0 and (right >= len(arr) or x - arr[left] <= arr[right] - x):
result.appendleft(arr[left])
left -= 1
else:
result.append(arr[right])
right += 1
return result | find-k-closest-elements | Python, binary search + expansion around the number. Time: O(log N) + O(k) | blue_sky5 | 0 | 44 | find k closest elements | 658 | 0.468 | Medium | 11,021 |
https://leetcode.com/problems/find-k-closest-elements/discuss/2630198/Python-clean-heapq-solution | class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
diff = [abs(num - x) for num in arr]
# zip diff and arr to list of tuple [(diff[0], arr[0]), (diff[1], arr[1]), (diff[2], arr[2])...]
h = list(zip(diff, arr))
ret = heapq.nsmallest(k, h, key=lambda x: x[0])
return sorted([i[1] for i in ret] | find-k-closest-elements | Python clean heapq solution | amikai | 0 | 21 | find k closest elements | 658 | 0.468 | Medium | 11,022 |
https://leetcode.com/problems/find-k-closest-elements/discuss/2549807/Python3-Easy-Heap-solution-Beginner-Friendly | class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
li=[]
ans=[]
for i in range(len(arr)):
diff=abs(arr[i]-x)
heapq.heappush(li,[diff,arr[i]])
for i in range(k):
diff,val=heapq.heappop(li)
ans.append(val)
ans.sort()
return ans | find-k-closest-elements | Python3 Easy Heap solution Beginner Friendly | pranjalmishra334 | 0 | 35 | find k closest elements | 658 | 0.468 | Medium | 11,023 |
https://leetcode.com/problems/split-array-into-consecutive-subsequences/discuss/2446738/Python-524ms-98.3-Faster-Multiple-solutions-94-memory-efficient | class Solution:
def isPossible(self, nums: List[int]) -> bool:
len1 = len2 = absorber = 0
prev_num = nums[0] - 1
for streak_len, streak_num in Solution.get_streaks(nums):
if streak_num == prev_num + 1:
spillage = streak_len - len1 - len2
if spillage < 0:
return False
absorber = min(absorber, spillage)
len1, len2, absorber = spillage - absorber, len1, absorber + len2
else:
if len1 or len2:
return False
absorber = 0
prev_num = streak_num
return len1 == len2 == 0
@staticmethod
def get_streaks(nums: List[int]):
streak_num = nums[0]
streak_len = 0
for num in nums:
if num == streak_num:
streak_len += 1
else:
yield streak_len, streak_num
streak_num = num
streak_len = 1
yield streak_len, streak_num | split-array-into-consecutive-subsequences | Python 524ms 98.3% Faster Multiple solutions 94% memory efficient | anuvabtest | 44 | 2,900 | split array into consecutive subsequences | 659 | 0.506 | Medium | 11,024 |
https://leetcode.com/problems/split-array-into-consecutive-subsequences/discuss/2446738/Python-524ms-98.3-Faster-Multiple-solutions-94-memory-efficient | class Solution:
def isPossible(self, nums: List[int]) -> bool:
counter = collections.Counter(nums)
for i in sorted(counter.keys()):
while counter[i] > 0:
last = 0
j = i
k = 0
while counter[j] >= last:
last = counter[j]
counter[j] -= 1
j += 1
k += 1
if k < 3:
return False
return True | split-array-into-consecutive-subsequences | Python 524ms 98.3% Faster Multiple solutions 94% memory efficient | anuvabtest | 44 | 2,900 | split array into consecutive subsequences | 659 | 0.506 | Medium | 11,025 |
https://leetcode.com/problems/split-array-into-consecutive-subsequences/discuss/2446738/Python-524ms-98.3-Faster-Multiple-solutions-94-memory-efficient | class Solution:
def isPossible(self, nums: List[int]) -> bool:
if len(nums) < 3: return False
frequency = collections.Counter(nums)
subsequence = collections.defaultdict(int)
for i in nums:
if frequency[i] == 0:
continue
frequency[i] -= 1
# option 1 - add to an existing subsequence
if subsequence[i-1] > 0:
subsequence[i-1] -= 1
subsequence[i] += 1
# option 2 - create a new subsequence
elif frequency[i+1] and frequency[i+2]:
frequency[i+1] -= 1
frequency[i+2] -= 1
subsequence[i+2] += 1
else:
return False
return True
# TC: O(n), SC: O(n) | split-array-into-consecutive-subsequences | Python 524ms 98.3% Faster Multiple solutions 94% memory efficient | anuvabtest | 44 | 2,900 | split array into consecutive subsequences | 659 | 0.506 | Medium | 11,026 |
https://leetcode.com/problems/split-array-into-consecutive-subsequences/discuss/485075/Greedy-approach-with-proof-of-validity-and-explanation-in-Python3 | class Solution:
def isPossible(self, nums: List[int]) -> bool:
if len(nums) < 3: return False
freqs = Counter(nums)
tails = Counter()
for num in nums:
# if the number already has a place in a sequence
if freqs[num] == 0:
continue
# if the number may be placed as a continuation of another sequence
elif tails[num] > 0:
tails[num] -= 1
tails[num + 1] += 1
# the number is not consecutive to a previous sequence
# a new sequence must be created
elif freqs[num + 1] > 0 and freqs[num + 2] > 0:
freqs[num + 1] -= 1
freqs[num + 2] -= 1
tails[num + 3] += 1
# if the number cannot continue a new sequence
# and cannot begin a new sequence then the list
# cannot be split
else:
return False
freqs[num] -= 1
return True | split-array-into-consecutive-subsequences | Greedy approach with proof of validity and explanation in Python3 | ThatTallProgrammer | 5 | 647 | split array into consecutive subsequences | 659 | 0.506 | Medium | 11,027 |
https://leetcode.com/problems/split-array-into-consecutive-subsequences/discuss/2448040/Greedy-queue-solution-O(n)-time-O(n)-space | class Solution:
def isPossible(self, nums) -> bool:
q = collections.deque([[nums[0]]])
for i in range(1,len(nums)):
if q[-1][-1] == nums[i]:
q.append([nums[i]])
continue
cur = q.pop()
while nums[i] > cur[-1]+1:
if len(cur) < 3: return False
if len(q) > 0: cur = q.pop()
else:
cur = []
break
cur.append(nums[i])
q.appendleft(cur)
while q:
if len(q.pop()) < 3: return False
return True | split-array-into-consecutive-subsequences | Greedy queue solution, O(n) time, O(n) space | TimGrimbergen | 1 | 50 | split array into consecutive subsequences | 659 | 0.506 | Medium | 11,028 |
https://leetcode.com/problems/split-array-into-consecutive-subsequences/discuss/2447979/python3-or-explained-or-easy-to-understand-or-Dictionary | class Solution:
def isPossible(self, nums: List[int]) -> bool:
d={} # to find the frequency of each element
for e in nums:
d[e] = d.get(e, 0)+1
dt={} # to keep track of num to be added
for num in nums:
if d.get(num, 0) == 0: # if the number is not present
continue
elif dt.get(num, 0) > 0: # if num can be appended into any existing sequence
dt[num] -= 1 # as number is added, so not able to add in that sequence again
dt[num+1] = dt.get(num+1, 0)+1 # now num+1 can be appended to the sequence
elif d.get(num+1, 0) > 0 and d.get(num+2, 0) > 0: # if number is not appendable then checking it to create new sequence
d[num+1]-=1 # if new sequence is possible then remove on occurance of num
d[num+2]-=1
dt[num+3] = dt.get(num+3, 0)+1 # expected next num for new sequence
else:
return False
d[num]-=1 # as it is visited so we are removing one occurance
return True | split-array-into-consecutive-subsequences | python3 | explained | easy to understand | Dictionary | H-R-S | 1 | 61 | split array into consecutive subsequences | 659 | 0.506 | Medium | 11,029 |
https://leetcode.com/problems/split-array-into-consecutive-subsequences/discuss/2447651/Python-Easy-Fast-with-comments | class Solution:
# Maintain 2 hashmaps
# First one stores the frequency of each num in nums
# Second one stores 3 or more length subarrays of nums ending with a particular num
# Cases when we iterate to a n in nums -
# 1. there alredy exists a subarray ending with n - 1 -> add n to it
# 2. there is no n - 1 ending subarray present - > create one subarray of n, n + 1, n + 2
# 3. n + 1 and n + 2 are not present - > answer not possible return False
# If all above cases pass without returning false you have a valid nums which can be divided hence return True
def isPossible(self, nums: List[int]) -> bool:
hm1 = Counter(nums)
hm2 = defaultdict(int)
for num in nums:
if hm1[num] == 0: continue
if num - 1 in hm2 and hm2[num - 1] > 0:
hm2[num - 1] -= 1
hm2[num] += 1
elif num + 1 in hm1 and num + 2 in hm1 and hm1[num + 1] > 0 and hm1[num + 2] > 0:
hm2[num + 2] += 1
hm1[num + 1] -= 1
hm1[num + 2] -= 1
else:
return False
hm1[num] -= 1
return True | split-array-into-consecutive-subsequences | Python Easy Fast with comments | shiv-codes | 1 | 249 | split array into consecutive subsequences | 659 | 0.506 | Medium | 11,030 |
https://leetcode.com/problems/split-array-into-consecutive-subsequences/discuss/2163206/Python-no-heaps-no-maps.-Time%3A-O(N)-Space%3A-O(N) | class Solution:
def isPossible(self, nums: List[int]) -> bool:
ss = [[nums[0], 1]]
i = 0
for n in nums[1:]:
if ss[len(ss) - 1][0] == n - 1:
i = len(ss) - 1
elif ss[i][0] == n - 1:
pass
elif ss[i-1][0] == n - 1:
i -= 1
else:
ss.append([0, 0])
i = len(ss) - 1
ss[i][0] = n
ss[i][1] += 1
return min(count for _, count in ss) >= 3 | split-array-into-consecutive-subsequences | Python, no heaps, no maps. Time: O(N), Space: O(N) | blue_sky5 | 1 | 122 | split array into consecutive subsequences | 659 | 0.506 | Medium | 11,031 |
https://leetcode.com/problems/split-array-into-consecutive-subsequences/discuss/2462535/Easy-to-understand-Solution-(using-Hashmap-and-min-heap) | class Solution:
def isPossible(self, nums: List[int]) -> bool:
n = len(nums)
if n < 3:
return False
mp = {}
for num in nums:
mp[num] = mp.get(num,0) + 1
pq = []
for k,v in mp.items():
heapq.heappush(pq,k)
while pq:
minn = pq[0]
count = 0
while True:
if minn not in mp:
if count < 3:
return False
break
mp[minn] -= 1
count += 1
if mp[minn] == 0:
if minn != pq[0]:
return False
heapq.heappop(pq)
if minn + 1 in mp and (mp[minn] >= mp[minn+1]):
if count < 3:
return False
break
minn += 1
return True | split-array-into-consecutive-subsequences | Easy to understand Solution (using Hashmap and min-heap) | rahulkapoor902 | 0 | 68 | split array into consecutive subsequences | 659 | 0.506 | Medium | 11,032 |
https://leetcode.com/problems/split-array-into-consecutive-subsequences/discuss/2452447/Python3-Solution-with-using-hashmap | class Solution:
def isPossible(self, nums: List[int]) -> bool:
freq_map, subseq_map = collections.Counter(nums), collections.Counter()
for num in nums:
# num already part of valid subseq
if freq_map[num] == 0:
continue
# num - 1 part of valid subseq
if subseq_map[num - 1] > 0:
subseq_map[num - 1] -= 1
subseq_map[num] += 1
elif freq_map[num + 1] > 0 and freq_map[num + 2] > 0:
freq_map[num + 1] -= 1
freq_map[num + 2] -= 1
subseq_map[num + 2] += 1
else:
return False
freq_map[num] -= 1
return True | split-array-into-consecutive-subsequences | [Python3] Solution with using hashmap | maosipov11 | 0 | 14 | split array into consecutive subsequences | 659 | 0.506 | Medium | 11,033 |
https://leetcode.com/problems/split-array-into-consecutive-subsequences/discuss/2450704/Python-Easy-Step-By-Step-Solution | class Solution:
def isPossible(self, nums: List[int]) -> bool:
# TimeComplexity: O(n)
# SpaceComplexity: O(n)
# create two counter dictionaries one for tracking occurances of nums
# and other for next number in the already filled subsequence
# if number is not in freq or has lost all its occurance move ahead
# if number is present and its also in nextMap reduce its occurance from it
# and put next number in nextMap
# if not both conditions then it will check if it can create new subsequence
# for that check if its next and further next values ie i+1, i+2 values are present
# if yes then reduce their occurance also and put their next number in nextMap
# if nothing works its False
# but in either true cases, current number will lose its frequency
# finally return True.
freqMap=Counter(nums)
nextMap=Counter()
for i in nums:
if not freqMap[i]:
continue
if nextMap[i]:
nextMap[i]-=1
nextMap[i+1]+=1
elif (freqMap[i+1] and freqMap[i+2]):
freqMap[i+1]-=1
freqMap[i+2]-=1
nextMap[i+3]+=1
else:
return False
freqMap[i]-=1
return True | split-array-into-consecutive-subsequences | Python Easy Step By Step Solution | varun21vaidya | 0 | 24 | split array into consecutive subsequences | 659 | 0.506 | Medium | 11,034 |
https://leetcode.com/problems/split-array-into-consecutive-subsequences/discuss/2450217/GolangPython-O(N)-time-or-O(N)-space | class Solution:
def isPossible(self, nums: List[int]) -> bool:
left = collections.Counter(nums)
right = collections.Counter()
for num in nums:
if not left[num]:
continue
left[num] -= 1
if right[num - 1] > 0:
right[num - 1] -= 1
right[num] += 1
elif left[num + 1] and left[num + 2]:
left[num + 1] -= 1
left[num + 2] -= 1
right[num + 2] += 1
else:
return False
return True | split-array-into-consecutive-subsequences | Golang/Python O(N) time | O(N) space | vtalantsev | 0 | 19 | split array into consecutive subsequences | 659 | 0.506 | Medium | 11,035 |
https://leetcode.com/problems/split-array-into-consecutive-subsequences/discuss/2447264/Python-or-Greedily-extending-shortest-subsequence-with-HEAPQ | class Solution:
def isPossible(self, nums):
SEQs_looks_for = defaultdict(list)
for num in nums:
pre_len, shortest_seq = heappop(SEQs_looks_for[num]) if SEQs_looks_for[num] else (0, [])
heappush(SEQs_looks_for[num + 1], (pre_len + 1, shortest_seq + [num]))
return all(l >= 3 for l, _ in chain.from_iterable(SEQs_looks_for.values())) | split-array-into-consecutive-subsequences | Python | Greedily extending shortest subsequence with HEAPQ | steve-jokes | 0 | 69 | split array into consecutive subsequences | 659 | 0.506 | Medium | 11,036 |
https://leetcode.com/problems/split-array-into-consecutive-subsequences/discuss/895143/Python3-deque-O(N) | class Solution:
def isPossible(self, nums: List[int]) -> bool:
freq = {}
for x in nums: freq[x] = 1 + freq.get(x, 0) # frequency table of nums
seen = deque()
for i, x in enumerate(nums):
if i == 0 or nums[i-1] != x:
if (n := freq[x] - freq.get(x-1, 0)) > 0: seen.extend([x]*n)
elif any(x - seen.popleft() < 3 for _ in range(-n)): return False
if not freq.get(x+1, 0) and any(x - seen.popleft() < 2 for _ in range(freq[x])): return False
return True | split-array-into-consecutive-subsequences | [Python3] deque O(N) | ye15 | 0 | 251 | split array into consecutive subsequences | 659 | 0.506 | Medium | 11,037 |
https://leetcode.com/problems/image-smoother/discuss/454951/Python3-simple-solution | class Solution:
def imageSmoother(self, M: List[List[int]]) -> List[List[int]]:
row, col = len(M), len(M[0])
res = [[0]*col for i in range(row)]
dirs = [[0,0],[0,1],[0,-1],[1,0],[-1,0],[1,1],[-1,-1],[-1,1],[1,-1]]
for i in range(row):
for j in range(col):
temp = [M[i+m][j+n] for m,n in dirs if 0<=i+m<row and 0<=j+n<col]
res[i][j] = sum(temp)//len(temp)
return res | image-smoother | Python3 simple solution | jb07 | 12 | 807 | image smoother | 661 | 0.551 | Easy | 11,038 |
https://leetcode.com/problems/image-smoother/discuss/2101331/python-3-oror-clean-and-efficient-solution | class Solution:
def imageSmoother(self, img: List[List[int]]) -> List[List[int]]:
m, n = len(img), len(img[0])
def avg(i, j):
s = squares = 0
top, bottom = max(0, i - 1), min(m, i + 2)
left, right = max(0, j - 1), min(n, j + 2)
for x in range(top, bottom):
for y in range(left, right):
s += img[x][y]
squares += 1
return s // squares
return [[avg(i, j) for j in range(n)] for i in range(m)] | image-smoother | python 3 || clean and efficient solution | dereky4 | 4 | 300 | image smoother | 661 | 0.551 | Easy | 11,039 |
https://leetcode.com/problems/image-smoother/discuss/1842115/6-Lines-Python-Solution-oror-76-Faster-oror-Memory-less-than-87 | class Solution:
def imageSmoother(self, I: List[List[int]]) -> List[List[int]]:
n=len(I) ; m=len(I[0]) ; ANS=[[0]*m for i in range(n)]
for i,j in product(range(n), range(m)):
s=[]
for x,y in product(range(max(0,i-1),min(i+2,n)),range(max(0,j-1),min(j+2,m))): s.append(I[x][y])
ANS[i][j]=sum(s)//len(s)
return ANS | image-smoother | 6-Lines Python Solution || 76% Faster || Memory less than 87% | Taha-C | 1 | 156 | image smoother | 661 | 0.551 | Easy | 11,040 |
https://leetcode.com/problems/image-smoother/discuss/2650719/Python3-Bits-operation-O(mn)-time-O(1)-space | class Solution:
def imageSmoother(self, img: List[List[int]]) -> List[List[int]]:
if len(img) == 1 and len(img[0]) == 1:
return img
for row in range(len(img)):
for col in range(len(img[0])):
partial = self.summ(img, row, col)
partial <<= 8
img[row][col] += partial
for row in range(len(img)):
for col in range(len(img[0])):
img[row][col] >>= 8
return img
def summ(self, m: List[List[int]], r: int, c: int) -> int:
directions = [(0,0), (-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)]
ans = 0
times = 0
for dx, dy in directions:
if r + dx >= 0 and r + dx < len(m) and c + dy >= 0 and c + dy < len(m[0]):
times += 1
ans += (m[r+dx][c+dy] & 255)
return int(ans / times) | image-smoother | [Python3] Bits operation, O(mn) time, O(1) space | DG_stamper | 0 | 15 | image smoother | 661 | 0.551 | Easy | 11,041 |
https://leetcode.com/problems/image-smoother/discuss/2306158/simple-python3-solution | class Solution:
def imageSmoother(self, img: List[List[int]]) -> List[List[int]]:
m, n = len(img), len(img[0])
res = [[0]*n for i in range(m)]
dirs = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]
for i in range(m):
for j in range(n):
cur_sum = img[i][j]
count = 1
for d in dirs:
x = i + d[0]
y = j + d[1]
if 0 <= x < m and 0 <= y < n:
count += 1
cur_sum += img[x][y]
res[i][j] = int(cur_sum / count)
return res | image-smoother | simple python3 solution | codeSheep_01 | 0 | 66 | image smoother | 661 | 0.551 | Easy | 11,042 |
https://leetcode.com/problems/image-smoother/discuss/1847404/PYTHON-O(-m-*-n-)-Solution-with-detailed-explanation-(1068ms) | class Solution:
def imageSmoother(self, img: List[List[int]]) -> List[List[int]]:
#Pull the dimensions
m_rows = len( img );
n_cols = len( img[ 0 ] );
#Kernel size is 3;
k = 3;
#Create a new image for each averaged total to be stored
newImage = [ [ 0 for _ in range( n_cols ) ] for _ in range( m_rows ) ];
#Start is the grid cordinate [ column , row ];
start = [ 0, 0 ];
#direction right tells us if we are true
directionRight = [ True ];
#Total keeps track of our total
total = [ 0 ];
#Initialize the kernel at [ 0 , 0 ];
#Valid kernel will tell us how many valid squares
#We are averaging
total[ 0 ] , validKernel = self.initializeKernel( img, m_rows, n_cols, start );
#Previous direction will help us snake down the matrix
#By snake down, we go right to left, then down, then left to right
#As we find the total
#This allows us to reuse our counts, and prevents overlapping calculations
#When previous direction is True
#It means we are going from right to left
#When it is False, we are going from left to right
prevDirection = True;
#While our row value is at a valid index, process:
while start[ 1 ] < m_rows:
#Pull the x and y coordinate
x = start[ 0 ];
y = start[ 1 ];
#Assign the average value
newImage[ y ][ x ] = total[ 0 ] // validKernel;
#Find the next coordinate by calling self.snake() to snake through the matri
#Instead of scanning and going back to the beginning at the end,
#Like when we read,
#We continue our calculations in the other direction
#next cord will go from
#BEGIN [ 0, 0] , [ 1 , 0 ] , [ 2 , 0] , END , [ 2, 1 ], [ 1 , 1 ], [ 0, 1 ]
# BEGIN [ 0, 2 ] [ 1, 2 ] [ 2, 2 ] END [ 2, 3 ] ...
nextCoord = self.snake(img, m_rows , n_cols, start, directionRight );
#nextCoord modifies the directionRight flag if it changes
#to false, and thus begins going left
#When we change directions, we want to go down a row
if prevDirection != directionRight[ 0 ]:
#We adjust the slice of the kernel by KEEPING
#the overlapped elements
#Adjust prev will remove from the total a slice of the kernel
#That does not overlap
#Since we are always going down, the below call to change slice
#Will always remove the non overlapping top part of the kernel
adjustPrev = self.changeSlice( img, m_rows, n_cols, [ x, y ] ,total, False, 0 );
validKernel -= adjustPrev;
#We remove the count so our average will only consider the overlapped
#Next we add the new slice that comes with our new coordinate
#This will always be the bottom part of the kernel
adjustCurr = self.changeSlice( img, m_rows, n_cols, [ x, y + 1 ] ,total, True, 1 );
validKernel += adjustCurr ;
#and same thing, we add to the count the pieces of our new slice
#If we are going in the same direction,
else:
#These values keep track of changeSlice
#Minus condition and plus condition
#Tell us which part of the kernel we are changing
#If we are going right:
#We remove the left slice of the old kernel
#And add the right slice of the new kernel
if directionRight[ 0 ]:
minusCondition = 3;
plusCondition = 2;
#If we are going left:
#It is the opposide
#We remove the right slice of the old kernel
#And add the left slice of the new kernel
else:
minusCondition = 2;
plusCondition = 3;
#Like with the above, We adjust the slices and update the validKernel count
adjustPrev = self.changeSlice( img, m_rows, n_cols, [ x, y ], total, False, minusCondition );
validKernel -= adjustPrev;
adjustCurr = self.changeSlice( img, m_rows, n_cols, nextCoord, total, True, plusCondition );
validKernel += adjustCurr;
#At the end, we update the start value with our nextCoord
#And we overWrite our prevDirection flag with our current direction
start = nextCoord;
prevDirection = directionRight[ 0 ];
return newImage;
#Is validCoord takes in the dimensions of the matrix
#And returns if a current coordinate pair is not a valid index
def isValidCoord( self, m, n, current ):
x = current[ 0 ];
y = current[ 1 ];
if x < 0 or y < 0:
return False;
if x >= n or y >= m:
return False;
return True;
#Intialize kernel will create the first instance of our kernel
#at the top left of our matrix
def initializeKernel( self, grid, m, n, start , k = 3):
x = start[ 0 ];
y = start[ 1 ];
starting_total = 0;
validCoord = 0;
#It is generalized to take any slice of k
#Since we are starting at the top left
#We only need half of the kernel to begin with
#Which is k // 2
#The plus one comes from including the middle section of the kernel
for i in range( ( k // 2) + 1 ):
for j in range( (k // 2 ) + 1 ):
#For each potential kernel location,
#We see if it is a valid coordinate
#This is needed for when the kernel is larger than the matrix
if self.isValidCoord( m , n , [ x + j, y + i ] ):
starting_total += grid[ y + i ][ x + j ];
validCoord += 1;
#We return our starting total
#And our count, validCoord, which is used to divide the total to find
#the average
return starting_total, validCoord;
#Change slice will tally slices of the kernel
#The top or bottom row,
#The left or right hand side of the column
#Change slice will find the valid coordinates of the slice
#And will either add them or subtract them from the total
#Depending on the passed in paratmeters
#It is the swiss-army-knife of this solution
def changeSlice( self, grid, m , n, current, total, addition = True, condition = 0 ,k = 3 ):
#Condition 0 tallies the top row
#Condition 1 tallies the bottom row
#Condition 2 tallies the right column
#Condition 3 tallies the left column
#If addition is True, we add to the total
#If addition is False, we subtract from the total
#We take the current center of the kernel
x = current[ 0 ];
y = current[ 1 ];
#Adjust slice allows us to generalize to other sizes of k
adjustSlice = ( k // 2 );
#We see how many valid coordinates are being modified
#That is, how many are going into the addition or subtraction of the total
validCoord = 0;
#Going down or right from the top left of the kernel
if condition == 0 or condition == 3:
start = [ x - adjustSlice , y - adjustSlice ];
#Going right from bottom left of the kernel
elif condition == 1:
start = [ x - adjustSlice , y + adjustSlice ];
#Going down from top right of the kernel
elif condition == 2:
start = [ x + adjustSlice , y - adjustSlice ];
else:
raise ValueError;
#For the size of the slice
for i in range( k ):
#Horizontal slice of k: condition 0 is top, 1 is bottom
if condition == 0 or condition == 1:
a = start[ 0 ] + i;
b = start[ 1 ] ;
#Vertical slice of k: 2 is righthand side, 3 is lefthand side
else:
a = start[ 0 ] ;
b = start[ 1 ] + i;
#Check to see if the generated coordinate is on the matrix
if self.isValidCoord( m , n , [ a ,b ] ):
#If it is, add to our subtotal count
validCoord += 1;
#If the addition flag is true:
#Add the value to the total
if addition:
total[ 0 ] += grid[ b ][ a ];
#If it is subtraction, remove the value from the total
else:
total[ 0 ] -= grid[ b ][ a ];
#Return the number of coordinates that changed the total
return validCoord;
#Snake will, given the current coordinate, generate the next one
#If directionRight is True, we are going right
#If directionRight is False, we are going left
def snake( self, grid, m, n, current , directionRight):
#Pull the coordinates
x = current[ 0 ];
y = current[ 1 ];
#Adjust the x value in accordance with the direction
if directionRight[ 0 ]:
x = x + 1;
else:
x = x - 1;
#If we are outside of a valid coordinate,
if x == -1 or x == n:
#Change direction
directionRight[ 0 ] = not directionRight[ 0 ];
#Return the original x, and increment y
return [ current[ 0 ] , y + 1 ]
#Otherwise, return the modified x, and the original y
return [ x , y ]; | image-smoother | PYTHON O( m * n ) Solution with detailed explanation (1068ms) | greg_savage | 0 | 128 | image smoother | 661 | 0.551 | Easy | 11,043 |
https://leetcode.com/problems/image-smoother/discuss/991703/Python-O(m*n)-Time-O(1)-Space-Solution | class Solution:
def imageSmoother(self, M: List[List[int]]) -> List[List[int]]:
m, n = len(M), len(M[0])
# Calculate sums in the same row.
for i in range(m):
tmp = M[i][0]
for j in range(1, n):
value = M[i][j]
M[i][j - 1] += value
M[i][j] += tmp
tmp = value
# Calculate the sums by columns.
for j in range(n):
tmp = M[0][j]
for i in range(1, m):
value = M[i][j]
M[i - 1][j] += value
M[i][j] += tmp
tmp = value
# Calulate the number of cells.
for i in range(m):
x = 3 - (1 if i == 0 else 0) - (1 if i == m - 1 else 0)
for j in range(n):
y = 3 - (1 if j == 0 else 0) - (1 if j == n - 1 else 0)
M[i][j] //= x * y
return M | image-smoother | Python O(m*n) Time, O(1) Space Solution | cheng-hao2 | 0 | 144 | image smoother | 661 | 0.551 | Easy | 11,044 |
https://leetcode.com/problems/maximum-width-of-binary-tree/discuss/688259/Python-solution-O(N)-BFS-traversal | class Solution:
def widthOfBinaryTree(self, root: TreeNode) -> int:
Q = collections.deque()
Q.append((root,0))
ans = 0
while Q:
length = len(Q)
_, start = Q[0]
for i in range(length):
node, index = Q.popleft()
if node.left:
Q.append((node.left, 2*index))
if node.right:
Q.append((node.right, 2*index+1))
ans = max(ans, index-start+1)
return ans | maximum-width-of-binary-tree | Python solution - O(N) BFS traversal | realslimshady | 4 | 489 | maximum width of binary tree | 662 | 0.407 | Medium | 11,045 |
https://leetcode.com/problems/maximum-width-of-binary-tree/discuss/1051024/Python-BFS-%2B-A-few-notes | class Solution:
def widthOfBinaryTree(self, root: TreeNode) -> int:
queue = collections.deque([(root, 0, 0)])
left, right = {}, {}
result = 0
while queue:
node, x, y = queue.popleft()
if not node: continue
left[y] = min(left.get(y, x), x)
right[y] = max(right.get(y, x), x)
result = max(result, right[y]-left[y]+1)
queue.extend([
(node.left, 2*x, y+1),
(node.right, (2*x)+1, y+1)
])
return result | maximum-width-of-binary-tree | Python BFS + A few notes | dev-josh | 3 | 324 | maximum width of binary tree | 662 | 0.407 | Medium | 11,046 |
https://leetcode.com/problems/maximum-width-of-binary-tree/discuss/2095130/Python3-Queue-O(n)-Time-Optimal-Solution | class Solution:
def widthOfBinaryTree(self, root: Optional[TreeNode]) -> int:
q = collections.deque()
q.append((root, 0))
res = 0
if not root: return res
while q:
# q[0] is left-most and q[-1] is right-most node of current level
res = max(res, q[-1][1] - q[0][1] + 1)
n = len(q)
for i in range(n):
tmp = q.popleft()
node = tmp[0]
dist = tmp[1]
if node.left: q.append((node.left, 2*dist-1))
if node.right: q.append((node.right, 2*dist))
return res
# Time: O(N)
# Space: O(N) | maximum-width-of-binary-tree | [Python3] Queue O(n) Time Optimal Solution | samirpaul1 | 2 | 152 | maximum width of binary tree | 662 | 0.407 | Medium | 11,047 |
https://leetcode.com/problems/maximum-width-of-binary-tree/discuss/2210151/Explained-with-Inline-Comment | class Solution:
def widthOfBinaryTree(self, root: Optional[TreeNode]) -> int:
if not root:
return None
q=deque()
q.append(root)
level=deque()
level.append(1)
max_width=1
while(len(q)!=0):
max_width=max(max_width,max(level)-min(level)+1)
for i in range(len(q)):
r=level.popleft()
node=q.popleft()
if node.left:
q.append(node.left)
level.append(2*r)
if node.right:
q.append(node.right)
level.append(2*r+1)
return max_width
#please upvote if it helps you in any manner regarding how to approach the problem | maximum-width-of-binary-tree | Explained with Inline Comment | Taruncode007 | 1 | 100 | maximum width of binary tree | 662 | 0.407 | Medium | 11,048 |
https://leetcode.com/problems/maximum-width-of-binary-tree/discuss/1808813/Short-and-Simplest-of-all | class Solution:
def widthOfBinaryTree(self, root: Optional[TreeNode]) -> int:
queue=[[root,0]]
m=0
while(queue):
m=max(m,queue[-1][1]-queue[0][1])
for i in range(len(queue)):
node,cur=queue.pop(0)
if(node.left): queue.append([node.left,2*cur+1])
if(node.right): queue.append([node.right,2*cur+2])
return m+1 | maximum-width-of-binary-tree | Short and Simplest of all | vedank98 | 1 | 52 | maximum width of binary tree | 662 | 0.407 | Medium | 11,049 |
https://leetcode.com/problems/maximum-width-of-binary-tree/discuss/1803757/Python3-oror-Simple-BFS-oror-96-Faster-oror-Easy-To-Understand | class Solution:
def widthOfBinaryTree(self, root: Optional[TreeNode]) -> int:
q = [(root, 0),]
res = 1
while q:
next_q, mn, mx = [], float('inf'), 0
for node, i in q:
mn, mx = min(mn, i), max(mx, i)
if node.left: next_q.append((node.left, i * 2 + 1))
if node.right: next_q.append((node.right, i * 2 + 2))
res = max(res, mx - mn + 1)
q = next_q
return res | maximum-width-of-binary-tree | Python3 || Simple BFS || 96% Faster || Easy To Understand | cherrysri1997 | 1 | 29 | maximum width of binary tree | 662 | 0.407 | Medium | 11,050 |
https://leetcode.com/problems/maximum-width-of-binary-tree/discuss/1803294/PYTHON3-Simple-BFS-Solution-oror-Using-deque-object-oror-40ms-beats-96 | class Solution:
def widthOfBinaryTree(self, root: Optional[TreeNode]) -> int:
res = 0
q = deque([[0, root]])
while q:
res = max(res, (q[-1][0] - q[0][0]) + 1)
for _ in range(len(q)):
j, node = q.popleft()
if node.left: q.append([j*2, node.left])
if node.right: q.append([(j*2)+1, node.right])
return res | maximum-width-of-binary-tree | [PYTHON3] Simple BFS Solution || Using deque object || 40ms beats 96% | nandhakiran366 | 1 | 45 | maximum width of binary tree | 662 | 0.407 | Medium | 11,051 |
https://leetcode.com/problems/maximum-width-of-binary-tree/discuss/1773524/python3-BFS-SOLUTION | class Solution:
def widthOfBinaryTree(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
from collections import deque
q=deque()
q.append((root,1))
res=0
while q:
res=max(res,q[-1][1]-q[0][1]+1)
n=len(q)
for i in range(n):
node,ind=q.popleft()
if node.left:
q.append((node.left,ind*2))
if node.right:
q.append((node.right,ind*2+1))
return res | maximum-width-of-binary-tree | python3 BFS SOLUTION | Karna61814 | 1 | 47 | maximum width of binary tree | 662 | 0.407 | Medium | 11,052 |
https://leetcode.com/problems/maximum-width-of-binary-tree/discuss/1555228/Python-BFS | class Solution:
def widthOfBinaryTree(self, root: Optional[TreeNode]) -> int:
max_width = 0
q = deque([(root, 0)])
while q:
length = len(q)
max_width = max(max_width, q[-1][1] - q[0][1] + 1)
for _ in range(length):
node, x = q.popleft()
if node.left:
q.append((node.left, 2 * x))
if node.right:
q.append((node.right, 2 * x + 1))
return max_width | maximum-width-of-binary-tree | Python, BFS | blue_sky5 | 1 | 141 | maximum width of binary tree | 662 | 0.407 | Medium | 11,053 |
https://leetcode.com/problems/maximum-width-of-binary-tree/discuss/727285/Python3-11-line-bfs | class Solution:
def widthOfBinaryTree(self, root: Optional[TreeNode]) -> int:
ans = 0
queue = deque([(root, 0)])
while queue:
ans = max(ans, queue[-1][1] - queue[0][1] + 1)
for _ in range(len(queue)):
node, x = queue.popleft()
if node.left: queue.append((node.left, 2*x))
if node.right: queue.append((node.right, 2*x+1))
return ans | maximum-width-of-binary-tree | [Python3] 11-line bfs | ye15 | 1 | 61 | maximum width of binary tree | 662 | 0.407 | Medium | 11,054 |
https://leetcode.com/problems/maximum-width-of-binary-tree/discuss/2769592/Learning-about-the-2-*-c-and-2-*-c-%2B-1-concept-for-binary-trees | class Solution:
# At each if you assign 2 * c to the left and 2 * c + 1 to the right
# then at any level you can know what is the rightmost node in that level order traversal
# by subtracting the rightmost in level order with leftmost in level order
# The max for any level will be our answer
def widthOfBinaryTree(self, root: Optional[TreeNode]) -> int:
queue = deque([(root, 0)])
res = 0
while queue:
size = len(queue)
_, l = queue[0]
for _ in range(size):
node, c = queue.popleft()
if node.left: queue.append((node.left, 2 * c))
if node.right: queue.append((node.right, 2 * c + 1))
res = max(res, c - l + 1)
return res | maximum-width-of-binary-tree | Learning about the 2 * c and 2 * c + 1 concept for binary trees | shiv-codes | 0 | 7 | maximum width of binary tree | 662 | 0.407 | Medium | 11,055 |
https://leetcode.com/problems/maximum-width-of-binary-tree/discuss/2550170/Python-BFS-and-DFS-90-Faster | class Solution(object):
def widthOfBinaryTree(self, root):
q = deque([(root,1)])
width = 0
while q:
_,left = q[0]
_,right = q[-1]
width = max(width, right-left+1)
next_level = deque()
while q:
node, index = q.popleft()
if node.left:
next_level.append((node.left,2*index))
if node.right:
next_level.append((node.right,2*index+1))
q = next_level
return width | maximum-width-of-binary-tree | Python BFS and DFS 90% Faster | Abhi_009 | 0 | 65 | maximum width of binary tree | 662 | 0.407 | Medium | 11,056 |
https://leetcode.com/problems/maximum-width-of-binary-tree/discuss/2539979/Python3-solution | class Solution:
def widthOfBinaryTree(self, root: Optional[TreeNode]) -> int:
if root==None:
return 0
res = 0
q = deque([(root, 0)])
while(q):
size = len(q)
mmin = q[0][1]
first, last = 0, 0
for i in range(0, size):
cur_id = q[0][1] - mmin
node = q[0][0]
q.popleft()
if i == 0:
first = cur_id
if i==size-1:
last = cur_id
if node.left:
q.append((node.left, cur_id*2+1))
if node.right:
q.append((node.right, cur_id*2+2))
res = max(res, last-first+1)
return res | maximum-width-of-binary-tree | Python3 solution | sumedha19129 | 0 | 29 | maximum width of binary tree | 662 | 0.407 | Medium | 11,057 |
https://leetcode.com/problems/maximum-width-of-binary-tree/discuss/2310515/Easy-BFS | class Solution:
def widthOfBinaryTree(self, root: Optional[TreeNode]) -> int:
if not root:
return None
queue = deque([(root, 0)])
result = 1
while queue:
columns = []
for _ in range(len(queue)):
node, column = queue.popleft()
columns.append(column)
if node.left:
queue.append((node.left, column * 2))
if node.right:
queue.append((node.right, column * 2 + 1))
result = max(result, columns[-1] - columns[0] + 1)
return result | maximum-width-of-binary-tree | Easy BFS | lastmidnoon | 0 | 75 | maximum width of binary tree | 662 | 0.407 | Medium | 11,058 |
https://leetcode.com/problems/maximum-width-of-binary-tree/discuss/1809135/Python-Solution-using-BFS | class Solution:
def widthOfBinaryTree(self, root: Optional[TreeNode]) -> int:
if root is None:
return 0
q = [(root, 0)]
max_width = float('-inf')
while len(q) != 0:
max_width = max(max_width, q[-1][1] - q[0][1]+1)
size = len(q)
while size > 0:
cur_node, position = q.pop(0)
size -= 1
if cur_node.left != None:
q.append((cur_node.left, position * 2))
if cur_node.right != None:
q.append((cur_node.right, position * 2 + 1))
return max_width | maximum-width-of-binary-tree | Python Solution, using BFS | pradeep288 | 0 | 47 | maximum width of binary tree | 662 | 0.407 | Medium | 11,059 |
https://leetcode.com/problems/maximum-width-of-binary-tree/discuss/1805014/Python3-BFS-solution | class Solution:
def widthOfBinaryTree(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
res = 0
q = collections.deque()
q.append((root, 0))
while q:
_, lvl_left_idx = q[0]
lvl_len = len(q)
for _ in range(lvl_len):
node, idx = q.popleft()
if node.left:
q.append((node.left, idx * 2))
if node.right:
q.append((node.right, idx * 2 + 1))
res = max(res, idx - lvl_left_idx + 1)
return res | maximum-width-of-binary-tree | [Python3] BFS solution | maosipov11 | 0 | 14 | maximum width of binary tree | 662 | 0.407 | Medium | 11,060 |
https://leetcode.com/problems/maximum-width-of-binary-tree/discuss/1804165/Python-Best-Solution | class Solution:
def widthOfBinaryTree(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
que = [(root, 0)]
width = 0
while que:
size = len(que)
minInLevel = que[0][1]
width = max(width, que[-1][1]-que[0][1]+1)
for _ in range(size):
node = que[0][0]
curr = que[0][1]-minInLevel # To prevent overflow...
que.pop(0)
if node.left:
que.append((node.left, 2*curr+1))
if node.right:
que.append((node.right, 2*curr+2))
return width | maximum-width-of-binary-tree | Python - Best Solution ✔ | leet_satyam | 0 | 66 | maximum width of binary tree | 662 | 0.407 | Medium | 11,061 |
https://leetcode.com/problems/maximum-width-of-binary-tree/discuss/1803606/Python-Simple-Python-Solution-Using-Level-Order-Traversal-Breadth-First-Search-and-Queue | class Solution:
def widthOfBinaryTree(self, root: Optional[TreeNode]) -> int:
queue=deque([[root,0]])
Max_Width=1
while queue:
StartIndex = queue[0][1]
Max_Width=max(Max_Width,queue[-1][1]-StartIndex+1)
for _ in range(len(queue)):
CurrentNode, CurrentIndex = queue.popleft()
CurrentIndex = CurrentIndex - StartIndex
Left_Node = CurrentNode.left
Right_Node = CurrentNode.right
CurrentDouble= 2 * CurrentIndex
if Left_Node != None:
queue.append([Left_Node,CurrentDouble])
if Right_Node != None:
queue.append([Right_Node,CurrentDouble+1])
return Max_Width | maximum-width-of-binary-tree | [ Python ] ✔✔ Simple Python Solution Using Level-Order-Traversal, Breadth-First-Search and Queue 🔥✌ | ASHOK_KUMAR_MEGHVANSHI | 0 | 99 | maximum width of binary tree | 662 | 0.407 | Medium | 11,062 |
https://leetcode.com/problems/maximum-width-of-binary-tree/discuss/738620/Python3-Level-Min-Max-(bfs) | class Solution:
def widthOfBinaryTree(self, root: TreeNode) -> int:
ans = 0
q = collections.deque([(root, 0, 1)])
level_dict = {}
while q:
node, level, pos = q.popleft()
if level not in level_dict:
level_dict[level] = [pos, pos]
else:
level_dict[level][0] = min(level_dict[level][0], pos)
level_dict[level][1] = max(level_dict[level][1], pos)
ans = max(ans, level_dict[level][1] - level_dict[level][0])
pos = pos*2
if node.left:
q.append((node.left, level+1, pos))
pos += 1
if node.right:
q.append((node.right, level+1, pos))
return ans + 1 | maximum-width-of-binary-tree | [Python3] Level Min-Max (bfs) | ManmayB | 0 | 97 | maximum width of binary tree | 662 | 0.407 | Medium | 11,063 |
https://leetcode.com/problems/maximum-width-of-binary-tree/discuss/717043/Python-BFS | class Solution:
# Time: O(n)
# Space: O(2**H)
def widthOfBinaryTree(self, root: TreeNode) -> int:
if not root:
return 0
level, res = [(root, 0)], 1
while level:
next_level = []
res = max(res, level[-1][1] - level[0][1] + 1)
for node, loc in level:
if node.left:
next_level.append((node.left, 2 * loc))
if node.right:
next_level.append((node.right, 2 * loc + 1))
level = next_level
return res | maximum-width-of-binary-tree | Python BFS | whissely | 0 | 173 | maximum width of binary tree | 662 | 0.407 | Medium | 11,064 |
https://leetcode.com/problems/maximum-width-of-binary-tree/discuss/415587/Python-faster-than-99.79. | class Solution:
def widthOfBinaryTree(self, root: TreeNode) -> int:
if not root:
return 0
L=[[root]]
V=[[0]]
while L[-1]:
R=[]
S=[]
for i in range(len(L[-1])):
if L[-1][i].left:
S.append(2*V[-1][i])
R.append(L[-1][i].left)
if L[-1][i].right:
S.append(2*V[-1][i]+1)
R.append(L[-1][i].right)
V.append(S)
L.append(R)
v=[S[-1]-S[0]+1 for S in V if S]
return max(v) | maximum-width-of-binary-tree | Python faster than 99.79%. | rifleviper | 0 | 77 | maximum width of binary tree | 662 | 0.407 | Medium | 11,065 |
https://leetcode.com/problems/strange-printer/discuss/1492420/Python3-dp | class Solution:
def strangePrinter(self, s: str) -> int:
s = "".join(ch for i, ch in enumerate(s) if i == 0 or s[i-1] != ch)
@cache
def fn(lo, hi):
"""Return min ops to print s[lo:hi]."""
if lo == hi: return 0
ans = 1 + fn(lo+1, hi)
for mid in range(lo+1, hi):
if s[lo] == s[mid]:
ans = min(ans, fn(lo, mid) + fn(mid+1, hi))
return ans
return fn(0, len(s)) | strange-printer | [Python3] dp | ye15 | 3 | 378 | strange printer | 664 | 0.468 | Hard | 11,066 |
https://leetcode.com/problems/non-decreasing-array/discuss/2193030/Python-Easy-Greedy-w-explanation-O(1)-space | class Solution:
def checkPossibility(self, nums: List[int]) -> bool:
cnt_violations=0
for i in range(1, len(nums)):
if nums[i]<nums[i-1]:
if cnt_violations==1:
return False
cnt_violations+=1
if i>=2 and nums[i-2]>nums[i]:
nums[i]=nums[i-1]
return True | non-decreasing-array | Python Easy Greedy w/ explanation - O(1) space | constantine786 | 52 | 2,800 | non decreasing array | 665 | 0.242 | Medium | 11,067 |
https://leetcode.com/problems/non-decreasing-array/discuss/2193653/Python3-simple-O(n)-greedy-solution | class Solution:
def checkPossibility(self, nums: List[int]) -> bool:
flag = False
nums = [-float('inf')] + nums + [float('inf')]
for i in range(1, len(nums) - 2):
if nums[i + 1] < nums[i]:
if flag: return False
else:
if nums[i + 2] >= nums[i] or nums[i + 1] >= nums[i - 1]:
flag = True
else: return False
return True | non-decreasing-array | 📌 Python3 simple O(n) greedy solution | Dark_wolf_jss | 6 | 57 | non decreasing array | 665 | 0.242 | Medium | 11,068 |
https://leetcode.com/problems/non-decreasing-array/discuss/2193172/Python3-or-Explained-or-Easy-to-Understand-or-Non-decreasing-Array | class Solution:
def checkPossibility(self, nums: List[int]) -> bool:
is_modified = False # to check for multiple occurances of False condition(non increasing)
index = -1 # to get the index of false condition
n = len(nums)
if n==1:return True
for i in range(1, n):
if nums[i] < nums[i-1] and not is_modified: # check if nums[i-1] is greater than nums[i]
index = i # stores the index
is_modified = True # mark the change which is to be modified
elif nums[i] < nums[i-1] and is_modified: # if another false occurs return false (atmost 1 false cond.)
return False
if index != -1:
v = nums[index-1]
nums[index-1] = nums[index] # modifying index value and check for sort
idx = index-1
if idx-1>=0 and idx<n and nums[idx-1]<=nums[idx]<=nums[idx+1]: # check if modified array is sorted or not
return True
elif idx==0 and idx+1<n and nums[idx]<=nums[idx+1]: # check if modified array is sorted or not
return True
nums[index-1]=v
nums[index] = nums[index-1]+1
if index-1>=0 and index+1<n and nums[index-1]<=nums[index]<=nums[index+1]: # check if modified array is sorted or not
return True
elif index==n-1 and nums[index-1]<=nums[index]:
return True
if index==-1: # if array is already sorted
return True
return False | non-decreasing-array | Python3 | Explained | Easy to Understand | Non-decreasing Array | H-R-S | 3 | 290 | non decreasing array | 665 | 0.242 | Medium | 11,069 |
https://leetcode.com/problems/non-decreasing-array/discuss/1066719/Python-or-Easy-solution-or-Beats-85 | class Solution:
def checkPossibility(self, nums: List[int]) -> bool:
count = 0
for i in range(len(nums)-1):
if nums[i+1] - nums[i]<0:
count += 1
if (i>1 and nums[i]-nums[i-2]<0 and nums[i+1]-nums[i-1]<0) or count>1:
return False
return True | non-decreasing-array | Python | Easy solution | Beats 85% | SlavaHerasymov | 3 | 190 | non decreasing array | 665 | 0.242 | Medium | 11,070 |
https://leetcode.com/problems/non-decreasing-array/discuss/332212/Solution-in-Python-3-(beats-~99) | class Solution:
def checkPossibility(self, nums: List[int]) -> bool:
j = 0
for i in range(len(nums)-1):
if nums[i]-nums[i+1] > 0:
D = i
j += 1
if j == 2:
return False
if j == 0 or D == 0 or D == len(nums)-2:
return True
if (nums[D-1] <= nums[D] <= nums[D+2]) or (nums[D-1] <= nums[D+1] <= nums[D+2]):
return True
else:
return False
- Python 3
- Junaid Mansuri | non-decreasing-array | Solution in Python 3 (beats ~99%) | junaidmansuri | 3 | 904 | non decreasing array | 665 | 0.242 | Medium | 11,071 |
https://leetcode.com/problems/non-decreasing-array/discuss/1454317/Simple-Python-O(n)-greedy-solution | class Solution:
def checkPossibility(self, nums: List[int]) -> bool:
nums = [-float("inf")]+nums+[float("inf")]
modified = False
for i in range(1, len(nums)-1):
if nums[i] < nums[i-1]:
if modified:
return False
if nums[i-1] <= nums[i+1]:
nums[i] = nums[i-1]
else:
nums[i-1] = nums[i]
if nums[i-1] < nums[i-2]:
return False
modified = True
return True | non-decreasing-array | Simple Python O(n) greedy solution | Charlesl0129 | 2 | 362 | non decreasing array | 665 | 0.242 | Medium | 11,072 |
https://leetcode.com/problems/non-decreasing-array/discuss/1191590/python-greedy-solution-with-explanation | class Solution:
def checkPossibility(self, nums: List[int]) -> bool:
if len(nums) <= 2:
return True
for i in range(1,len(nums)-1):
# 3 1 2 pattern. if it's 3 2 1 then it will fail at the final check
# becomes 1 1 2 pattern
if (nums[i] < nums[i-1] and nums[i-1] > nums[i+1]):
nums[i-1] = nums[i]
break
# 2 1 3 pattern or 1 3 2 pattern -> 2 2 3 pattern or 1 1 2 pattern
elif (nums[i] < nums[i-1] and nums[i+1] > nums[i-1]) or (nums[i] > nums[i-1] and nums[i] > nums[i+1] and nums[i+1] > nums[i-1]):
nums[i] = nums[i-1]
break
# 2 3 1 pattern -> 2 3 3
elif (nums[i] > nums[i-1] and nums[i+1] < nums[i-1]):
nums[i+1] = nums[i]
break
# final check
for i in range(len(nums)-1):
if nums[i] > nums[i+1]:
return False
return True | non-decreasing-array | python greedy solution with explanation | yingziqing123 | 1 | 156 | non decreasing array | 665 | 0.242 | Medium | 11,073 |
https://leetcode.com/problems/non-decreasing-array/discuss/2830495/python3-easy-understanding | class Solution:
def checkPossibility(self, nums: List[int]) -> bool:
cnt_same_items, flag, prev_item = 1, False, float("-inf")
for i in range(1, len(nums)):
if nums[i] == nums[i - 1]:
cnt_same_items += 1
elif nums[i] > nums[i - 1]:
cnt_same_items = 1
prev_item = nums[i - 1]
else:
change_current = (i + 1 < len(nums) and nums[i + 1] >= nums[i - 1]) or i + 1 == len(nums)
change_prev = cnt_same_items == 1 and prev_item <= nums[i]
if (change_current or change_prev) and not flag:
flag = True
else:
return False
return True | non-decreasing-array | python3 easy understanding | Yaro1 | 0 | 1 | non decreasing array | 665 | 0.242 | Medium | 11,074 |
https://leetcode.com/problems/non-decreasing-array/discuss/2826625/Solving-without-modifying-the-input-list | class Solution:
def checkPossibility(self, nums: List[int]) -> bool:
fix_idx=-10
fix_value=-10e5
for i in range(len(nums)-1):
x1 = fix_value if i-1>=0 and i-1 == fix_idx else nums[i-1] if i-1>=0 else -10e5
x2 = fix_value if i == fix_idx else nums[i]
x3 = fix_value if i+1 == fix_idx else nums[i+1]
x4 = fix_value if i+2<len(nums) and i+2 == fix_idx else nums[i+2] if i+2<len(nums) else 10e5
if x2 > x3:
need_fix = -1
if x2 <= x4:
need_fix = i+1
elif x3 >= x1:
need_fix = i
if need_fix == -1:
return False
if fix_idx >= 0 and need_fix != fix_idx:
return False
else:
fix_idx = need_fix
fix_value = nums[i] if need_fix==i+1 else nums[i+1]
return True | non-decreasing-array | Solving without modifying the input list | ngotunglam1997 | 0 | 2 | non decreasing array | 665 | 0.242 | Medium | 11,075 |
https://leetcode.com/problems/non-decreasing-array/discuss/2201369/Python-Simple-and-Easy-Solution-O(N)-Time-complexity | class Solution:
def checkPossibility(self, nums: List[int]) -> bool:
changed = False
for i in range(len(nums) - 1):
if nums[i] <= nums[i + 1]:
continue
if changed:
return False
if i == 0 or nums[i+ 1] >= nums[i - 1]:
nums[i] = nums[i + 1]
else:
nums[i + 1] = nums[i]
changed = True
return True | non-decreasing-array | Python - Simple and Easy Solution - O(N) Time complexity | dayaniravi123 | 0 | 15 | non decreasing array | 665 | 0.242 | Medium | 11,076 |
https://leetcode.com/problems/non-decreasing-array/discuss/2195764/Simple-Python-Solutions-With-Explanation | class Solution:
def checkPossibility(self, nums: List[int]) -> bool:
i, already_changed, N = 0, False, len(nums)
while i < N - 1:
if nums[i] <= nums[i+1]:
i += 1
continue
# if nums[i] > nums[i+1] then
if already_changed:
return False
if i == 0 or (i and nums[i-1] <= nums[i+1]):
already_changed = True
else:
already_changed = True
nums[i+1] = nums[i]
i += 1
return True | non-decreasing-array | Simple Python Solutions With Explanation | atiq1589 | 0 | 32 | non decreasing array | 665 | 0.242 | Medium | 11,077 |
https://leetcode.com/problems/non-decreasing-array/discuss/2195655/Simple-For-Loop-Python | class Solution:
def checkPossibility(self, nums: List[int]) -> bool:
# break point means the position where the num is greater than the next num
break_point = None
for i in range(len(nums)-1):
if nums[i] > nums[i+1]:
# if there was already a break point, you can't replace at two indices, return False
if break_point != None:
return False
break_point = i
# if the break point was never found or if it was the first or 2nd last, return true
# you can always replace at index 0 bcoz there's nothing before it
# if the break point is at len-2, you can always replace at the last index
if break_point == None or break_point == 0 or break_point == len(nums)-2:
return True
# if you replace the num at breakpoint, check if it's surroundings are valid or not
# or if you replace the num at breakpoint+1, check if it's surroundings are valid or not
if (nums[break_point-1] <= nums[break_point+1]) or (nums[break_point] <= nums[break_point+2]):
return True
return False | non-decreasing-array | Simple For Loop - Python | nihaljoshi | 0 | 23 | non decreasing array | 665 | 0.242 | Medium | 11,078 |
https://leetcode.com/problems/non-decreasing-array/discuss/2195654/O(n)-time-O(1)-space-easy-to-understand! | class Solution:
def checkPossibility(self, nums) -> bool:
#find the decreasing number, if it at the end of the nums, return True
i=0
while i<=len(nums)-2:
if nums[i]>nums[i+1]:
break
i+=1
i+=2
if i>len(nums)-1:
return True
'''
skip the decreasing one, and compare the number with the number 1 or 2 behind it,
if both make the array still decreasing, return False
if one number behind can make the array non-decreasing, continue comparing,
if some number is greater than the next, return False
if no number is greater than the next, return Ture
'''
if (i==2 and (nums[i]>=nums[i-1] or nums[i]>=nums[i-2])) or (nums[i-1]>=nums[i-3] and nums[i]>=nums[i-1]) or (nums[i]>=nums[i-2]) :
for k in range(i,len(nums)-1):
if nums[k]>nums[k+1]:
return False
return True
else:
return False
"""
time complexity:O(n), memory complexity: O(1)
""" | non-decreasing-array | O(n) time, O(1) space, easy to understand! | XRFXRF | 0 | 26 | non decreasing array | 665 | 0.242 | Medium | 11,079 |
https://leetcode.com/problems/non-decreasing-array/discuss/2194306/Using-Stack-oror-with-comments-oror-Python | class Solution:
def checkPossibility(self, nums: List[int]) -> bool:
n=len(nums)
count=0
stack=[nums[0]]
if n==1:
return True
for i in range(1,n):
if nums[i]<stack[-1]: # if current is smaller than stack[-1]
if len(stack)==1: # when len of stack 1 will pop the value ans insert the current value
stack.pop()
stack.append(nums[i])
count+=1
elif stack[-2]<=nums[i]: # if current is smaller than stack[-1] as wel as current is greater than stack[-2] both then
count+=1
p=stack.pop()
stack.append(min(p,nums[i]))
else:
count+=1
else:
stack.append(nums[i])
if count<=1:
return True
return False | non-decreasing-array | Using Stack || with comments || Python | abhishek8090 | 0 | 19 | non decreasing array | 665 | 0.242 | Medium | 11,080 |
https://leetcode.com/problems/non-decreasing-array/discuss/2194025/easily-explained | class Solution:
def checkPossibility(self, nums: List[int]) -> bool:
cnt=0
if len(nums)==1:
return True
```appended 10^5, so that list index don't get out of range
```
nums.append(10**5)
nums.append(10**5)
for i in range (0,len(nums)-1):
if nums[i]>nums[i+1]:
``` If the list is like [4,2,3], we are setting the 4 as 2. Once the list is modified we breaking the loop```
if nums[i]>nums[i+2]:
nums[i]=nums[i+1]
break
else:
``` If the list is like [5,7,2,8], setting the 7 as 2 won't work. so we set 2 as 8```
nums[i+1]=nums[i+2]
break
```After modifying the list, if it is still not in non-decreasing order the value of count will be greater than 0```
for i in range (0,len(nums)-1):
if nums[i]>nums[i+1]:
cnt+=1
if cnt>0:
return False
else:
return True | non-decreasing-array | easily explained | Sadika12 | 0 | 11 | non decreasing array | 665 | 0.242 | Medium | 11,081 |
https://leetcode.com/problems/non-decreasing-array/discuss/2193994/Violations-Check-oror-Easy-and-Simple-Approach | class Solution:
def checkPossibility(self, nums: List[int]) -> bool:
violations = 0
n = len(nums)
for i in range(1, n):
if nums[i] < nums[i -1]:
if violations == 1:
return False
violations += 1
if i >= 2 and nums[i - 2] > nums[i]:
nums[i] = nums[i - 1]
return True | non-decreasing-array | Violations Check || Easy and Simple Approach | Vaibhav7860 | 0 | 16 | non decreasing array | 665 | 0.242 | Medium | 11,082 |
https://leetcode.com/problems/non-decreasing-array/discuss/2193836/Python-simple-greedy-oror-O(n)-time | class Solution:
def checkPossibility(self, nums: List[int]) -> bool:
# if we get a wrong pair we have two options, either we can change i-1th value or we can change ith value.
cnt=0
cnt1=0
num=nums[:] # make a deep copy
for i in range(len(nums)-1,0,-1): # change i-1th value
if nums[i-1]>nums[i]:
nums[i-1]=nums[i]
cnt+=1
for i in range(len(num)-1): # change the ith value.
if num[i]>num[i+1]:
num[i+1]=num[i]
cnt1+=1
return True if cnt<=1 or cnt1<=1 else False | non-decreasing-array | Python simple greedy || O(n) time | akshat12199 | 0 | 24 | non decreasing array | 665 | 0.242 | Medium | 11,083 |
https://leetcode.com/problems/non-decreasing-array/discuss/2193834/Python-O(n)-Solution | class Solution:
def checkPossibility(self, nums: List[int]) -> bool:
decreasing_indices = []
for i in range(1, len(nums)):
if nums[i] >= nums[i-1]:
if i -1 not in decreasing_indices:
pass
else:
prev_dec_indice = decreasing_indices[-1]-1
if nums[i] < nums[prev_dec_indice]:
if prev_dec_indice == 0:
pass
else:
prev_prev_indice = prev_dec_indice - 1
if nums[prev_prev_indice] <= nums[decreasing_indices[-1]]:
pass
else:
return False
else:
decreasing_indices.append(i)
if len(decreasing_indices) <= 1:
return True
if len(decreasing_indices) >= 2:
return False | non-decreasing-array | Python O(n) Solution | Vayne1994 | 0 | 17 | non decreasing array | 665 | 0.242 | Medium | 11,084 |
https://leetcode.com/problems/non-decreasing-array/discuss/2193681/Easy-Solution | class Solution:
def checkPossibility(self, nums: List[int]) -> bool:
chance = False
i = 0
while i < len(nums)-1:
if nums[i+1] < nums[i]:
if chance == True:
return False
else:
if i == 0:
nums[i] = nums[i+1]
else:
if nums[i-1] <= nums[i+1]:
nums[i] = nums[i+1]
else:
nums[i+1] = nums[i]
chance = True
i -= 1
if i < 0:
i = 0
else:
i += 1
return True | non-decreasing-array | Easy Solution | boxn_jumbo | 0 | 11 | non decreasing array | 665 | 0.242 | Medium | 11,085 |
https://leetcode.com/problems/non-decreasing-array/discuss/2193509/Python-or-Easy-and-clean-code-or-99-faster-submission-in-python | class Solution:
def checkPossibility(self, nums: List[int]) -> bool:
flag = False # to check whether changed is made or not
for i in range(len(nums) - 1):
if nums[i] <= nums[i+1]:
continue
if flag: # changed is made and can not be made more than one so return False
return False
# This is when nums[i-1]th element is <= nums[i+1]
if i == 0 or nums[i+1] >= nums[i-1]:
nums[i] = nums[i+1]
else:
nums[i+1] = nums[i]
flag = True
return True | non-decreasing-array | Python | Easy and clean code | 99% faster submission in python | __Asrar | 0 | 28 | non decreasing array | 665 | 0.242 | Medium | 11,086 |
https://leetcode.com/problems/non-decreasing-array/discuss/2193469/Python3-Easy | class Solution:
def checkPossibility(self, nums: List[int]) -> bool:
# First pass
modification_1 = 0
curr_highest = float('-inf') # helps keep track of cases where nums[i-1] > nums[i] but also nums[i-2] > nums[i] e.g [4, 6, 2, 4, 5]
for i in range(len(nums)):
if nums[i] < curr_highest:
modification_1 += 1
curr_highest = max(nums[i], curr_highest)
# Second pass
modification_2 = 0
curr_lowest = float('inf')
for i in range(len(nums)-1, -1, -1):
if nums[i] > curr_lowest:
modification_2 += 1
curr_lowest = min(curr_lowest, nums[i])
return modification_1 <= 1 or modification_2 <= 1 | non-decreasing-array | ✅Python3 - Easy | thesauravs | 0 | 11 | non decreasing array | 665 | 0.242 | Medium | 11,087 |
https://leetcode.com/problems/non-decreasing-array/discuss/2193447/Python3-Easy-solution | class Solution:
def checkPossibility(self, nums: List[int]) -> bool:
# First pass
# left to right scan to check number of modifications required
modification_1 = 0
# helps keep track of occurences where nums[i-1] <= nums[i] but nums[i-2] > nums[i]
curr_highest = float('-inf')
for i in range(len(nums)):
if nums[i] < curr_highest:
modification_1 += 1
curr_highest = max(nums[i], curr_highest)
# Second pass
# right to left scan to check number of modifications required
modification_2 = 0
curr_lowest = float('inf')
for i in range(len(nums)-1, -1, -1):
if nums[i] > curr_lowest:
modification_2 += 1
curr_lowest = min(curr_lowest, nums[i])
return modification_1 <= 1 or modification_2 <= 1 | non-decreasing-array | ✅Python3 - Easy solution | thesauravs | 0 | 8 | non decreasing array | 665 | 0.242 | Medium | 11,088 |
https://leetcode.com/problems/non-decreasing-array/discuss/2193402/Python-Easy-Solution | class Solution:
def checkPossibility(self, nums: List[int]) -> bool:
cnt_violations=0
for i in range(1, len(nums)):
if nums[i]<nums[i-1]:
if cnt_violations==1:
return False
cnt_violations+=1
if i>=2 and nums[i-2]>nums[i]:
nums[i]=nums[i-1]
return True | non-decreasing-array | Python Easy Solution | vaibhav0077 | 0 | 20 | non decreasing array | 665 | 0.242 | Medium | 11,089 |
https://leetcode.com/problems/non-decreasing-array/discuss/2193079/Python-one-pass | class Solution:
def checkPossibility(self, nums: List[int]) -> bool:
found = False
for i in range(1, len(nums)):
if nums[i] < nums[i-1]:
if found:
return False
found = True
if i == 1:
continue
if nums[i] < nums[i-2]:
if nums[i-1] < nums[i-2]:
return False
nums[i] = nums[i-1]
return True | non-decreasing-array | Python, one pass | blue_sky5 | 0 | 18 | non decreasing array | 665 | 0.242 | Medium | 11,090 |
https://leetcode.com/problems/non-decreasing-array/discuss/2174544/Python3-Simple-O(N)-solution-with-explanation | class Solution:
def checkPossibility(self, nums: List[int]) -> bool:
## RC ##
## APPROACH : MATH ##
## LOGIC ##
## 1. lets say nums[i] < nums[i-1] which is invalid case. Consider 2 cases to make it valid:
## 2. The array should be valid case if I replace nums[i-1] with nums[i-2] ( picking lower end for lower index i.e nums[i-2], nums[i-2], nums[i] should be non-decreasing )
## 3. or else array should be a valid case if I repalce nums[i] with nums[i+1] ( picking higher end for higher index, i.e nums[i], nums[i+1], nums[i+1] should be non decreasing )
## In any case if both are invalid, then it cannot be made non decreasing with just one change ( either 2nd change or 3rd change ) ( ex: [3,4,2,3] --> [3,3,2,3] invalid and [3,4,3,3] invalid )
def isValid(a, b, c):
if a <= b <= c:
return True
return False
if len(nums) <= 2:
return True
n = len(nums)
# To easily handle cases where abnormality is at begining
## Ex: [4, 2, 3]
changes = 0
if nums[0] > nums[1]:
nums[0] = nums[1]
changes += 1
# to handle case [1,2,4,5,3]
# To easily handle cases where abnormality is at ending
nums.append(max(nums))
nums.append(max(nums))
for i in range(2, n):
if nums[i] < nums[i-1]:
# 2nd abnormality, immediately return False
if changes == 1:
return False
#2
if isValid(nums[i-2], nums[i-2], nums[i]):
changes += 1
#3
elif isValid(nums[i-1], nums[i+1], nums[i+1]):
changes += 1
# seems like we cannot make it valid array if we change one element
else:
return False
return True | non-decreasing-array | [Python3] Simple O(N) solution with explanation | 101leetcode | 0 | 73 | non decreasing array | 665 | 0.242 | Medium | 11,091 |
https://leetcode.com/problems/non-decreasing-array/discuss/1763098/Python3-Solution-O(n) | class Solution:
def checkPossibility(self, nums: List[int]) -> bool:
if len(nums) == 1:
return True
count = 0
for i in range(1, len(nums)-1):
if nums[i-1] > nums[i+1]:
if nums[i] > nums[i+1]:
nums[i+1] = nums[i]
count += 1
if nums[i] < nums[i-1]:
nums[i-1] = nums[i]
count += 1
else:
if nums[i] > nums[i+1]:
nums[i] = nums[i+1]
count += 1
if nums[i] < nums[i-1]:
nums[i] = nums[i-1]
count += 1
if count >= 2:
return False
return True | non-decreasing-array | Python3 Solution, O(n) | AprDev2011 | 0 | 80 | non decreasing array | 665 | 0.242 | Medium | 11,092 |
https://leetcode.com/problems/non-decreasing-array/discuss/1191787/Python-O(n)-O(1)-with-comments | class Solution:
def checkPossibility(self, nums: List[int]) -> bool:
cnt = 0
n = 0
for i in range(1, len(nums)):
# the prev is less or equal the current. The array is not decreasing
if nums[i-1]<=nums[i]:
# note the previous, so we want the future items to be not bigger than n
n = nums[i-1]
elif n <= nums[i]:
cnt +=1 # increase counter because we have to "modify" the current item
else:
nums[i]=nums[i-1] # since n is greater than the current item, we have to modify the current item to the previous one to keep a non-decreasing order
cnt +=1 # increase counter because we have to "modify" the current item
# eliminate redundant iterations
if cnt > 1:
return False
return True | non-decreasing-array | Python O(n), O(1) with comments | arsamigullin | 0 | 124 | non decreasing array | 665 | 0.242 | Medium | 11,093 |
https://leetcode.com/problems/non-decreasing-array/discuss/661088/Simple-Python-solution-faster-than-95 | class Solution:
def checkPossibility(self, nums: List[int]) -> bool:
flag = True
for i in range(1, len(nums)):
if nums[i] < nums[i - 1]:
if flag == True:
flag = False
if i!= 1:
if nums[i - 2] > nums[i]:
nums[i] = nums[i - 1]
else:
return False
return True | non-decreasing-array | Simple Python solution; faster than 95% | Swap24 | 0 | 122 | non decreasing array | 665 | 0.242 | Medium | 11,094 |
https://leetcode.com/problems/non-decreasing-array/discuss/246682/Python-O(N)-BFS-no-modification-In-simple-terms | class Solution:
def checkPossibility(self, nums: List[int]) -> bool:
changes = 0
for i, j in zip(range(0, len(nums) - 1), range(1, len(nums))):
if nums[j] < nums[i]:
lchanges, rchanges = 0, 0
for x in reversed(range(0, j)):
if nums[x] > nums[j]:
lchanges += 1
if lchanges == 2:
break;
else:
break
for y in range(j, len(nums)):
if nums[y] < nums[i]:
rchanges += 1
if rchanges == 2:
break
else:
break
changes += min(lchanges, rchanges)
if changes >= 2:
return False
return True | non-decreasing-array | Python O(N) BFS no modification - In simple terms | ikaruswill | 0 | 229 | non decreasing array | 665 | 0.242 | Medium | 11,095 |
https://leetcode.com/problems/beautiful-arrangement-ii/discuss/1158414/Python3-greedy | class Solution:
def constructArray(self, n: int, k: int) -> List[int]:
lo, hi = 1, n
ans = []
while lo <= hi:
if k&1:
ans.append(lo)
lo += 1
else:
ans.append(hi)
hi -= 1
if k > 1: k -= 1
return ans | beautiful-arrangement-ii | [Python3] greedy | ye15 | 1 | 57 | beautiful arrangement ii | 667 | 0.597 | Medium | 11,096 |
https://leetcode.com/problems/beautiful-arrangement-ii/discuss/2831178/easy-understanding | class Solution:
def constructArray(self, n: int, k: int) -> List[int]:
number_tail = k // 2
start, end = [i for i in range(1, n - number_tail + 1)], [i for i in range(n, n - number_tail, -1)]
i, j = 0, 0
if k % 2 == 0:
start, end = end, start
answer = []
for i, j in zip(start, end):
answer.append(i)
answer.append(j)
if len(start) > len(end):
for i in range(len(end), len(start)):
answer.append(start[i])
if len(start) < len(end):
for i in range(len(start), len(end)):
answer.append(end[i])
return answer | beautiful-arrangement-ii | easy understanding | Yaro1 | 0 | 1 | beautiful arrangement ii | 667 | 0.597 | Medium | 11,097 |
https://leetcode.com/problems/beautiful-arrangement-ii/discuss/2820124/Python-Solution-in-O(n)-and-o(1) | class Solution:
def constructArray(self, n: int, k: int) -> List[int]:
m=k//2
ans=[0 for _ in range(n)]
i=(n-m)
j=(n-m+1)
t=n-1
if(k%2!=0):
ans[t]=i
i-=1
t-=1
while(m!=0):
ans[t]=i
t-=1
i-=1
ans[t]=j
j+=1
t-=1
m-=1
while(i>0):
ans[t]=i
i-=1
t-=1
return ans | beautiful-arrangement-ii | Python Solution in O(n) and o(1) | ng2203 | 0 | 1 | beautiful arrangement ii | 667 | 0.597 | Medium | 11,098 |
https://leetcode.com/problems/beautiful-arrangement-ii/discuss/2782563/Python-all-consecutive-differences-range-from-1-to-k. | class Solution:
def constructArray(self, n: int, k: int) -> List[int]:
ans = [1]
num = k + 1
flag = True
diff = k
while len(ans) < num:
if flag:
ans.append(ans[-1] + diff)
else:
ans.append(ans[-1] - diff)
diff -= 1
flag = not flag
cur_max = num
while len(ans) < n:
end = ans[-1]
for z in range(min(end + k, n), cur_max, -1):
ans.append(z)
cur_max = end + k
return ans | beautiful-arrangement-ii | Python, all consecutive differences range from 1 to k. | yiming999 | 0 | 3 | beautiful arrangement ii | 667 | 0.597 | Medium | 11,099 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.