diff --git a/container-most-water.py b/container-most-water.py new file mode 100644 index 00000000..f728c2ec --- /dev/null +++ b/container-most-water.py @@ -0,0 +1,17 @@ +# O(n) time, O(1) space + +# move pointers inward when height is lower +class Solution: + def maxArea(self, height: List[int]) -> int: + l=0 + r=len(height)-1 + area = 0 + while l < r: + width = r - l + if height[l]<=height[r]: + area = max(area,height[l]*width) + l+=1 + elif height[l]>height[r]: + area = max(area,height[r]*width) + r-=1 + return area \ No newline at end of file diff --git a/sort-colors.py b/sort-colors.py new file mode 100644 index 00000000..d7e5ff0f --- /dev/null +++ b/sort-colors.py @@ -0,0 +1,22 @@ + +# o(n) time, o(1) space +class Solution: + def sortColors(self, nums: List[int]) -> None: + + mid = 0 + low = 0 + high = len(nums)-1 + + while mid <= high: + + if nums[mid] == 2: + nums[mid],nums[high] = nums[high],nums[mid] + high-=1 + elif nums[mid] == 0: + nums[mid],nums[low]=nums[low],nums[mid] + mid+=1 + low+=1 + else: + mid+=1 + + return nums \ No newline at end of file diff --git a/three-sum.py b/three-sum.py new file mode 100644 index 00000000..d2f71444 --- /dev/null +++ b/three-sum.py @@ -0,0 +1,27 @@ +# time O(n^2), space O(1) +class Solution: + def threeSum(self, nums: list[int]) -> list[list[int]]: + + res=[] + for i in range(len(nums)): + #outside duplicacy + if i != 0 and nums[i] == nums[i-1]: + continue + a = nums[i] + l=i+1 + r=len(nums)-1 + while l < r: + three = a+nums[l]+nums[r] + if three > 0: + dp = nums[r] + while nums[r] == dp and r > l: + r-=1 + else: + if three == 0: + res.append([nums[i],nums[l],nums[r]]) + # if three less than 0 or three == 0, move left pointer + dup = nums[l] + while nums[l] == dup and l < r: + l+=1 + + return res