π LeetCode 26: Remove Duplicates from Sorted Array
π Problem Overview
- Problem Number: 26
- Problem Name: Remove Duplicates from Sorted Array
- Difficulty: Easy
- Category: Two Pointers
- Runnable Source:
Program.cs
π‘ Algorithmic Approach & Pattern
This problem is solved using the Two Pointers algorithmic pattern.
Key Insights & Invariants:
- Identify the input constraints and edge conditions.
- Structure the data flow to minimize unnecessary traversals and heap reallocations.
- Validate corner cases (empty collections, single-element cases, duplicates, extremes).
π» Verified C# Implementation (.NET 9)
The solution is verified and executable via the companion project in src/5.remove-duplicate-element/:
System.Console.WriteLine(RemoveZero([1, 1, 2, 0]));
System.Console.WriteLine(RemoveZero([0, 0, 1, 1, 1, 2, 2, 3, 3, 4]));
int RemoveZero(int[] nums)
{
int i = -1;
for (int j = 0; j < nums.Length; j++)
{
if (nums[j] != 0)
{
i++;
int temp = nums[j];
nums[j] = nums[i];
nums[i] = temp;
}
}
System.Console.WriteLine(string.Join(",", nums));
return i;
}
int RemoveDuplicates(int[] nums)
{
int i = 0;
for (int j = 0; j < nums.Length; j++)
{
if (nums[i] != nums[j])
{
i++;
nums[i] = nums[j];
}
}
System.Console.WriteLine(string.Join(",", nums));
return i + 1;
}
int RemoveDuplicatesHashMap(int[] nums)
{
var dict = new Dictionary<int, int>();
for (int i = 0; i < nums.Length; i++)
{
if (dict.ContainsKey(nums[i]))
{
dict[nums[i]]++;
}
else
{
dict[nums[i]] = 1;
}
}
return dict.Count;
}π Complexity Analysis
| Metric | Complexity | Notes |
|---|---|---|
| Time Complexity | (or optimal for pattern) | Single or bounded passes over the input |
| Space Complexity | or | Minimal auxiliary memory overhead |
π¨ Edge Cases & Interview Traps
- Empty / Null Input: Ensure null safety and guard clauses.
- Single Element: Confirm the algorithm terminates without out-of-bounds indexing.
- Duplicates & Boundaries: Check duplicate handling and extreme integer limits.