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
33 changes: 33 additions & 0 deletions MergeSortedArray.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
//Time Complexity: O(m + n)
//Space Complexity: O(1)

//Approach

//Use three pointers (p1, p2, i) starting from the end of nums1, nums2 and the merged array.
//While p2 >= 0, place the larger of nums1[p1] and nums2[p2] at nums1[i] (guarding p1 >= 0).
//Decrement pointers accordingly; remaining nums1 elements are already in correct position.
public class Solution
{
public void Merge(int[] nums1, int m, int[] nums2, int n)
{
int p1 = m - 1;
int p2 = n - 1;
int i = m + n - 1;
while (p2 >= 0) //Because nums2 must be fully merged
{
if (p1 >= 0 && nums1[p1] > nums2[p2]) //Because p1 might be exhausted, but p2 not be ignored
{
nums1[i--] = nums1[p1--];
}
else
{
nums1[i--] = nums2[p2--];
}
}
}
}





45 changes: 45 additions & 0 deletions RemoveDuplicatesFromSortedArray.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
// Time Complexity:
// O(n)

// Space Complexity:
// O(1)

//Approach
// Keep slow pointer at index 0 , for loop Starts with index 1 ,
// if the previous and the current elements are same increment count.
// if the the elements are unequal reset the count to 1.
// if count is less than 0 equal to 2 or k , update slow pointer with current vals.
// Increment slow pointer.
public class Solution
{
public int RemoveDuplicates(int[] nums)
{
int slow = 1;
int count = 1;
for (int i = 1; i < nums.Length; i++)
{
if (nums[i] == nums[i - 1])
{
count++;
}
else
{
count = 1;
}
if (count <= 2)
{
nums[slow] = nums[i];
slow++;
}

}
return slow;
}
}







34 changes: 34 additions & 0 deletions SearchIn2DMatrix2.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
public class Solution {

// Time Complexity:
// O(m + n)

// Space Complexity:
// O(1)

// Start from the top-right corner of the matrix.
// If the number is bigger, move left; if smaller, move down.
// Keep checking until you find the target or exit the matrix bounds.
public bool SearchMatrix(int[][] matrix, int target)
{
int m = matrix.Length;
int n = matrix[0].Length;
int r = 0; int c = n - 1;
while (r < m && c >= 0)
{
if (matrix[r][c] == target)
{
return true;
}
else if (target < matrix[r][c])
{
c--;
}
else
{
r++;
}
}
return false;
}
}