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
24 changes: 24 additions & 0 deletions MergeSortedArray.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// Time Complexity : O(m + n)
// Space Complexity : O(1)
// Did this code successfully run on Leetcode : yes
// Three line explanation of solution in plain english
/*
Use 2 pointers to traverse from ends of both the arrays and compare the values at each iteration to know
the greater value and place it at the end of the first array using a 3rd pointer. This way, we can achieve
an array sorted in non-decreasing order.
*/

class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
int p1 = m - 1;
int p2 = n - 1;
for(int p = m + n - 1 ; p >= 0 ; p--) {
if(p2 < 0)
break;
if(p1 >= 0 && nums1[p1] > nums2[p2])
nums1[p] = nums1[p1--];
else
nums1[p] = nums2[p2--];
}
}
}
25 changes: 25 additions & 0 deletions RemoveDuplicatesFromSortedArray2.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// Time Complexity : O(n)
// Space Complexity : O(1)
// Did this code successfully run on Leetcode : yes
// Three line explanation of solution in plain english
/*
Take 2 pointers as slow and fast. As per problem, k is atmost twice. So, we initially start with slow and
fast at k index.Now, we need to check if even post k indices, fast pointer and slow before k index are still
the same.If yes, it means we are still watching duplicates post k times, so we just increment fast pointer.
If not, we came across non-duplicate value and we need to swap that value with slow pointer's value.
*/
class Solution {
public int removeDuplicates(int[] nums) {
int k = 2;
int slow = k , fast = k;

while(fast < nums.length) {
if(nums[slow - k] != nums[fast]) {
nums[slow] = nums[fast];
slow++;
}
fast++;
}
return slow;
}
}
28 changes: 28 additions & 0 deletions SearchA2DMatrix2.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// Time Complexity : O(m + n)
// Space Complexity : O(1)
// Did this code successfully run on Leetcode :yes
// Three line explanation of solution in plain english
/*
Have a pointer pointing to the (m-1,0) cell or (0,n-1) because it helps us in identifying if we are greater
or less than target and move the row or column accordingly since as per the problem, rows and columns
are sorted in ascending order. Need to make sure we are not crossing the boundaries for both row and
column.
*/

class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int m = matrix.length;
int n = matrix[0].length;

int r = m - 1, c = 0;
while(r >= 0 && c < n) {
if(matrix[r][c] == target)
return true;
else if(matrix[r][c] > target)
r--;
else
c++;
}
return false;
}
}