diff --git a/3sum.py b/3sum.py new file mode 100644 index 00000000..d542fa9e --- /dev/null +++ b/3sum.py @@ -0,0 +1,47 @@ +''' +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 +''' +class Solution: + def threeSum(self, nums): + n = len(nums) + result = [] + nums.sort() + for i in range(n - 2): + if i > 0 and nums[i] == nums[i - 1]: + continue + left = i + 1 + right = n - 1 + + while left < right: + total = nums[i] + nums[left] + nums[right] + + if total == 0: + result.append([nums[i], nums[left], nums[right]]) + left += 1 + right -= 1 + + while left < right and nums[left] == nums[left - 1]: + left += 1 + + while left < right and nums[right] == nums[right + 1]: + right -= 1 + + elif total < 0: + left += 1 + else: + right -= 1 + + return result + + + +s = Solution() +nums = [-1,0,1,2,-1,-4] +print(s.threeSum(nums)) +nums = [0,1,1] +print(s.threeSum(nums)) +nums = [0,0,0] +print(s.threeSum(nums)) diff --git a/container-with-most-water.py b/container-with-most-water.py new file mode 100644 index 00000000..2648804b --- /dev/null +++ b/container-with-most-water.py @@ -0,0 +1,41 @@ +class Solution: + ''' + TC: O(n) + SC: O(1) + Leetcode: Solved the problem + Issue: No issue + ''' + def maxArea(self, height): + low = 0 + high = len(height) - 1 + res = 0 + while low <= high: + h = min(height[low], height[high]) + w = high - low + res = max(res, h*w) + if height[low] < height[high]: + low += 1 + else: + high -= 1 + return res + + ''' + TC: O(n^2) + SC: O(1) + ''' + def maxArea(self, height): + n = len(height) + res = 0 + for i in range(n-1): + for j in range(1, n): + h = min(height[i], height[j]) + w = j - i + res = max(res, h*w) + return res + + +s = Solution() +height = [1,8,6,2,5,4,8,3,7] +print(s.maxArea(height)) +height = [1,1] +print(s.maxArea(height)) \ No newline at end of file diff --git a/sort-colors.py b/sort-colors.py new file mode 100644 index 00000000..f2a029e5 --- /dev/null +++ b/sort-colors.py @@ -0,0 +1,23 @@ +''' +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 sortColors(self, nums): + n = len(nums) + low = 0 + mid = 0 + high = n - 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 + elif nums[mid] == 1: + mid += 1