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(Wrappe... | 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
... | 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(... | 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 rang... | 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... | 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... | 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
... | 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,... | 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:
a... | 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):
... | 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+... | 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... | 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:
ri... | 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:... | 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)
... | 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
... | 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... | 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
... | 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):
... | 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 ... | 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.app... | 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(a... | 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
... | 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 sub... | 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
... | 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 =... | 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: ... | 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... | 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:
... | 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)
... | 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 -... | 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 i... | 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] -... | 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... | 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-... | 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):
... | 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... | 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])... | 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
... | 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... | 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
... | 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
... | 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 nod... | 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] = mi... | 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 =... | 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()
no... | 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(... | 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.lef... | 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, no... | 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)... | 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()
... | 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 nod... | 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 wid... | 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 = ... | 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):
... | 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,... | 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... | 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)
... | 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 ... | 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()
CurrentInd... | 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... | 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, lo... | 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])
... | 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)
f... | 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
... | 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 ... | 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 ... | 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 ... | 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+... | 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] <= n... | 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 n... | 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_ite... | 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 = ... | 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]:
... | 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
i... | 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, ... | 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
... | 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:... | 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... | 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... | 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(le... | 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 =... | 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:
... | 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 s... | 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_... | 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')
fo... | 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
... | 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:
... | 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... | 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]
... | 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 ... | 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]:
... | 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] >... | 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 -=... | 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 = []
f... | 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-... | 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)
di... | 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.