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/largest-perimeter-triangle/discuss/2693748/Python-Easy-solution
class Solution: def largestPerimeter(self, nums: list[int]) -> int: nums.sort(reverse = True) while len(nums) > 2 and nums[0] >= nums[1] + nums[2]: nums.pop(0) return sum(nums[:3]) if len(nums) > 2 else 0
largest-perimeter-triangle
Python Easy solution
faraazahmed000
0
4
largest perimeter triangle
976
0.544
Easy
15,800
https://leetcode.com/problems/largest-perimeter-triangle/discuss/2693728/PYTHONGREEDY-APPROACH-EASILY-EXPLAINED.
class Solution: def largestPerimeter(self, nums: List[int]) -> int: nums.sort(reverse=True) for a, b, c in zip(nums, nums[1:], nums[2:]): if b+c > a: return a+b+c return 0
largest-perimeter-triangle
✔PYTHON🐍GREEDY APPROACH, EASILY EXPLAINED.
shubhamdraj
0
7
largest perimeter triangle
976
0.544
Easy
15,801
https://leetcode.com/problems/largest-perimeter-triangle/discuss/2693662/Python-simple-straightforward-solution
class Solution: def largestPerimeter(self, nums: List[int]) -> int: nums.sort(reverse=True) for i in range(len(nums) - 2): if nums[i] < nums[i + 1] + nums[i + 2]: return nums[i] + nums[i + 1] + nums[i + 2] return 0
largest-perimeter-triangle
Python simple straightforward solution
meatcodex
0
2
largest perimeter triangle
976
0.544
Easy
15,802
https://leetcode.com/problems/largest-perimeter-triangle/discuss/2693326/python-solution
class Solution: def largestPerimeter(self, nums: List[int]) -> int: n=len(nums) if n<3: return 0 nums.sort(reverse=True) for i in range(3,n+1): if nums[i-1]+nums[i-2]>nums[i-3]: return sum(nums[i-3:i]) return 0
largest-perimeter-triangle
python solution
shashank_2000
0
2
largest perimeter triangle
976
0.544
Easy
15,803
https://leetcode.com/problems/largest-perimeter-triangle/discuss/2693058/python3-solution.
class Solution: def largestPerimeter(self, nums: List[int]) -> int: nums.sort() for i in range(len(nums) - 3, -1, -1): if nums[i] + nums[i + 1] > nums[i + 2]: return nums[i] + nums[i+1] + nums[i+2] else: return 0
largest-perimeter-triangle
python3 solution.
parryrpy
0
5
largest perimeter triangle
976
0.544
Easy
15,804
https://leetcode.com/problems/largest-perimeter-triangle/discuss/2692978/Python-3-Easy-solution-faster-than-96
class Solution: def largestPerimeter(self, nums: List[int]) -> int: nums.sort(reverse = True) for i in range(3,len(nums)+1): if(nums[i-3] < nums[i-2]+nums[i-1]): return sum(nums[i-3:i]) return 0
largest-perimeter-triangle
Python 3 Easy solution faster than 96%
Ritesh2345
0
1
largest perimeter triangle
976
0.544
Easy
15,805
https://leetcode.com/problems/largest-perimeter-triangle/discuss/2692971/Python-Solution-or-Sorting-or-Greedy
class Solution: def largestPerimeter(self, nums: List[int]) -> int: nums.sort(reverse=True) n=len(nums) for i in range(n-2): third_side=nums[i] for j in range(i+1, n-1, 2): if nums[j]+nums[j+1]>third_side: return third_side+nums[j]+nums[j+1] return 0
largest-perimeter-triangle
Python Solution | Sorting | Greedy
Siddharth_singh
0
4
largest perimeter triangle
976
0.544
Easy
15,806
https://leetcode.com/problems/largest-perimeter-triangle/discuss/2692914/Python-or-Easy-solution-using-sorting-or-few-lines-of-code
class Solution: def largestPerimeter(self, nums: List[int]) -> int: nums.sort() for i in range(len(nums)-1,1,-1): a,b,c = nums[i-2],nums[i-1],nums[i] if c < a + b: return a+b+c return 0
largest-perimeter-triangle
Python | Easy solution using sorting | few lines of code
__Asrar
0
4
largest perimeter triangle
976
0.544
Easy
15,807
https://leetcode.com/problems/largest-perimeter-triangle/discuss/2692873/python-simple-easyToUnderstand
class Solution: def largestPerimeter(self, nums: List[int]) -> int: def triangle(a,b,c): return (a+b>c and a+c>b and b+c>a) nums.sort() l=len(nums) while l>2: if triangle(nums[-1],nums[-2],nums[-3]): return sum(nums[i] for i in range(-1,-4,-1)) nums.pop() l-=1 return 0
largest-perimeter-triangle
python simple easyToUnderstand
VignaTejReddy
0
4
largest perimeter triangle
976
0.544
Easy
15,808
https://leetcode.com/problems/largest-perimeter-triangle/discuss/2692868/PYTHON3-oror-EASY-TO-UNDERSTAND-oror-BRUTE-FORCE-SOLUTION
class Solution: def largestPerimeter(self, nums: List[int]) -> int: maxx=0 nums.sort() for i in range(0, len(nums)-2): s1=nums[i] s2=nums[i+1] s3=nums[i+2] if s2+s3>s1 and s1+s3>s2 and s1+s2>s3: if maxx<(s1+s2+s3): maxx=(s1+s2+s3) return maxx
largest-perimeter-triangle
PYTHON3 || EASY TO UNDERSTAND || BRUTE FORCE SOLUTION
pratiyushray2152
0
1
largest perimeter triangle
976
0.544
Easy
15,809
https://leetcode.com/problems/largest-perimeter-triangle/discuss/2692765/Python3-or-easy-and-simple-or-O(logN)
class Solution: def largestPerimeter(self, nums: List[int]) -> int: nums.sort(reverse = True) for i in range(2,len(nums)): if nums[i] + nums[i - 1] > nums[i - 2]: return nums[i] + nums[i - 1] + nums[i - 2] return 0
largest-perimeter-triangle
Python3 | easy and simple | O(logN)
Kumada_Takuya
0
4
largest perimeter triangle
976
0.544
Easy
15,810
https://leetcode.com/problems/largest-perimeter-triangle/discuss/2692669/Easy-and-Faster
class Solution: def largestPerimeter(self, A: List[int]) -> int: A.sort() N = len(A) res = 0 for i in range(N - 1, 1, -1): if A[i - 2] + A[i - 1] > A[i]: return A[i - 2] + A[i - 1] + A[i] return 0
largest-perimeter-triangle
Easy and Faster
Raghunath_Reddy
0
3
largest perimeter triangle
976
0.544
Easy
15,811
https://leetcode.com/problems/largest-perimeter-triangle/discuss/2692650/Python-Easy-Solution-oror-Largest-Perimeter-Triangle
class Solution: def largestPerimeter(self, nums: List[int]) -> int: nums.sort(reverse=True) for a,b,c in zip(nums,nums[1:],nums[2:]): if b+c>a: return a+b+c return 0
largest-perimeter-triangle
Python Easy Solution || Largest Perimeter Triangle
Motaharozzaman1996
0
3
largest perimeter triangle
976
0.544
Easy
15,812
https://leetcode.com/problems/largest-perimeter-triangle/discuss/2692599/Python3-Sort-and-try-Max-with-concise-way-of-getting-3-edges
class Solution: def largestPerimeter(self, nums: List[int]) -> int: nums.sort() n = len(nums) for i in range(n - 3, -1, -1): a, b, c = nums[i:i+3] # Very nice way of getting the 3 edges if a + b > c: return sum([a, b, c]) return 0
largest-perimeter-triangle
[Python3] Sort, and try Max with concise way of getting 3 edges
JoeH
0
8
largest perimeter triangle
976
0.544
Easy
15,813
https://leetcode.com/problems/largest-perimeter-triangle/discuss/2692545/Python-sort
class Solution: def largestPerimeter(self, nums: List[int]) -> int: nums.sort(reverse=True) for i in range(len(nums)-2): if nums[i] < nums[i+1] + nums[i+2]: return nums[i] + nums[i+1] + nums[i+2] return 0
largest-perimeter-triangle
Python, sort
blue_sky5
0
10
largest perimeter triangle
976
0.544
Easy
15,814
https://leetcode.com/problems/largest-perimeter-triangle/discuss/2692518/Triangle-Inequality-or-Math-quickly-explained
class Solution: def largestPerimeter(self, nums: List[int]) -> int: nums.sort(reverse = True) for c, b, a in zip(nums, nums[1:], nums[2:]): if a + b > c: return a + b + c return 0
largest-perimeter-triangle
Triangle Inequality | Math quickly explained
sr_vrd
0
3
largest perimeter triangle
976
0.544
Easy
15,815
https://leetcode.com/problems/largest-perimeter-triangle/discuss/2692467/Python-simple-solution
class Solution: def largestPerimeter(self, nums: List[int]) -> int: nums.sort(reverse = True) for idx in range(len(nums) - 2): if nums[idx] < nums[idx+1] + nums[idx+2]: return sum(nums[idx:idx+3]) return 0
largest-perimeter-triangle
Python simple solution
Terry_Lah
0
3
largest perimeter triangle
976
0.544
Easy
15,816
https://leetcode.com/problems/largest-perimeter-triangle/discuss/2692414/Python-Short-and-Simple
class Solution: def largestPerimeter(self, nums: List[int]) -> int: nums.sort(reverse=True) for i in range(len(nums)-2): x = nums[i+1] + nums[i+2] if nums[i] < x: return nums[i] + x return 0
largest-perimeter-triangle
[Python] Short and Simple
Paranoidx
0
7
largest perimeter triangle
976
0.544
Easy
15,817
https://leetcode.com/problems/largest-perimeter-triangle/discuss/2664883/Python3-solutions
class Solution: def largestPerimeter(self, nums: List[int]) -> int: nums.sort(reverse = True) for i in range(len(nums) - 2): a = nums[i] # longest side b = nums[i + 1] c = nums[i + 2] if b + c > a: return a + b + c return 0
largest-perimeter-triangle
Python3 solutions
AnzheYuan1217
0
22
largest perimeter triangle
976
0.544
Easy
15,818
https://leetcode.com/problems/largest-perimeter-triangle/discuss/2664883/Python3-solutions
class Solution: def largestPerimeter(self, nums: List[int]) -> int: nums.sort(reverse = True) for a, b, c in zip(nums, nums[1:], nums[2:]): if b + c > a: return a + b + c return 0
largest-perimeter-triangle
Python3 solutions
AnzheYuan1217
0
22
largest perimeter triangle
976
0.544
Easy
15,819
https://leetcode.com/problems/largest-perimeter-triangle/discuss/2664301/Python-or-Greedy-sorting-or-O(nlog(n))
class Solution: def largestPerimeter(self, nums: List[int]) -> int: nums.sort() i = len(nums) - 1 while i != 1: a, b, c = nums[i - 2], nums[i - 1], nums[i] if a < b + c and b < a + c and c < a + b: return a + b + c i -= 1 return 0
largest-perimeter-triangle
Python | Greedy sorting | O(nlog(n))
LordVader1
0
17
largest perimeter triangle
976
0.544
Easy
15,820
https://leetcode.com/problems/largest-perimeter-triangle/discuss/2496341/Python-or-Easy-and-Fast-Solution
class Solution: def largestPerimeter(self, nums: List[int]) -> int: # Condition of a triangle a<(b+c) and a>=b>=c nums=sorted(nums,reverse=True) for i in range(len(nums)-2): if nums[i]<nums[i+1]+nums[i+2]: return nums[i] + nums[i+1] + nums[i+2] return 0
largest-perimeter-triangle
Python | Easy and Fast Solution
kathanbhavsar
0
88
largest perimeter triangle
976
0.544
Easy
15,821
https://leetcode.com/problems/squares-of-a-sorted-array/discuss/310865/Python%3A-A-comparison-of-lots-of-approaches!-Sorting-two-pointers-deque-iterator-generator
class Solution: def sortedSquares(self, A: List[int]) -> List[int]: return_array = [0] * len(A) write_pointer = len(A) - 1 left_read_pointer = 0 right_read_pointer = len(A) - 1 left_square = A[left_read_pointer] ** 2 right_square = A[right_read_pointer] ** 2 while write_pointer >= 0: if left_square > right_square: return_array[write_pointer] = left_square left_read_pointer += 1 left_square = A[left_read_pointer] ** 2 else: return_array[write_pointer] = right_square right_read_pointer -= 1 right_square = A[right_read_pointer] ** 2 write_pointer -= 1 return return_array
squares-of-a-sorted-array
Python: A comparison of lots of approaches! [Sorting, two pointers, deque, iterator, generator]
Hai_dee
386
20,500
squares of a sorted array
977
0.719
Easy
15,822
https://leetcode.com/problems/squares-of-a-sorted-array/discuss/310865/Python%3A-A-comparison-of-lots-of-approaches!-Sorting-two-pointers-deque-iterator-generator
class Solution: def generate_sorted_squares(self, nums): # Start by doing our binary search to find where # to place the pointers. left = 0 right = len(nums) while right - left > 1: mid = left + (right - left) // 2 if nums[mid] > 0: right = mid else: left = mid # And now the main generator loop. The condition is the negation # of the StopIteration condition for the iterator approach. while left >= 0 or right < len(nums): if left < 0: right += 1 yield nums[right - 1] ** 2 elif right >= len(nums): left -= 1 yield nums[left + 1] ** 2 else: left_square = nums[left] ** 2 right_square = nums[right] ** 2 if left_square < right_square: left -= 1 yield left_square else: right += 1 yield right_square def sortedSquares(self, A: List[int]) -> List[int]: return list(self.generate_sorted_squares(A))
squares-of-a-sorted-array
Python: A comparison of lots of approaches! [Sorting, two pointers, deque, iterator, generator]
Hai_dee
386
20,500
squares of a sorted array
977
0.719
Easy
15,823
https://leetcode.com/problems/squares-of-a-sorted-array/discuss/283978/Python-Two-Pointers
class Solution: def sortedSquares(self, A: List[int]) -> List[int]: result = [None for _ in A] left, right = 0, len(A) - 1 for index in range(len(A)-1, -1, -1): if abs(A[left]) > abs(A[right]): result[index] = A[left] ** 2 left += 1 else: result[index] = A[right] ** 2 right -= 1 return result
squares-of-a-sorted-array
Python Two Pointers
aquafie
72
10,200
squares of a sorted array
977
0.719
Easy
15,824
https://leetcode.com/problems/squares-of-a-sorted-array/discuss/1419437/Python-or-Two-Pointers-solution-or-O(n)
class Solution: def sortedSquares(self, nums: List[int]) -> List[int]: i = 0 n = len(nums) j = n - 1 new = [0] * n k = n - 1 while i <= j: if abs(nums[i]) < abs(nums[j]): new[k] = nums[j] ** 2 j -= 1 else: new[k] = nums[i] ** 2 i += 1 k -= 1 return new
squares-of-a-sorted-array
Python | Two-Pointers solution | O(n)
Shreya19595
11
1,500
squares of a sorted array
977
0.719
Easy
15,825
https://leetcode.com/problems/squares-of-a-sorted-array/discuss/2806619/Simple-python-solution-by-queue
class Solution: def sortedSquares(self, nums: List[int]) -> List[int]: res = [] num_deque = collections.deque(nums) while num_deque: left = num_deque[0] ** 2 right = num_deque[-1] ** 2 if left > right: res.append(left) num_deque.popleft() else: res.append(right) num_deque.pop() return res[::-1]
squares-of-a-sorted-array
😎 Simple python solution by queue
Pragadeeshwaran_Pasupathi
6
414
squares of a sorted array
977
0.719
Easy
15,826
https://leetcode.com/problems/squares-of-a-sorted-array/discuss/2406220/2-Pointers-fully-explained-or-Python-3-or-O(n)-or-79.29-faster
class Solution: def sortedSquares(self, nums: List[int]) -> List[int]: # Solution with 2 Pointers # Time Complexity: O(n) Space Complexity: O(n) """ 1. Initialize two pointers: lowValue = 0; highValue = len(nums) - 1 2. Create a list with same length as nums to store squared values arranged in non decreasing order 3. Loop through the nums array "Backwards" (last index to 0) For each i, compare the absolute values of given list at the lowValue and highValue indexes 3a. If absolute value of element at index lowValue >= absolute value of element at index highValue: - Element of index i of new list = square (element at index lowValue) - lowValue += l (Increment lowValue) 3b. Else if absolute value of element at index lowValue < absolute value of element at index highValue: - Element of index i of new list = square (element at index highValue) - highValue -= l (Decrement highValue) """ # Step 1. lowValue = 0 highValue = len(nums) - 1 # Step 2. nums_square = [None] * int(len(nums)) # Step 3. for i in range(len(nums) - 1, -1, -1): # Step 3a. if abs(nums[lowValue]) >= abs(nums[highValue]): nums_square[i] = nums[lowValue] * nums[lowValue] lowValue+=1 # Step 3b else: nums_square[i] = nums[highValue] * nums[highValue] highValue-=1 return nums_square
squares-of-a-sorted-array
2 Pointers fully explained | Python 3 | O(n) | 79.29% faster
harishmanjunatheswaran
4
169
squares of a sorted array
977
0.719
Easy
15,827
https://leetcode.com/problems/squares-of-a-sorted-array/discuss/1903311/Most-efficient-python-solution-using-two-pointers-approach.
class Solution: def sortedSquares(self, nums: List[int]) -> List[int]: l=0 r=len(nums)-1 ans=[0]*len(nums) for i in range(len(nums)-1,-1,-1): if nums[l]**2<nums[r]**2: ans[i]=nums[r]**2 r-=1 else: ans[i]=nums[l]**2 l+=1 return ans
squares-of-a-sorted-array
Most efficient python solution using two-pointers approach.
tkdhimanshusingh
4
258
squares of a sorted array
977
0.719
Easy
15,828
https://leetcode.com/problems/squares-of-a-sorted-array/discuss/1874940/Python3-Two-Pointers-approach
class Solution: def sortedSquares(self, nums: List[int]) -> List[int]: length = len(nums) start, end = 0, length - 1 res = [0]*length index = -1 while start <= end: if abs(nums[start]) > abs(nums[end]): res[index] = nums[start] * nums[start] start += 1 else: res[index] = nums[end] * nums[end] end -= 1 index -= 1 return res
squares-of-a-sorted-array
Python3 - Two Pointers approach
eliasroodrigues
4
167
squares of a sorted array
977
0.719
Easy
15,829
https://leetcode.com/problems/squares-of-a-sorted-array/discuss/1541316/Python-O-(n)-Solution
class Solution: def sortedSquares(self, nums: List[int]) -> List[int]: i, j = 0, len(nums)-1 res = [None] * (j + 1) for r in range(j, -1, -1): if abs(nums[i]) > abs(nums[j]): res[r] = nums[i] ** 2 i += 1 else: res[r] = nums[j] ** 2 j -= 1 else: return res
squares-of-a-sorted-array
Python O (n) Solution
aaffriya
4
541
squares of a sorted array
977
0.719
Easy
15,830
https://leetcode.com/problems/squares-of-a-sorted-array/discuss/2319821/Python-O(n)-solution-explained
class Solution: def sortedSquares(self, nums: List[int]) -> List[int]: result = [] left, right = 0, len(nums) - 1 while left <= right: if nums[left] ** 2 < nums[right] ** 2: result.append(nums[right] ** 2) right -= 1 else: result.append(nums[left] ** 2) left += 1 return result[::-1]
squares-of-a-sorted-array
Python O(n) solution explained
Balance-Coffee
3
204
squares of a sorted array
977
0.719
Easy
15,831
https://leetcode.com/problems/squares-of-a-sorted-array/discuss/2163842/Small-and-large-pointer-approach-or-Python-or-90
class Solution: def sortedSquares(self, nums: List[int]) -> List[int]: sortedSquare = [0 for _ in range(len(nums))] smallidx= 0 largeidx= len(nums)-1 for idx in reversed(range(len(nums))): smallVal = nums[smallidx] largeVal = nums[largeidx] if abs(smallVal) > abs(largeVal): sortedSquare[idx] = smallVal*smallVal smallidx+=1 else: sortedSquare[idx] = largeVal*largeVal largeidx-=1 return sortedSquare
squares-of-a-sorted-array
Small and large pointer approach | Python | 90%
bliqlegend
3
159
squares of a sorted array
977
0.719
Easy
15,832
https://leetcode.com/problems/squares-of-a-sorted-array/discuss/1476082/O(N*log(N))-to-O(N)-oror-Intuition-explained-greatergreater-Merge-Process
class Solution: def sortedSquares(self, nums: List[int]) -> List[int]: output = [] for i in nums: square = i * i output.append(square) output.sort() return output
squares-of-a-sorted-array
O(N*log(N)) to O(N) || Intuition explained -->> Merge Process
aarushsharmaa
3
329
squares of a sorted array
977
0.719
Easy
15,833
https://leetcode.com/problems/squares-of-a-sorted-array/discuss/1476082/O(N*log(N))-to-O(N)-oror-Intuition-explained-greatergreater-Merge-Process
class Solution: def sortedSquares(self, nums: List[int]) -> List[int]: n = len(nums) answer = [] #i will point to the right side, that is, increasing array from ith index to (n-1)th index, or from 1st positive element #j will point to left side, that is, increasing array from (i-1)th index till 0th index #to get the index of first element >= 0 for i in range(0, n): if nums[i] >= 0: break #negative element will lie from 0th index till (i-1)th index #and if we move from (i-1)th index till 0th index,we will be moving in increasing fashion j = i - 1 while (j >= 0 and i <= n-1): #two pointers approach #comparing first positive element's square to first negative element's square if (nums[i] * nums[i]) <= (nums[j] * nums[j]): answer.append(nums[i] * nums[i]) i += 1 else: answer.append(nums[j] * nums[j]) j -= 1 while (j >= 0): #it means that copy all remaining elements from jth index till 0th index answer.append(nums[j] * nums[j]) j -= 1 while (i <= n-1): #it means that copy all elements from ith index till (n-1)th index answer.append(nums[i] * nums[i]) i += 1 return answer
squares-of-a-sorted-array
O(N*log(N)) to O(N) || Intuition explained -->> Merge Process
aarushsharmaa
3
329
squares of a sorted array
977
0.719
Easy
15,834
https://leetcode.com/problems/squares-of-a-sorted-array/discuss/1035653/Python3-%22Two-pointers-approach%22
class Solution: def sortedSquares(self, nums: List[int]) -> List[int]: l = [] i = 0 j = len(nums)-1 while i <= j: a= nums[i]*nums[i] b = nums[j]*nums[j] if a > b: l.insert(0,a) i += 1 else: l.insert(0,b) j -= 1 return l
squares-of-a-sorted-array
Python3 "Two pointers approach"
EklavyaJoshi
3
186
squares of a sorted array
977
0.719
Easy
15,835
https://leetcode.com/problems/squares-of-a-sorted-array/discuss/2415230/Python-O(n)-Accurate-Method-Two-Pointers-l-and-r-oror-Documented
class Solution: # Two Pointer: O(n) def sortedSquares(self, nums: List[int]) -> List[int]: n = len(nums) result = [0] * n # initialize result array with 0 l, r = 0, n-1 # two pointers left and right of the array # start from last position to 0th position in the result array for i in range(n-1, -1, -1): sl, sr = nums[l]**2, nums[r]**2 # calculate the squares of numbers at left and right if sl > sr: # if square at left is greater result[i] = sl # set square of left into result at i l += 1 # forward left pointer else: result[i] = sr # set square of right into result at i r -= 1 # backward right pointer return result
squares-of-a-sorted-array
[Python] O(n)-Accurate Method - Two Pointers l & r || Documented
Buntynara
2
56
squares of a sorted array
977
0.719
Easy
15,836
https://leetcode.com/problems/squares-of-a-sorted-array/discuss/2054712/Python-Solution-91-fast-and-99-less-space
class Solution: def sortedSquares(self, nums: List[int]) -> List[int]: l=[] for i in range(len(nums)): a=nums[i]*nums[i] nums[i]=a nums.sort() return nums
squares-of-a-sorted-array
Python Solution 91% fast and 99% less space
pranjalmishra334
2
178
squares of a sorted array
977
0.719
Easy
15,837
https://leetcode.com/problems/squares-of-a-sorted-array/discuss/1899743/Python-3-Solution
class Solution: def sortedSquares(self, nums: List[int]) -> List[int]: first = 0 last = len(nums) - 1 answer = [0] * len(nums) while first <= last: left, right = abs(nums[first]), abs(nums[last]) if left > right: answer[last - first] = left ** 2 first += 1 else: answer[last - first] = right ** 2 last -= 1 return answer
squares-of-a-sorted-array
Python 3 Solution
AprDev2011
2
117
squares of a sorted array
977
0.719
Easy
15,838
https://leetcode.com/problems/squares-of-a-sorted-array/discuss/2472916/Python-two-solutions.
class Solution: def sortedSquares(self, nums): listLength = len(nums) sortedNums = [0]*listLength # n extra space for i in range(listLength): # O(n) if nums[i] < 0: nums[i] *= -1 i = listLength-1 l, r = 0, listLength-1 while i >= 0: # O(n) if nums[l] > nums[r]: sortedNums[i] = nums[l] # O(1) l+=1 else: sortedNums[i] = nums[r] # O(1) r-=1 i-=1 for i in range(listLength): # O(n) sortedNums[i] *= sortedNums[i] return sortedNums
squares-of-a-sorted-array
Python two solutions.
OsamaRakanAlMraikhat
1
95
squares of a sorted array
977
0.719
Easy
15,839
https://leetcode.com/problems/squares-of-a-sorted-array/discuss/2472916/Python-two-solutions.
class Solution: def sortedSquares(self, nums): for i in range(0,len(nums)): # O(n) nums[i] *= nums[i] # O(1) return sorted(nums) # O(nlogn)
squares-of-a-sorted-array
Python two solutions.
OsamaRakanAlMraikhat
1
95
squares of a sorted array
977
0.719
Easy
15,840
https://leetcode.com/problems/squares-of-a-sorted-array/discuss/2463693/Python-Solution-builtin-function-oror-beginner-friendly
class Solution: def sortedSquares(self, nums: List[int]) -> List[int]: l=[] for i in range(len(nums)): l.append(nums[i]*nums[i]) l.sort() return l
squares-of-a-sorted-array
Python Solution - builtin function || beginner friendly
T1n1_B0x1
1
61
squares of a sorted array
977
0.719
Easy
15,841
https://leetcode.com/problems/squares-of-a-sorted-array/discuss/2337496/EASY-5-line-python-code
class Solution: def sortedSquares(self, nums: List[int]) -> List[int]: squares = [] for i in nums: squares.append(int(i*i)) squares.sort() return squares
squares-of-a-sorted-array
EASY 5 line python code
adithya_s_k
1
59
squares of a sorted array
977
0.719
Easy
15,842
https://leetcode.com/problems/squares-of-a-sorted-array/discuss/2309995/Python-Two-Different-Two-Pointer-Solutions
class Solution: def sortedSquares(self, nums: List[int]) -> List[int]: res = [] l, r = 0, len(nums) - 1 # With pointers are each end, append the one that has the greater square to return array while l <= r: lsquare = nums[l] * nums[l] rsquare = nums[r] * nums[r] if lsquare > rsquare: res.append(lsquare) l += 1 else: res.append(rsquare) r -= 1 # res is in descending order because the two pointers started at the ends, which have the largest values - so reverse it res.reverse() return res
squares-of-a-sorted-array
Python - Two Different Two Pointer Solutions
Reinuity
1
75
squares of a sorted array
977
0.719
Easy
15,843
https://leetcode.com/problems/squares-of-a-sorted-array/discuss/2309995/Python-Two-Different-Two-Pointer-Solutions
class Solution: def sortedSquares(self, nums: List[int]) -> List[int]: # Initialize an array with dummy info of length nums so you can start placing largest values from right to left res = [None] * len(nums) l, r = 0, len(nums) - 1 # Iterate through your initialized array from right to left, adding the greater between the left and right values squared for i in range(len(res) - 1, -1, -1): lsquare = nums[l] * nums[l] rsquare = nums[r] * nums[r] if lsquare > rsquare: res[i] = lsquare l += 1 else: res[i] = rsquare r -= 1 return res
squares-of-a-sorted-array
Python - Two Different Two Pointer Solutions
Reinuity
1
75
squares of a sorted array
977
0.719
Easy
15,844
https://leetcode.com/problems/squares-of-a-sorted-array/discuss/2309995/Python-Two-Different-Two-Pointer-Solutions
class Solution: def sortedSquares(self, nums: List[int]) -> List[int]: # Square for i in range(len(nums)): nums[i] = nums[i] * nums[i] # Sort nums.sort() return nums
squares-of-a-sorted-array
Python - Two Different Two Pointer Solutions
Reinuity
1
75
squares of a sorted array
977
0.719
Easy
15,845
https://leetcode.com/problems/squares-of-a-sorted-array/discuss/2238508/Python3-Explanation-Achieving-O(N)-using-Two-Pointers
class Solution: def sortedSquares(self, nums: List[int]) -> List[int]: # Initialize two pointers at opposite ends of the array which will be used for comparisons l = 0 r = len(nums) - 1 # Populate array with null values to match the length of the 'nums' array result = [None for i in range(len(nums))] # Iterate backwards as we want to populate our result array with the largest values first for i in reversed(range(len(nums))): # If the right pointer's value is larger than left, add that value to our array and decrement the right pointer if abs(nums[r]) > abs(nums[l]): result[i] = nums[r]**2 r -= 1 # Otherwise we add the left pointers value and increment the left pointer else: result[i] = nums[l]**2 l += 1 return result
squares-of-a-sorted-array
[Python3] [Explanation] Achieving O(N) using Two Pointers
shrined
1
74
squares of a sorted array
977
0.719
Easy
15,846
https://leetcode.com/problems/squares-of-a-sorted-array/discuss/2231896/Python-Two-Pointers-Time-O(N)-or-Space-O(N)-or-O(1)-Explained
class Solution: def sortedSquares(self, nums: List[int]) -> List[int]: result = [0 for i in range(len(nums))] left = 0 right = len(nums) - 1 for i in range(len(result) - 1, -1, -1): if abs(nums[left]) >= abs(nums[right]): result[i] = nums[left] ** 2 left += 1 else: result[i] = nums[right] ** 2 right -= 1 return result
squares-of-a-sorted-array
[Python] Two Pointers Time O(N) | Space O(N) or O(1) Explained
Symbolistic
1
110
squares of a sorted array
977
0.719
Easy
15,847
https://leetcode.com/problems/squares-of-a-sorted-array/discuss/2231896/Python-Two-Pointers-Time-O(N)-or-Space-O(N)-or-O(1)-Explained
class Solution: def sortedSquares(self, nums: List[int]) -> List[int]: result = [i for i in range(len(nums))] left = 0 right = len(nums) - 1 for i in range(len(result) - 1, -1, -1): leftNum = nums[left] ** 2 rightNum = nums[right] ** 2 if leftNum >= rightNum: result[i] = leftNum left += 1 else: result[i] = rightNum right -= 1 return result
squares-of-a-sorted-array
[Python] Two Pointers Time O(N) | Space O(N) or O(1) Explained
Symbolistic
1
110
squares of a sorted array
977
0.719
Easy
15,848
https://leetcode.com/problems/squares-of-a-sorted-array/discuss/2175915/Python3-oror-Simplest-and-Raw-logic-oror-O(N)-Sol.-Beats-99-oror-Explained
class Solution: def sortedSquares(self, nums: List[int]) -> List[int]: n = len(nums) res = [] # check last index of -ve num neg = -1 for i in range(n): if nums[i] > -1: break else: neg = i # If no +ve num found return sq from back if i == n-1: return [i*i for i in nums[::-1]] # If no -ve num found return sq from strt if neg == -1: return [i*i for i in nums] # Convert all element into +ve nums = [abs(i) for i in nums] # Classic 2 pointer where l = last -ve index &amp; r = first +ve index # Since all nums converted into +ves so if nums[l] < nums[r] than its # squre will also be smallest compared to all ele so add in res and l -= 1 # Simi, with r and rest is understood l, r = neg, neg+1 while l > -1 and r < n: if nums[l] < nums[r]: res.append(nums[l] * nums[l]) l -= 1 else: res.append(nums[r]*nums[r]) r += 1 while r < n: res.append(nums[r]*nums[r]) r += 1 while l > -1: res.append(nums[l] * nums[l]) l -= 1 return res
squares-of-a-sorted-array
Python3 || Simplest and Raw logic || O(N) Sol. Beats 99% || Explained
Dewang_Patil
1
174
squares of a sorted array
977
0.719
Easy
15,849
https://leetcode.com/problems/squares-of-a-sorted-array/discuss/2094098/Python3-from-nlogn-to-O(N)
class Solution: def sortedSquares(self, nums: List[int]) -> List[int]: # return self.squaresOfASortedArrayOptimalTwo(nums) return self.squaresOfASortedArrayWithSorting(nums) # O(n) || O(n) # runtime: 344ms 36.34% def squaresOfASortedArrayOptimalTwo(self, array): if not array: return 0 newArray = [0] * len(array) left, right = 0, len(array) - 1 j = len(newArray) - 1 while left <= right: num1 = abs(array[left]) num2 = abs(array[right]) if num1 > num2: newArray[j] = pow(num1, 2) left += 1 else: newArray[j] = pow(num2, 2) right -= 1 j -= 1 return newArray # O(nlogn) || O(1) # runtime: 352ms 34.00% def squaresOfASortedArrayWithSorting(self, array): if not array: return array array = sorted([pow(x, 2) for x in array]) return array
squares-of-a-sorted-array
Python3 from nlogn to O(N)
arshergon
1
174
squares of a sorted array
977
0.719
Easy
15,850
https://leetcode.com/problems/squares-of-a-sorted-array/discuss/2061459/simple-python-solution-or208-ms-faster-than-98.07-of-Python3-online-submissions
class Solution: def sortedSquares(self, nums: List[int]) -> List[int]: for i in range(len(nums)): nums[i] = nums[i] * nums[i] return sorted(nums)
squares-of-a-sorted-array
simple python solution |208 ms, faster than 98.07% of Python3 online submissions
user3245t
1
58
squares of a sorted array
977
0.719
Easy
15,851
https://leetcode.com/problems/squares-of-a-sorted-array/discuss/2041701/Python3-or-Two-solutions-explained
class Solution: def sortedSquares(self, nums: List[int]) -> List[int]: return sorted([x * x for x in nums])
squares-of-a-sorted-array
Python3 | Two solutions explained
manfrommoon
1
169
squares of a sorted array
977
0.719
Easy
15,852
https://leetcode.com/problems/squares-of-a-sorted-array/discuss/2041701/Python3-or-Two-solutions-explained
class Solution: def sortedSquares(self, nums: List[int]) -> List[int]: left_pointer, right_pointer = 0, len(nums) - 1 result = [] while left_pointer <= right_pointer: if abs(nums[left_pointer]) >= abs(nums[right_pointer]): result.append(nums[left_pointer]**2) left_pointer += 1 else: result.append(nums[right_pointer]**2) right_pointer -= 1 return result[::-1]
squares-of-a-sorted-array
Python3 | Two solutions explained
manfrommoon
1
169
squares of a sorted array
977
0.719
Easy
15,853
https://leetcode.com/problems/squares-of-a-sorted-array/discuss/1902195/100-working-Easiest-method-with-O(n.logn)-Time-complexity
class Solution: def sortedSquares(self, nums: List[int]) -> List[int]: for i in range(len(nums)): nums[i]=nums[i]**2 nums.sort() return nums
squares-of-a-sorted-array
100% working Easiest method with O(n.logn) Time complexity
tkdhimanshusingh
1
96
squares of a sorted array
977
0.719
Easy
15,854
https://leetcode.com/problems/squares-of-a-sorted-array/discuss/1876862/Python-l-Pointers
class Solution: def sortedSquares(self, nums: List[int]) -> List[int]: n = len(nums) i = 0 j = n-1 p = n-1 square = [0]*n while i <= j: x = nums[i]**2 y = nums[j]**2 if x > y: square[p] = x i += 1 else: square[p] = y j -= 1 p -= 1 return square
squares-of-a-sorted-array
Python l Pointers
morpheusdurden
1
85
squares of a sorted array
977
0.719
Easy
15,855
https://leetcode.com/problems/squares-of-a-sorted-array/discuss/1858119/python-easy-to-read-and-understand-or-two-pointers
class Solution: def sortedSquares(self, nums: List[int]) -> List[int]: res = [] i, j = 0, len(nums)-1 while i <= j: if abs(nums[i]) > abs(nums[j]): res = [nums[i]**2] + res i = i+1 else: res = [nums[j]**2] + res j = j-1 return res
squares-of-a-sorted-array
python easy to read and understand | two-pointers
sanial2001
1
208
squares of a sorted array
977
0.719
Easy
15,856
https://leetcode.com/problems/squares-of-a-sorted-array/discuss/1760386/2-Solutions%3A-1-row-solution-and-two-pointers-solution
class Solution: def sortedSquares(self, nums: List[int]) -> List[int]: return sorted([x**2 for x in nums])
squares-of-a-sorted-array
2 Solutions: 1-row solution and two-pointers solution
lior1509
1
139
squares of a sorted array
977
0.719
Easy
15,857
https://leetcode.com/problems/squares-of-a-sorted-array/discuss/1760386/2-Solutions%3A-1-row-solution-and-two-pointers-solution
class Solution: def sortedSquares(self, nums: List[int]) -> List[int]: left,right = 0,len(nums)-1 results = [] while left<=right: if abs(nums[left])>abs(nums[right]): results.append(nums[left]**2) left += 1 else: results.append(nums[right]**2) right -= 1 return results[::-1]
squares-of-a-sorted-array
2 Solutions: 1-row solution and two-pointers solution
lior1509
1
139
squares of a sorted array
977
0.719
Easy
15,858
https://leetcode.com/problems/squares-of-a-sorted-array/discuss/1734661/Python3-%3A-Two-line-solution-with-lambda-Timsort-O(N)
class Solution: def sortedSquares(self, nums: [int]) -> [int]: sorted_nums = sorted(nums, key=lambda x:abs(x)) # not using sort() in order not to overwrite the input array return [x**2 for x in sorted_nums]
squares-of-a-sorted-array
Python3 : Two line solution with lambda, Timsort, O(N)
poobhat
1
113
squares of a sorted array
977
0.719
Easy
15,859
https://leetcode.com/problems/squares-of-a-sorted-array/discuss/1612960/Python3-Simple-O(n)-Two-pointer-approach
class Solution: def sortedSquares(self, nums: List[int]) -> List[int]: &nbsp; &nbsp; &nbsp; &nbsp;length = len(nums) ans = [0] * length i, j, k = 0, length - 1, length -1 while(i <= j): first, second = abs(nums[i]), abs(nums[j]) if first < second: ans[k] = second ** 2 j -= 1 else: ans[k] = first ** 2 i += 1 k -= 1 return ans
squares-of-a-sorted-array
Python3 Simple O(n) Two pointer approach
rajatrj20
1
285
squares of a sorted array
977
0.719
Easy
15,860
https://leetcode.com/problems/squares-of-a-sorted-array/discuss/1561414/O(n-log-n)-faster-than-the-O(n)-solution
class Solution: def sortedSquares(self, nums: List[int]) -> List[int]: return sorted([x*x for x in nums])
squares-of-a-sorted-array
O(n log n) faster than the O(n) solution?
hemersontacon
1
204
squares of a sorted array
977
0.719
Easy
15,861
https://leetcode.com/problems/squares-of-a-sorted-array/discuss/1561414/O(n-log-n)-faster-than-the-O(n)-solution
class Solution: def sortedSquares(self, nums: List[int]) -> List[int]: result = [] i = 0 j = len(nums)-1 while i <= j: if abs(nums[i]) > abs(nums[j]): x = nums[i] i+=1 else: x = nums[j] j-=1 result.append(x*x) return result[::-1]
squares-of-a-sorted-array
O(n log n) faster than the O(n) solution?
hemersontacon
1
204
squares of a sorted array
977
0.719
Easy
15,862
https://leetcode.com/problems/squares-of-a-sorted-array/discuss/1524041/An-amazing-approach-in-O(n)-by-Sanchez-oror-Python
class Solution: def sortedSquares(self, nums: List[int]) -> List[int]: l,r=0,len(nums)-1 co=r out=[0]*(r+1) while(l<=r): if abs(nums[l])>abs(nums[r]): out[co]=nums[l]**2 l+=1 else: out[co]=nums[r]**2 r-=1 co-=1 return out
squares-of-a-sorted-array
An amazing approach in O(n) by Sanchez || Python
RickSanchez101
1
185
squares of a sorted array
977
0.719
Easy
15,863
https://leetcode.com/problems/squares-of-a-sorted-array/discuss/1450819/Python3-Solution-without-reverse
class Solution: def sortedSquares(self, nums: List[int]) -> List[int]: res = [0] * len(nums) left, right = 0, len(nums) - 1 while left <= right: left_val = abs(nums[left]) right_val = abs(nums[right]) if left_val < right_val: res[right - left] = right_val ** 2 right -= 1 else: res[right - left] = left_val ** 2 left += 1 return res
squares-of-a-sorted-array
[Python3] Solution without reverse
maosipov11
1
71
squares of a sorted array
977
0.719
Easy
15,864
https://leetcode.com/problems/squares-of-a-sorted-array/discuss/1223760/Python3-decent-solution-with-comments-as-explanation
class Solution: def sortedSquares(self, nums: List[int]) -> List[int]: n = len(nums) i = 0 # to traverse from the begining of the list j = n - 1 # to traverse from the ending of the list k = n - 1 # to fill new list from end # create same size list before hand, if we just create and empty list like # result = [] and keep inserting from the front of the list, it takes more time # instead create list before hand fill it in O(1) time. result = list(range(n)) while i <= j: neg_square = nums[i]*nums[i] pos_square = nums[j]*nums[j] if neg_square < pos_square: # fill from the back of the list result[k] = pos_square j = j - 1 else: # fill from the back of the list result[k] = neg_square i = i + 1 k = k - 1 return result
squares-of-a-sorted-array
Python3 decent solution with comments as explanation
NagaVenkatesh
1
221
squares of a sorted array
977
0.719
Easy
15,865
https://leetcode.com/problems/squares-of-a-sorted-array/discuss/1146965/99.9-faster-solution-with-2-lines-of-code-and-easy-to-understand
class Solution: def sortedSquares(self, nums: List[int]) -> List[int]: res = [i*i for i in nums] res.sort(reverse=False) return res
squares-of-a-sorted-array
99.9% faster solution with 2 lines of code and easy to understand
vashisht7
1
151
squares of a sorted array
977
0.719
Easy
15,866
https://leetcode.com/problems/squares-of-a-sorted-array/discuss/632502/JavaPython3-2-pointers
class Solution: def sortedSquares(self, A: List[int]) -> List[int]: lo, hi = 0, len(A)-1 ans = [None]*len(A) while lo <= hi: if abs(A[lo]) < abs(A[hi]): ans[hi - lo] = A[hi]**2 hi -= 1 else: ans[hi - lo] = A[lo]**2 lo += 1 return ans
squares-of-a-sorted-array
[Java/Python3] 2 pointers
ye15
1
163
squares of a sorted array
977
0.719
Easy
15,867
https://leetcode.com/problems/squares-of-a-sorted-array/discuss/632502/JavaPython3-2-pointers
class Solution: def sortedSquares(self, nums: List[int]) -> List[int]: ans = [0] * len(nums) lo, hi = 0, len(nums)-1 for i in reversed(range(len(nums))): if abs(nums[lo]) >= abs(nums[hi]): ans[i] = nums[lo] * nums[lo] lo += 1 else: ans[i] = nums[hi] * nums[hi] hi -= 1 return ans
squares-of-a-sorted-array
[Java/Python3] 2 pointers
ye15
1
163
squares of a sorted array
977
0.719
Easy
15,868
https://leetcode.com/problems/squares-of-a-sorted-array/discuss/632502/JavaPython3-2-pointers
class Solution: def sortedSquares(self, A: List[int]) -> List[int]: for i in range(len(A)): A[i] *= A[i] A.sort() return A
squares-of-a-sorted-array
[Java/Python3] 2 pointers
ye15
1
163
squares of a sorted array
977
0.719
Easy
15,869
https://leetcode.com/problems/squares-of-a-sorted-array/discuss/353723/Solution-in-Python-3-(beats-~99)-(one-line)
class Solution: def sortedSquares(self, A: List[int]) -> List[int]: return sorted(i*i for i in A) - Junaid Mansuri (LeetCode ID)@hotmail.com
squares-of-a-sorted-array
Solution in Python 3 (beats ~99%) (one line)
junaidmansuri
1
568
squares of a sorted array
977
0.719
Easy
15,870
https://leetcode.com/problems/squares-of-a-sorted-array/discuss/2849405/Python-Simple-one-liner-code!
class Solution(object): def sortedSquares(self, nums): return sorted([i ** 2 for i in nums])
squares-of-a-sorted-array
✅Python - Simple one liner code!
Nematulloh
0
1
squares of a sorted array
977
0.719
Easy
15,871
https://leetcode.com/problems/squares-of-a-sorted-array/discuss/2847163/Python-1-line
class Solution: def sortedSquares(self, nums: List[int]) -> List[int]: return sorted([value ** 2 for value in nums])
squares-of-a-sorted-array
Python 1 line
yijiun
0
1
squares of a sorted array
977
0.719
Easy
15,872
https://leetcode.com/problems/squares-of-a-sorted-array/discuss/2846743/python3
class Solution: def sortedSquares(self, nums: List[int]) -> List[int]: return sorted(list(map(lambda i: i ** 2, nums)))
squares-of-a-sorted-array
python3
Geniuss87
0
1
squares of a sorted array
977
0.719
Easy
15,873
https://leetcode.com/problems/squares-of-a-sorted-array/discuss/2830930/Squares-of-a-Sorted-Array-or-Python-3.x-or-O(n)
class Solution: def sortedSquares(self, nums: List[int]) -> List[int]: result = [] left = 0 right = len(nums) - 1 while True: if left == right: result.append(nums[left] * nums[left]) break if abs(nums[left]) >= abs(nums[right]): result.append(nums[left] * nums[left]) left += 1 elif abs(nums[right]) > abs(nums[left]): result.append(nums.pop() ** 2) right -= 1 return result[:: -1]
squares-of-a-sorted-array
Squares of a Sorted Array | Python 3.x | O(n)
SnLn
0
3
squares of a sorted array
977
0.719
Easy
15,874
https://leetcode.com/problems/squares-of-a-sorted-array/discuss/2830775/Easy-to-understand-two-liner-solution-(faster-than-96-solutions)-or-Python-3
class Solution: def sortedSquares(self, nums: List[int]) -> List[int]: l=[i**2 for i in nums] l.sort() return l
squares-of-a-sorted-array
Easy to understand two liner solution (faster than 96% solutions) | Python 3
divyankrawat2021
0
2
squares of a sorted array
977
0.719
Easy
15,875
https://leetcode.com/problems/squares-of-a-sorted-array/discuss/2828990/Simple-Python-program-with-no-extra-space-needed
class Solution: def sortedSquares(self, nums: List[int]) -> List[int]: for i in range(len(nums)): nums[i] = nums[i]**2 nums.sort() return nums
squares-of-a-sorted-array
Simple Python program with no extra space needed
shashank00818
0
1
squares of a sorted array
977
0.719
Easy
15,876
https://leetcode.com/problems/longest-turbulent-subarray/discuss/1464950/Python3-Longest-Turbulent-Subarray-O(n)-(one-pass)
class Solution: def maxTurbulenceSize(self, arr: List[int]) -> int: cur, mx, t = 1, 1, None for i in range(1, len(arr)): # Start of subarray if t == None: if arr[i] != arr[i-1]: cur = 2 t = arr[i] > arr[i-1] # Valid element in subarray, continue cur subarray elif (t and arr[i] < arr[i-1]) or (not t and arr[i] > arr[i-1]): cur += 1; t = not t # Invalid element in subarray, start new subarray else: if arr[i] == arr[i-1]: t = None mx = max(mx, cur) cur = 2 return max(mx, cur)
longest-turbulent-subarray
✅ [Python3] Longest Turbulent Subarray O(n) (one pass)
vscala
2
207
longest turbulent subarray
978
0.474
Medium
15,877
https://leetcode.com/problems/longest-turbulent-subarray/discuss/1464825/Python3-No-DP-Simple-Solution-or-O(N)-Time-and-O(1)-Space
class Solution: def maxTurbulenceSize(self, arr: List[int]) -> int: def cmp(odd, prev, curr): return curr < prev if odd else curr > prev n = len(arr) ans = 1 for flip in [False, True]: l = 0 for r in range(1, n): odd = r &amp; 1 prev = arr[r-1] curr = arr[r] if flip: odd = not odd if not cmp(odd, prev, curr): l = r ans = max(ans, r-l+1) return ans
longest-turbulent-subarray
[Python3] No DP Simple Solution | O(N) Time & O(1) Space
chaudhary1337
2
140
longest turbulent subarray
978
0.474
Medium
15,878
https://leetcode.com/problems/longest-turbulent-subarray/discuss/2745829/Python-TC-%3A-97-SC%3A-O(1)
class Solution: def maxTurbulenceSize(self, arr: List[int]) -> int: l, r ,output, n =0, 0, 0, len(arr) if n==1: return 1 while r < n: while r<n-1 and (arr[r-1]>arr[r]<arr[r+1] or arr[r-1]<arr[r]>arr[r+1]): r+=1 while l < r and arr[l]==arr[l+1]: l+=1 output = max(output,r-l+1) l=r r+=1 return output
longest-turbulent-subarray
Python T/C : 97% S/C: O(1)
user6230Om
1
145
longest turbulent subarray
978
0.474
Medium
15,879
https://leetcode.com/problems/longest-turbulent-subarray/discuss/2841656/DP-with-Greedy-Kadane's-algorithm-python-one-pass-solution
class Solution: def maxTurbulenceSize(self, arr: List[int]) -> int: # [inc, dec] N = len(arr) dp = [[1, 1] for _ in range(N)] for i in range(1, N): j = i - 1 if arr[i] > arr[j]: dp[i][0] = max(dp[i][0], dp[j][1] + 1) elif arr[i] < arr[j]: dp[i][1] = max(dp[i][1], dp[j][0] + 1) else: dp[i] = [1, 1] ret = -math.inf for pair in dp: for item in pair: ret = max(ret, item) return ret
longest-turbulent-subarray
DP with Greedy / Kadane's algorithm / python one-pass solution
Lara_Craft
0
5
longest turbulent subarray
978
0.474
Medium
15,880
https://leetcode.com/problems/longest-turbulent-subarray/discuss/2797605/Python-(Simple-Dynamic-Programming)
class Solution: def maxTurbulenceSize(self, arr): n = len(arr) up, down = [0]*n, [0]*n up[0], down[0] = 1, 1 for i in range(1,n): if arr[i] > arr[i-1]: up[i] = down[i-1] + 1 down[i] = 1 elif arr[i] < arr[i-1]: down[i] = up[i-1] + 1 up[i] = 1 else: up[i] = 1 down[i] = 1 return max(max(up),max(down))
longest-turbulent-subarray
Python (Simple Dynamic Programming)
rnotappl
0
2
longest turbulent subarray
978
0.474
Medium
15,881
https://leetcode.com/problems/longest-turbulent-subarray/discuss/2784375/O(N)-solution-with-flags
class Solution: def maxTurbulenceSize(self, arr: List[int]) -> int: res = 1 curr = 1 flag = None max_curr = 1 if len(arr) == 1: return 1 if arr[1]>arr[0]: flag = False else: flag = True for i in range(1,len(arr)): if arr[i-1]>arr[i] and flag==True: curr+=1 flag = False elif arr[i-1]<arr[i] and flag == False: curr+=1 flag = True else: max_curr = max(curr, max_curr) if arr[i-1]>arr[i]: curr = 2 flag = False elif arr[i-1]<arr[i]: curr = 2 flag = True else: curr = 1 return max(curr,max_curr)
longest-turbulent-subarray
O(N) solution with flags
pranav_hq
0
5
longest turbulent subarray
978
0.474
Medium
15,882
https://leetcode.com/problems/longest-turbulent-subarray/discuss/2605735/Python-3-sliding-window-super-easy-%2B-explanation
class Solution: def maxTurbulenceSize(self, arr: List[int]) -> int: if len(set(arr)) == 1: return 1 longest = 2 curr = 2 for i in range(1, len(arr) - 1): if arr[i - 1] > arr[i] and arr[i] < arr[i + 1]: curr += 1 elif arr[i - 1] < arr[i] and arr[i] > arr[i + 1]: curr += 1 else: curr = 2 longest = max(curr, longest) return longest
longest-turbulent-subarray
Python 3 sliding window - super easy + explanation
zakmatt
0
16
longest turbulent subarray
978
0.474
Medium
15,883
https://leetcode.com/problems/longest-turbulent-subarray/discuss/1981353/PYTHON-SOL-LEETCODE-WITH-COMPLETE-EXPLANATION-oror-WELL-EXPLAINED-oror-SLIDING-WINDOW-oror
class Solution: def maxTurbulenceSize(self, arr: List[int]) -> int: def cmp(a,b): if a == b: return 0 if a > b : return 1 return -1 n = len(arr) ans = 1 prev = 0 for i in range(1,n): c = cmp(arr[i-1],arr[i]) if c == 0: # we shift prev to i prev = i elif i == n-1 or c * cmp(arr[i],arr[i+1]) != -1: ans = ans if ans > i - prev + 1 else i - prev + 1 prev = i return ans
longest-turbulent-subarray
PYTHON SOL LEETCODE WITH COMPLETE EXPLANATION || WELL EXPLAINED || SLIDING WINDOW ||
reaper_27
0
45
longest turbulent subarray
978
0.474
Medium
15,884
https://leetcode.com/problems/longest-turbulent-subarray/discuss/1548869/Python3-Deque-Sliding-Window-Solution
class Solution: def maxTurbulenceSize(self, arr: List[int]) -> int: def iterating(arr): prev = arr[0] tmp = None for x in arr[1:]: if x == prev: yield '=' elif x > prev: yield '<' else: yield '>' prev = x queue = deque([]) ans = 0 for x in iterating(arr): if x == '=': queue.clear() continue if queue and x == queue[-1]: queue.clear() queue.append(x) ans = max(ans, len(queue)) return ans+1
longest-turbulent-subarray
[Python3] Deque Sliding Window Solution
whitehatbuds
0
52
longest turbulent subarray
978
0.474
Medium
15,885
https://leetcode.com/problems/longest-turbulent-subarray/discuss/1465119/Easiest-Greedy-Approach-oror-97-faster-oror-Well-Explained-with-Example
class Solution: def maxTurbulenceSize(self, arr: List[int]) -> int: n=len(arr) if max(arr)==min(arr): return 1 # If all elements are equal. if n<3: return n # if size of array is less then 3. left, right, res = [0]*n, [0]*n, [0]*n for i in range(1,n): left[i] = 1 if arr[i]>arr[i-1] else -1 if arr[i]<arr[i-1] else 0 ind = n-i-1 right[ind] = 1 if arr[ind]>arr[ind+1] else -1 if arr[ind]<arr[ind+1] else 0 for i in range(1,n): if left[i]==right[i]: res[i]=res[i-1]+1 return max(res)+2
longest-turbulent-subarray
🐍 Easiest - Greedy Approach || 97% faster || Well-Explained with Example 📌📌
abhi9Rai
0
51
longest turbulent subarray
978
0.474
Medium
15,886
https://leetcode.com/problems/longest-turbulent-subarray/discuss/1001053/Python-3-Faster-than-100
class Solution: def maxTurbulenceSize(self, arr: List[int]) -> int: if len(arr) <= 1: return len(arr) if len(arr) == 2 and arr[0] != arr[1]: return 2 if len(arr) == 2: return 1 max_len = 2 ans = max_len is_last_increasing = (arr[0] < arr[1]) if arr[0] == arr[1]: return self.maxTurbulenceSize(arr[1:]) for i in range(2, len(arr)): if is_last_increasing: if arr[i-1] > arr[i]: is_last_increasing = False max_len += 1 else: ans = max(ans, max_len) if arr[i-1] == arr[i]: max_len = 1 else: max_len = 2 else: if arr[i-1] < arr[i]: is_last_increasing = True max_len += 1 else: ans = max(ans, max_len) if arr[i-1] == arr[i]: max_len = 1 else: max_len = 2 return max(ans, max_len)
longest-turbulent-subarray
Python 3 Faster than 100%
EddyLin
0
50
longest turbulent subarray
978
0.474
Medium
15,887
https://leetcode.com/problems/longest-turbulent-subarray/discuss/982318/Python3-linear-scan-O(N)
class Solution: def maxTurbulenceSize(self, arr: List[int]) -> int: ans = cnt = 1 prev = 0 for i in range(1, len(arr)): if arr[i-1] == arr[i]: cnt = 1 elif prev * (arr[i] - arr[i-1]) >= 0: cnt = 2 # reset else: cnt += 1 ans = max(ans, cnt) prev = arr[i] - arr[i-1] return ans
longest-turbulent-subarray
[Python3] linear scan O(N)
ye15
0
60
longest turbulent subarray
978
0.474
Medium
15,888
https://leetcode.com/problems/longest-turbulent-subarray/discuss/982318/Python3-linear-scan-O(N)
class Solution: def maxTurbulenceSize(self, arr: List[int]) -> int: ans = cnt = 0 for i in range(len(arr)): if i >= 2 and (arr[i-2] > arr[i-1] < arr[i] or arr[i-2] < arr[i-1] > arr[i]): cnt += 1 elif i >= 1 and arr[i-1] != arr[i]: cnt = 2 else: cnt = 1 ans = max(ans, cnt) return ans
longest-turbulent-subarray
[Python3] linear scan O(N)
ye15
0
60
longest turbulent subarray
978
0.474
Medium
15,889
https://leetcode.com/problems/longest-turbulent-subarray/discuss/470159/Python3-96.53-(496-ms)25.00-(16.7-MB)-O(n)-time-O(1)-space-one-pointer
class Solution: def maxTurbulenceSize(self, A: List[int]) -> int: index = 0 A_len = len(A) A_len_ = A_len - 1 current_length = 1 max_length = 1 while (A_len - index > max_length): while (index < A_len_ and A[index + 1] == A[index]): index += 1 if (A_len - index > max_length): faktor = 1 if A[index] > A[index + 1] else -1 index += 1 current_length = 2 while (index < A_len_ and faktor * A[index] < faktor * A[index + 1]): faktor = -faktor current_length += 1 index += 1 if (current_length > max_length): max_length = current_length return max_length
longest-turbulent-subarray
Python3 96.53% (496 ms)/25.00% (16.7 MB) -- O(n) time / O(1) space -- one pointer
numiek_p
0
90
longest turbulent subarray
978
0.474
Medium
15,890
https://leetcode.com/problems/distribute-coins-in-binary-tree/discuss/2797049/Very-short-concise-Python-solution-with-DFS
class Solution: def distributeCoins(self, v: Optional[TreeNode], parent=None) -> int: if v is None: return 0 m = self.distributeCoins(v.left, v) + self.distributeCoins(v.right, v) if v.val != 1: parent.val += v.val - 1 m += abs(v.val - 1) return m
distribute-coins-in-binary-tree
Very short, concise Python solution with DFS
metaphysicalist
0
4
distribute coins in binary tree
979
0.721
Medium
15,891
https://leetcode.com/problems/distribute-coins-in-binary-tree/discuss/1635888/Recursive-solution-76-speed
class Solution: def distributeCoins(self, root: TreeNode) -> int: count = 0 def traverse(node: TreeNode) -> int: nonlocal count if not node: return 0 move = node.val + traverse(node.left) + traverse(node.right) - 1 count += abs(move) return move traverse(root) return count
distribute-coins-in-binary-tree
Recursive solution, 76% speed
EvgenySH
0
124
distribute coins in binary tree
979
0.721
Medium
15,892
https://leetcode.com/problems/distribute-coins-in-binary-tree/discuss/982693/Python3-post-order-dfs
class Solution: def distributeCoins(self, root: TreeNode) -> int: def fn(node): """Return surplus and number of moves at node.""" if not node: return 0, 0 # surplus | move xtr0, mv0 = fn(node.left) xtr1, mv1 = fn(node.right) return node.val - 1 + xtr0 + xtr1, mv0 + mv1 + abs(xtr0) + abs(xtr1) return fn(root)[1]
distribute-coins-in-binary-tree
[Python3] post-order dfs
ye15
0
87
distribute coins in binary tree
979
0.721
Medium
15,893
https://leetcode.com/problems/distribute-coins-in-binary-tree/discuss/982693/Python3-post-order-dfs
class Solution: def distributeCoins(self, root: TreeNode) -> int: def fn(node): """Return flux (surplus/deficit) of node.""" nonlocal ans if not node: return 0 left, right = fn(node.left), fn(node.right) ans += abs(left) + abs(right) return node.val - 1 + left + right # surplus/deficit ans = 0 fn(root) return ans
distribute-coins-in-binary-tree
[Python3] post-order dfs
ye15
0
87
distribute coins in binary tree
979
0.721
Medium
15,894
https://leetcode.com/problems/unique-paths-iii/discuss/1535158/Python-Backtracking%3A-Easy-to-understand-with-Explanation
class Solution: def uniquePathsIII(self, grid: List[List[int]]) -> int: # first, prepare the starting and ending points # simultaneously, record all the non-obstacle coordinates start = end = None visit = set() for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j] == 0: visit.add((i, j)) elif grid[i][j] == 1: start = (i, j) elif grid[i][j] == 2: end = (i, j) visit.add((i, j)) def backtrack(x, y, visit): if (x, y) == end: # implement success condition: valid only if there are no more coordinates to visit return len(visit) == 0 result = 0 # assume no valid paths by default # we need to try every possible path from this coordinate if (x-1, y) in visit: # the coordinate directly above this one is non-obstacle, try that path visit.remove((x-1, y)) # first, note down the 'visited status' of the coordinate result += backtrack(x-1, y, visit) # then, DFS to find all valid paths from that coordinate visit.add((x-1, y)) # last, reset the 'visited status' of the coordinate if (x+1, y) in visit: # the coordinate directly below this one is non-obstacle, try that path visit.remove((x+1, y)) result += backtrack(x+1, y, visit) visit.add((x+1, y)) if (x, y-1) in visit: # the coordinate directly to the left of this one is non-obstacle, try that path visit.remove((x, y-1)) result += backtrack(x, y-1, visit) visit.add((x, y-1)) if (x, y+1) in visit: # the coordinate directly to the right of this one is non-obstacle, try that path visit.remove((x, y+1)) result += backtrack(x, y+1, visit) visit.add((x, y+1)) return result return backtrack(start[0], start[1], visit) # we start from the starting point, backtrack all the way back, and consolidate the result
unique-paths-iii
Python Backtracking: Easy-to-understand with Explanation
zayne-siew
74
3,500
unique paths iii
980
0.797
Hard
15,895
https://leetcode.com/problems/unique-paths-iii/discuss/1535158/Python-Backtracking%3A-Easy-to-understand-with-Explanation
class Solution: def uniquePathsIII(self, grid: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) # iterate through the grid to get relevant info start = None # to store starting point count = 0 # to count number of squares to walk over for i in range(m): for j in range(n): count += grid[i][j] == 0 if not start and grid[i][j] == 1: start = (i, j) def backtrack(i: int, j: int) -> int: """ Backtracking algo to find all valid paths from (i, j). :param i: Index of row (where top = 0) of coordinate. :param j: Index of column (where left = 0) of coordinate. :returns: Total number of valid paths from (i, j). """ nonlocal count result = 0 for x, y in ((i-1, j), (i+1, j), (i, j-1), (i, j+1)): # border check if 0 <= x < m and 0 <= y < n: if grid[x][y] == 0: # traverse down this path grid[x][y] = -1 count -= 1 result += backtrack(x, y) # backtrack and reset grid[x][y] = 0 count += 1 elif grid[x][y] == 2: # check if all squares have been walked over result += count == 0 return result # perform DFS + backtracking to find valid paths return backtrack(start[0], start[1])
unique-paths-iii
Python Backtracking: Easy-to-understand with Explanation
zayne-siew
74
3,500
unique paths iii
980
0.797
Hard
15,896
https://leetcode.com/problems/unique-paths-iii/discuss/1184821/Python3-backtracking-and-bitmask-dp
class Solution: def uniquePathsIII(self, grid: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) # dimensions empty = 0 for i in range(m): for j in range(n): if grid[i][j] == 1: start = (i, j) elif grid[i][j] == 0: empty += 1 # empty squares def fn(i, j, empty): """Count paths via backtracking.""" nonlocal ans if grid[i][j] == 2: if empty == -1: ans += 1 return grid[i][j] = -1 # mark as visited for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j): if 0 <= ii < m and 0 <= jj < n and grid[ii][jj] != -1: fn(ii, jj, empty-1) grid[i][j] = 0 # backtracking ans = 0 fn(*start, empty) return ans
unique-paths-iii
[Python3] backtracking & bitmask dp
ye15
7
230
unique paths iii
980
0.797
Hard
15,897
https://leetcode.com/problems/unique-paths-iii/discuss/1184821/Python3-backtracking-and-bitmask-dp
class Solution: def uniquePathsIII(self, grid: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) mask = 0 for i in range(m): for j in range(n): if grid[i][j] == 1: start = (i, j) if grid[i][j] in (-1, 1): mask ^= 1 << i*n+j @cache def fn(i, j, mask): """Return unique paths from (i, j) to end""" if grid[i][j] == 2 and mask == (1<<m*n) - 1: return 1 ans = 0 for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j): if 0 <= ii < m and 0 <= jj < n: kk = ii*n + jj if not mask &amp; 1<<kk: ans += fn(ii, jj, mask ^ 1<<kk) return ans return fn(*start, mask)
unique-paths-iii
[Python3] backtracking & bitmask dp
ye15
7
230
unique paths iii
980
0.797
Hard
15,898
https://leetcode.com/problems/unique-paths-iii/discuss/1842954/Clean-Python-DFSBacktracking-Solution
class Solution: def uniquePathsIII(self, grid: List[List[int]]) -> int: row_movements = [1, -1, 0, 0] # Possible changes in row index col_movements = [0, 0, 1, -1] # Possible changes in row index ways = 0 # Answer variable max_row = len(grid) max_col = len(grid[0]) total = max_row * max_col # Total number of blocks to cover for r in range(max_row): for c in range(max_col): if grid[r][c] == -1: # Remove the blocks which are obstacles total -= 1 def backtrack(row, col, visited, current_count): # Current row, col, visited indices and number of blocks traversed so far. nonlocal ways if grid[row][col] == 2 and current_count >= total: # Breaking conditions met ways += 1 return for i in range(4): # 4 Possible movements from a certain row, column index r = row + row_movements[i] c = col + col_movements[i] if 0 <= r < max_row and 0 <= c < max_col and grid[r][c] != -1 and not visited[r][c]: # If the new r, c index is in range, is not an obstacle and is not yet visited visited[r][c] = True # Traverse forward with visited set to true backtrack(r, c, visited, current_count + 1) # DFS traversal visited[r][c] = False # Backtrack by setting visited to false for r in range(max_row): for c in range(max_col): if grid[r][c] == 1: # Starting index found visited = [[False] * max_col for _ in range(max_row)] visited[r][c] = True # Set starting index to True backtrack(r, c, visited, 1) # Start DFS from starting index return ways return 0
unique-paths-iii
Clean Python DFS/Backtracking Solution
anCoderr
3
130
unique paths iii
980
0.797
Hard
15,899