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 Merge-sorted-array.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
int p1 = m-1;
int p2 = n-1;
int p3 = m+n-1;
while(p1>=0 && p2>=0){
if(nums1[p1] <= nums2[p2]){
nums1[p3] = nums2[p2];
p2--;
p3--;
}else {
nums1[p3] = nums1[p1];
p1--;
p3--;
}
}

while(p2>=0){
nums1[p3] = nums2[p2];
p2--;
p3--;
}
}
}
8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
# Two-Pointers-2

## Problem1 (https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/)
* Brutforce - Hasshmap freq map, keep 2 elements
* Optimal - no extra space used. keep 2 ptrs- i for iterating array, slow ptr for keeping the freq count <=2.


## Problem2 (https://leetcode.com/problems/merge-sorted-array/)
* Brutforce - Copy nums2 arr behind nums1 arr & then sort it - T(n) = O(m+n log(m+n))
* Optimal - 3 pointers p1 for nums1 at m-1, p2 for nums2 at n-1, p3 for num1 at m+n-1.
* comparing p1 & p2 whichever is greater keeping at p3. Look for condition where p2 will still be inbound that time copy elements from p2 to nums1 array at p3.


## Problem3 (https://leetcode.com/problems/search-a-2d-matrix-ii/)

* Top Right or Bottom Left elements have deciding factor - whether to go up/down or left/right.
* Search the target within limits.
18 changes: 18 additions & 0 deletions Remove-duplicates-from-sorted-array-ii.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
class Solution {
public int removeDuplicates(int[] nums) {
int count = 1;
int slow = 1;
for(int i=1;i<nums.length;i++){
if(nums[i]==nums[i-1]){
count++;
}else{
count=1;//reset
}
if(count<=2){
nums[slow] = nums[i];
slow++;
}
}
return slow;
}
}
19 changes: 19 additions & 0 deletions Search-a-2d-matrix-ii.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int m = matrix.length;
int n = matrix[0].length;
//top right element has deciding power
int r = 0, c=n-1;
while(r<m && c>=0){
if(matrix[r][c] == target) {
return true;
}else if(matrix[r][c] < target){
r++;
}else{
c--;
}
}

return false;
}
}