diff --git a/MergeSortedArrays.java b/MergeSortedArrays.java new file mode 100644 index 00000000..8d742df9 --- /dev/null +++ b/MergeSortedArrays.java @@ -0,0 +1,35 @@ +//Approach: Since both the arrays are sorted, if we keep pointers at the end and do the iterations for a better time complexity and space complexity +//Time Complexity : O(m) + O(m+n) +//Space Complexity: O(m) + +class MergeSortedArrays { + public void merge(int[] nums1, int m, int[] nums2, int n) { + + int ptrOne = m-1; + int ptrTwo = n-1; + int i = m+n-1; + + //Since the arrays are sorted if we keep pointers at the end of the arrays, it will be easier to compare and populate + while(ptrOne >= 0 && ptrTwo >= 0) + { + if(nums1[ptrOne] > nums2[ptrTwo]) + { + nums1[i] = nums1[ptrOne]; + ptrOne--; + } + else + { + nums1[i] = nums2[ptrTwo]; + ptrTwo--; + } + i--; + } + // In case if ptrOne reaches 0 and ends the earlier loop, we copy the rem + while(ptrTwo>= 0) + { + nums1[i] = nums2[ptrTwo]; + ptrTwo--; + i--; + } + } +} \ No newline at end of file diff --git a/RemoveDuplicate.java b/RemoveDuplicate.java new file mode 100644 index 00000000..3c1f0d3b --- /dev/null +++ b/RemoveDuplicate.java @@ -0,0 +1,34 @@ +//Approach: Use slow pointer to collect the elements within k (in this case 2), and the first pointer to iterate through the entire array +//Time Complexity : O(n) +//Space Complexity: O(1) +public class RemoveDuplicate +{ + public int removeDuplicates(int[] nums) { + + int s = 1; + int f = 1; + int count = 1; + + // s pointer to collect the elements that are not repeated more than twice + // while f pointer iterates through the entire array + while(f < nums.length) + { + if(nums[f] == nums[f-1]){ + count++; + } + else{ + count = 1; // new element is found + } + + //Until the count reaches the number of repeated elements allowed (in this case 2), we keep replacing + if(count <= 2){ + nums[s] = nums[f]; + s++; + } + + f++; + } + + return s; + } +} \ No newline at end of file diff --git a/SearchTwoDMatrix.java b/SearchTwoDMatrix.java new file mode 100644 index 00000000..d5682108 --- /dev/null +++ b/SearchTwoDMatrix.java @@ -0,0 +1,31 @@ +//Approach: Row elimination using binary search to find the element with O(m)+O(n) +//Time Complexity : O(m) + O(n) +//Space Complexity: O(1) + +public class SearchTwoDMatrix +{ + public boolean searchMatrix(int[][] matrix, int target) { + //Validate inputs + if (matrix == null || matrix.length == 0) { + return false; + } + + int m = matrix.length; + int n = matrix[0].length; + + int r = 0, c = n - 1; + + while (r < m && c >= 0) { + //Target found + if (matrix[r][c] == target) return true; + // Since the rows are sorted, we can safely assume that the target lies on to the left side + else if (matrix[r][c] > target) { + c--; + } else { + r++; + } + } + return false; + } +} +