Striver 79
Next Permutation
def nextPermutation(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
ind = -1
n = len(nums)
for i in range(n-2,-1,-1):
if nums[i] < nums[i+1]:
ind = i
break
if ind == -1:
return nums.reverse()
for i in range(n-1,ind-1,-1):
if nums[i] > nums[ind]:
nums[i],nums[ind] = nums[ind], nums[i]
break
nums[ind+1:n] = reversed(nums[ind+1:n])
return nums
Three Sum
def threeSum(self, nums: List[int]) -> List[List[int]]:
ans = []
nums.sort()
for i in range(len(nums)):
j,k = i+1,len(nums)-1
if i > 0 and nums[i] == nums[i - 1]: continue
while(j<k):
temp_sum = nums[i] + nums[j] + nums[k]
if temp_sum < 0: j += 1
elif temp_sum > 0: k -= 1
else:
ans.append([nums[i], nums[j], nums[k]])
j,k = j+1, k-1
while j < k and nums[j] == nums[j - 1]: j += 1
while j < k and nums[k] == nums[k + 1]: k -= 1
return ans
Maximum Subarray
def maxSubArray(self, nums: List[int]) -> int:
max1 = float('-inf')
sum1 = 0
for i in range(len(nums)):
sum1 +=nums[i]
if sum1 > max1:
max1 = sum1
if sum1 < 0:
sum1 = 0
return max1
Max Product Subarray
def maxProduct(self, nums: List[int]) -> int:
pre = 1
suf = 1
max1= -1000
n = len(nums)
for i in range(n):
if pre == 0: pre=1
if suf == 0: suf=1
pre=nums[i]*pre
suf=nums[n-1-i]*suf
max1 = max(max1, max(pre, suf))
return int(max1)
Binary Search
Search in Rotated Array
def search(self, nums: List[int], target: int) -> bool:
low = 0
high = len(nums)-1
while(low<=high):
mid = (low+high)//2
if (nums[mid] == target): return True
if nums[low] == nums[mid] and nums[mid] == nums[high]:
low +=1
high -=1
continue
if nums[low] <= nums[mid]:
if nums[low] <= target and target <= nums[mid]:
high = mid - 1
else:
low = mid + 1
else:
if nums[mid] <= target and target <= nums[high]:
low = mid + 1
else:
high = mid - 1
return False
Minimum in Rotated Sorted Array
def findMin(self, nums: List[int]) -> int:
low = 0
high = len(nums)
ans = float('inf')
while (low < high):
mid = (low+high)//2
if nums[low]<= nums[mid]:
ans = min(ans,nums[low])
low = mid +1
else:
high = mid-1
ans = min(ans,nums[mid])
return ans
Find peak element
def findPeakElement(self, nums: List[int]) -> int:
n = len(nums)
if n == 1: return 0
if nums[0] > nums[1]: return 0
if nums[n-1] > nums[n-2]: return n-1
low = 1
high = n-1
while low <= high:
mid = (low+high)//2
if((mid == 0 or nums[mid] > nums[mid-1]) and (mid == n-1 or nums[mid] > nums[mid+1])):
return mid
elif(mid > 0 and nums[mid-1] > nums[mid]):
high = mid - 1
else:
low = mid + 1
return -1