diff --git a/3sum.py b/3sum.py new file mode 100644 index 00000000..dcfc3491 --- /dev/null +++ b/3sum.py @@ -0,0 +1,36 @@ +''' Time Complexity : O(n^2) + Space Complexity : O(1) + Did this code successfully run on Leetcode : Yes + Any problem you faced while coding this : No + + + Approach : Fix the 1st number and run 2sum on rest array using TWO - pointers +''' +class Solution: + def threeSum(self, nums: List[int]) -> List[List[int]]: + nums.sort() + print(nums) + n = len(nums) + res = [] + for i in range(n-1): + if i > 0 and nums[i] == nums[i-1]: + continue + l, r = i+1, n-1 + while l < r: + summ = nums[i] + nums[l] + nums[r] + if summ == 0: + res.append([nums[i],nums[l],nums[r]]) + l += 1 + r -= 1 + while l < r and nums[l] == nums[l-1]: + l += 1 + while l < r and nums[r] == nums[r+1]: + r -= 1 + elif summ > 0: + r -= 1 + else: + l += 1 + return res + + + \ No newline at end of file diff --git a/container-with-most-water.py b/container-with-most-water.py new file mode 100644 index 00000000..11749e9e --- /dev/null +++ b/container-with-most-water.py @@ -0,0 +1,21 @@ +''' Time Complexity : O(n) + Space Complexity : O(1) + Did this code successfully run on Leetcode : Yes + Any problem you faced while coding this : No +''' + +class Solution: + def maxArea(self, height: List[int]) -> int: + n= len(height) + l, r = 0, n-1 + maxarea = 0 + while l < r: + h = min(height[l],height[r]) + w = (r - l) + area = h * w + maxarea = max(maxarea, area) + if height[l] < height[r]: + l += 1 + else: + r -= 1 + return maxarea \ No newline at end of file diff --git a/sort-colors.py b/sort-colors.py new file mode 100644 index 00000000..b4dd454e --- /dev/null +++ b/sort-colors.py @@ -0,0 +1,34 @@ +''' Time Complexity : O(n) + Space Complexity : O(1) + Did this code successfully run on Leetcode : Yes + Any problem you faced while coding this : No + + + Approach : Use 3 pointers, 1 for collecting 0, one for collecting 2, and mid to iterate array + swap the elements so that, 0s are at left, 2s are at right and 1s are at the middle + +''' + +class Solution: + def sortColors(self, nums: List[int]) -> None: + """ + Do not return anything, modify nums in-place instead. + """ + n = len(nums) + l, mid, r = 0, 0 , n-1 + def swap(nums, x, y): + temp = nums[x] + nums[x] = nums[y] + nums[y] = temp + + while mid <= r: + if nums[mid] == 2: + swap(nums,mid,r) + r -= 1 + elif nums[mid] == 0: + swap(nums,mid,l) + l += 1 + mid += 1 + else: + mid += 1 + \ No newline at end of file