Remove Duplicates from Sorted Array Two Pointer in DSA Rust - Time & Space Complexity
We want to understand how fast the two-pointer method removes duplicates from a sorted array.
How does the time needed grow as the array gets bigger?
Analyze the time complexity of the following code snippet.
fn remove_duplicates(nums: &mut Vec<i32>) -> usize {
if nums.is_empty() {
return 0;
}
let mut i = 0;
for j in 1..nums.len() {
if nums[j] != nums[i] {
i += 1;
nums[i] = nums[j];
}
}
i + 1
}
This code moves through the array once, shifting unique values forward to remove duplicates.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: A single loop that goes through the array once.
- How many times: Exactly once for each element after the first.
As the array size grows, the loop runs once for each element, so the work grows steadily.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 9 |
| 100 | 99 |
| 1000 | 999 |
Pattern observation: The number of steps grows directly with the number of elements.
Time Complexity: O(n)
This means the time to remove duplicates grows in a straight line with the array size.
[X] Wrong: "Because there are duplicates, the loop will run more than once per element."
[OK] Correct: The loop always runs once per element regardless of duplicates; duplicates only affect how many times we move elements, not the loop count.
Understanding this linear time approach shows you can efficiently handle sorted data with simple pointers, a skill useful in many coding problems.
"What if the array was not sorted? How would the time complexity change?"
Practice
Remove Duplicates from Sorted Array problem?Solution
Step 1: Understand the two-pointer approach
One pointer tracks the position to place the next unique element, the other scans the array.Step 2: Purpose of pointers in-place
This method avoids extra space by overwriting duplicates directly in the original array.Final Answer:
To efficiently track unique elements and overwrite duplicates in-place -> Option BQuick Check:
Two pointers help remove duplicates in-place [OK]
- Thinking two pointers create a new array
- Assuming sorting is needed again
- Counting duplicates instead of removing
Solution
Step 1: Identify pointer roles
Pointer i tracks last unique index, starting at 0; j scans from 1.Step 2: Match initialization
Correct initialization islet mut i = 1; let mut j = 0;to start comparing from second element.Final Answer:
let mut i = 1; let mut j = 0; -> Option AQuick Check:
i=1, j=0 starts scanning correctly [OK]
- Swapping i and j initialization
- Not using mutable variables
- Starting both pointers at 0
let mut nums = vec![1, 1, 2, 3, 3];?Solution
Step 1: Apply two-pointer logic
Start with i=0, j=1; compare nums[j] with nums[i]. When different, increment i and copy nums[j].Step 2: Trace array changes
nums changes to [1, 2, 3, 3, 3], but only first 3 elements are unique; rest are leftover values.Final Answer:
[1, 2, 3, _, _] -> Option CQuick Check:
Unique elements at start, duplicates ignored [OK]
- Assuming duplicates are removed from array length
- Expecting zeros instead of leftover values
- Not understanding in-place overwrite
let mut i = 0;
for j in 1..nums.len() {
if nums[i] == nums[j] {
i += 1;
nums[i] = nums[j];
}
}Solution
Step 1: Analyze the if condition
The code increments i and copies nums[j] only when nums[i] == nums[j], which is wrong.Step 2: Correct condition logic
We want to copy nums[j] only when nums[j] != nums[i], meaning a new unique element found.Final Answer:
The condition should check for inequality, not equality -> Option DQuick Check:
Copy unique elements when different [OK]
- Incrementing i on duplicates
- Wrong comparison operator
- Loop starting index confusion
nums with possible duplicates, how would you modify the two-pointer approach to return the count of unique elements and also ensure the first part of the vector contains only these unique elements in Rust?Solution
Step 1: Initialize pointers and iterate
Set i=0 for last unique index, j=1 to scan; compare nums[j] with nums[i].Step 2: Copy unique elements and count
If nums[j] != nums[i], increment i and copy nums[j] to nums[i]. After loop, unique count is i+1.Final Answer:
Use two pointers i=0, j=1; increment i and copy nums[j] when nums[j] != nums[i]; return i+1 as count -> Option AQuick Check:
Two-pointer overwrite returns unique count [OK]
- Using extra space like HashSet unnecessarily
- Re-sorting after removal
- Incorrect count calculation
Ready to prove it?
Pass the test and this pattern moves unknown
