From 567f57921cae0f054d3614b6f1c7b1758aeafcd9 Mon Sep 17 00:00:00 2001 From: Kattuvila Milkiyas Date: Sun, 7 Dec 2025 16:54:51 -0800 Subject: [PATCH] 2 pointers-1 completed --- 3-sum.py | 51 ++++++++++++++++++++++++++++++++++++ container-with-most-water.py | 39 +++++++++++++++++++++++++++ sort-colors.py | 26 ++++++++++++++++++ 3 files changed, 116 insertions(+) create mode 100644 3-sum.py create mode 100644 container-with-most-water.py create mode 100644 sort-colors.py diff --git a/3-sum.py b/3-sum.py new file mode 100644 index 00000000..1bccf621 --- /dev/null +++ b/3-sum.py @@ -0,0 +1,51 @@ +Run a loop through nums for each element with index i. Take l=i+1 and r=n-1. +Check the sum of the element with the element at r and l indecies. If the summation + is 0 increment the left pointer till a uniqure element is met and decrement the right + pointer. If the summation is less than 0, increse the left pointer till a unique + element is met. If the sum is greater than 0 decrese the right pointer + +Time complexity: O(n2) +Space complexity: O(1) + +class Solution(object): + + def threeSum(self, nums): + """ + :type nums: List[int] + :rtype: List[List[int]] + """ + n=len(nums) + r=n-1 + l=0 + arr=[] + nums.sort() + for ind, i in enumerate(nums): + if ind-1>=0 and i==nums[ind-1]: + continue + + l=ind+1 + r=n-1 + while lind and nums[l]==nums[l-1]: + l+=1 + continue + s= i+ nums[r]+nums[l] + if s==0: + arr.append([i,nums[l],nums[r]]) + l+=1 + r-=1 + + elif s<0: + l+=1 + else: + r-=1 + + return arr + + + + + + + + \ 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..fe679593 --- /dev/null +++ b/container-with-most-water.py @@ -0,0 +1,39 @@ +# Take two pointers l=0 r=n-1. initialize max volume with 0 +# while lheight[r]: + r-=1 + else: + l+=1 + return mvol + + + + + + + + + + + + + \ No newline at end of file diff --git a/sort-colors.py b/sort-colors.py new file mode 100644 index 00000000..d337874f --- /dev/null +++ b/sort-colors.py @@ -0,0 +1,26 @@ + +# Initialize an annray arr of length(nums) with 0 . Loop through nums, for each element +# x in nums, increment the acount of arr[x]. Iterate arr and replace nums[i] with the +# elemts in arr with their correspnding no. of times. + +# Time compleity: O(n) +# Space complexity O(1) + +class Solution(object): + def sortColors(self, nums): + """ + :type nums: List[int] + :rtype: None Do not return anything, modify nums in-place instead. + """ + arr=[0, 0, 0] + for i in nums: + arr[i]=arr[i]+1 + print(arr) + j=0 + for ind, i in enumerate(arr): + n=j + while j