diff --git a/Problem1.java b/Problem1.java new file mode 100644 index 00000000..23ddd03b --- /dev/null +++ b/Problem1.java @@ -0,0 +1,37 @@ +1// Time Complexity :O(n) +// Space Complexity :O(1) +// Did this code successfully run on Leetcode :Yes +// Any problem you faced while coding this :No + + +// Your code here along with comments explaining your approach +/* we can count the number of 0s,1s and 2s and just set them in the array which works but that would be pass through the array twice +I have proceeded with two point approach along with an additional pointer as marker for tracking the mid value. +*/ +class Solution { + public void sortColors(int[] nums) { + //two pointer + int l=0, mid =0;//left for tracking 0s and mid for tracking 1s + int r = nums.length-1;// right for tracking 2s + while(mid<=r){ + if(nums[mid]==2){ + swap(nums, mid, r);//move the 2s to right + r--;//reduce right by 1 since we know 2 is in the end + } + else if(nums[mid]==0){ + swap(nums, l, mid);//move 0 to the front + l++;//move left since we know 0 is in the front + mid++; + } + else{ + mid++;//since the number is 1 do nothing as 1 is in mid + } + } + } + + public void swap(int []nums, int x, int y){ + int temp = nums[x]; + nums[x]=nums[y]; + nums[y]=temp; + } +} \ No newline at end of file diff --git a/Problem2.java b/Problem2.java new file mode 100644 index 00000000..753af395 --- /dev/null +++ b/Problem2.java @@ -0,0 +1,50 @@ +// Time Complexity :O(n2) +// Space Complexity :O(1) +// Did this code successfully run on Leetcode :Yes +// Any problem you faced while coding this :No + + +// Your code here along with comments explaining your approach +/* +we can implement by selecting a pivot element and sum other two elements which would bring total sum to 0 +the other two elements can be identified wither by +1. two sum problem - this will need a additional hashset of triplets to avoid duplicate triplets +time - O(n2) +space - O(n) +2. binary search +time - O(n2logn) +3.we can use two pointers +time- O(n2) +space - O(1) +*/ +class Solution { + public List> threeSum(int[] nums) { + List> result= new ArrayList<>(); + Arrays.sort(nums);// sort because we want to implement two pointer + for(int i=0;i0) break;//we dont want to iterate if one element all the elements after this is >0 because sum is >0 + if(i>0 && nums[i]==nums[i-1]) continue;//remove external duplicate triplets + int l=i+1; + int r=nums.length-1; + //two pointer for remaining elements after the pivot + while(l li= Arrays.asList(nums[l],nums[r],nums[i]); + result.add(li); + l++; + r--; + //remove interval duplicate elements + while(l