Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions MergeSortedArrays.java
Original file line number Diff line number Diff line change
@@ -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--;
}
}
}
34 changes: 34 additions & 0 deletions RemoveDuplicate.java
Original file line number Diff line number Diff line change
@@ -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;
}
}
31 changes: 31 additions & 0 deletions SearchTwoDMatrix.java
Original file line number Diff line number Diff line change
@@ -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;
}
}