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
29 changes: 29 additions & 0 deletions Merge_sorted_array.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@

// 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 two pointers starting from the ends of both arrays and fill the first array from the back.
//Compare elements: place the larger one at the end and move that pointer backward.
//Repeat until all elements from both arrays are merged.
class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
int p1=m-1, p2=n-1;
int idx=m+n-1;
while(p1>=0 && p2>=0){
if(nums2[p2]>nums1[p1]){
nums1[idx]= nums2[p2];
p2--;
}else{
nums1[idx]= nums1[p1];
p1--;
}
idx--;
}
while(p2 >= 0){
nums1[idx] = nums2[p2];
p2--;
idx--;
}
}
}
28 changes: 28 additions & 0 deletions Remove_dublicates.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// Time Complexity : O(n)
// Space Complexity : O(1)
// Did this code successfully run on Leetcode : yes
// Three line explanation of solution in plain english-
/*
1. Use two pointers, slow and fast, to traverse the array.
2. Keep track of the count of consecutive duplicate elements.
3. Only keep elements that appear at most twice.
*/
class Solution {
public int removeDuplicates(int[] nums) {
// if(nums.length==null) return -1;
int slow = 1;
// int fast = 1;
int c = 1;

for(int fast=1; fast<nums.length;fast++){
if(nums[fast]==nums[fast-1]){
c++;
}else c=1;
if(c<=2){
nums[slow]=nums[fast];
slow++;
}
}
return slow;
}
}
29 changes: 29 additions & 0 deletions search_2d_matrix_2.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@

// 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-
/*
1. Start from the top-right corner of the matrix.
2. If the current element is equal to the target, return true.
3. If the current element is greater than the target, move left; if it's smaller, move down. Repeat until you find the target or go out of bounds.
*/
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int m = matrix.length;
int n = matrix[0].length;
int row = 0;
int col = n - 1; // Start at top-right

while (row < m && col >= 0) {
if (matrix[row][col] == target) {
return true;
} else if (matrix[row][col] > target) {
col--; // Target is smaller, move left
} else {
row++; // Target is bigger, move down
}
}
return false;
}
}