Bird
Raised Fist0
DSA Javascriptprogramming

Remove Duplicates from Sorted Array Two Pointer in DSA Javascript

Choose your learning style10 modes available
Mental Model
Use two pointers to keep track of unique elements and overwrite duplicates in place.
Analogy: Imagine sorting your bookshelf and moving only unique books forward, skipping duplicates as you go.
[1, 1, 2, 2, 3, 4, 4]
 ↑   ↑
slow fast
Dry Run Walkthrough
Input: array: [1, 1, 2, 2, 3]
Goal: Remove duplicates in place so the start of the array contains unique elements only
Step 1: Initialize slow pointer at index 0, fast pointer at index 1
[1, 1, 2, 2, 3]
 slow=0 ↑ fast=1 ↑
Why: We start comparing from the second element to find duplicates
Step 2: Compare elements at slow and fast; both are 1, duplicate found, move fast forward
[1, 1, 2, 2, 3]
 slow=0 ↑ fast=2 ↑
Why: Skip duplicate by moving fast pointer
Step 3: Elements differ (1 vs 2), increment slow and copy fast element to slow
[1, 2, 2, 2, 3]
 slow=1 ↑ fast=2 ↑
Why: Place new unique element at slow position
Step 4: Move fast forward to index 3, compare with slow at index 1
[1, 2, 2, 2, 3]
 slow=1 ↑ fast=3 ↑
Why: Check next element for duplicates
Step 5: Elements are equal (2 vs 2), duplicate found, move fast forward
[1, 2, 2, 2, 3]
 slow=1 ↑ fast=4 ↑
Why: Skip duplicate by moving fast pointer
Step 6: Elements differ (2 vs 3), increment slow and copy fast element to slow
[1, 2, 3, 2, 3]
 slow=2 ↑ fast=4 ↑
Why: Place new unique element at slow position
Step 7: Fast pointer reaches end, stop
[1, 2, 3, 2, 3]
 slow=2 ↑ fast=4 ↑
Why: All unique elements are moved to front
Result:
[1, 2, 3, 2, 3]
Unique elements count: 3
Annotated Code
DSA Javascript
class Solution {
  removeDuplicates(nums) {
    if (nums.length === 0) return 0;
    let slow = 0;
    for (let fast = 1; fast < nums.length; fast++) {
      if (nums[fast] !== nums[slow]) {
        slow++;
        nums[slow] = nums[fast];
      }
    }
    return slow + 1;
  }
}

// Driver code
const nums = [1, 1, 2, 2, 3];
const solution = new Solution();
const length = solution.removeDuplicates(nums);
let output = '';
for (let i = 0; i < length; i++) {
  output += nums[i] + (i < length - 1 ? ' -> ' : ' -> null');
}
console.log(output);
console.log('Unique elements count:', length);
if (nums.length === 0) return 0;
Handle empty array edge case
for (let fast = 1; fast < nums.length; fast++) {
Traverse array with fast pointer starting from second element
if (nums[fast] !== nums[slow]) {
Check if current fast element is different from slow element
slow++;
Move slow pointer forward to next unique position
nums[slow] = nums[fast];
Overwrite duplicate by placing unique element at slow pointer
return slow + 1;
Return count of unique elements
OutputSuccess
1 -> 2 -> 3 -> null Unique elements count: 3
Complexity Analysis
Time: O(n) because we traverse the array once with two pointers
Space: O(1) because we modify the array in place without extra space
vs Alternative: Compared to creating a new array for unique elements which uses O(n) space, this approach is more space efficient
Edge Cases
empty array
returns 0 immediately, no processing needed
DSA Javascript
if (nums.length === 0) return 0;
array with all duplicates
returns 1, only one unique element remains at start
DSA Javascript
if (nums[fast] !== nums[slow]) {
array with no duplicates
returns original length, array remains unchanged
DSA Javascript
if (nums[fast] !== nums[slow]) {
When to Use This Pattern
When you see a sorted array and need to remove duplicates in place, use the two pointer pattern to overwrite duplicates efficiently.
Common Mistakes
Mistake: Not incrementing slow pointer before overwriting, causing duplicates to remain
Fix: Always increment slow pointer before assigning new unique element
Mistake: Starting fast pointer at index 0 instead of 1, causing incorrect comparisons
Fix: Start fast pointer at index 1 to compare with slow pointer at index 0
Summary
Removes duplicates from a sorted array in place using two pointers.
Use when you want to keep only unique elements without extra space.
The slow pointer marks the position to place the next unique element found by the fast pointer.

Practice

(1/5)
1. What is the main purpose of using the two-pointer technique in removing duplicates from a sorted array?
easy
A. To reverse the array while removing duplicates
B. To sort the array again after duplicates are removed
C. To count the total number of duplicates in the array
D. To efficiently overwrite duplicates and keep unique elements at the start

Solution

  1. Step 1: Understand the two-pointer technique

    One pointer tracks the position to place the next unique element, the other scans the array.
  2. Step 2: Purpose of the technique

    It overwrites duplicates by placing unique elements at the front, avoiding extra space.
  3. Final Answer:

    To efficiently overwrite duplicates and keep unique elements at the start -> Option D
  4. Quick Check:

    Two-pointer = overwrite duplicates [OK]
Hint: Two pointers: one scans, one writes unique values [OK]
Common Mistakes:
  • Thinking it sorts the array again
  • Confusing counting duplicates with removing them
  • Assuming it reverses the array
2. Which of the following is the correct syntax to initialize two pointers for removing duplicates from a sorted array nums in JavaScript?
easy
A. let i = 1, j = 0;
B. let i = 0, j = 1;
C. let i = 0, j = 0;
D. let i = 1, j = 1;

Solution

  1. Step 1: Identify pointer roles

    Pointer i tracks last unique element index, j scans from next element.
  2. Step 2: Correct initialization

    i starts at 0 (first element), j starts at 1 (second element) to compare.
  3. Final Answer:

    let i = 0, j = 1; -> Option B
  4. Quick Check:

    i=0, j=1 start positions [OK]
Hint: Start i at 0, j at 1 to compare neighbors [OK]
Common Mistakes:
  • Starting both pointers at 0
  • Swapping i and j initialization
  • Starting both pointers at 1
3. What will be the output array after removing duplicates using the two-pointer method on nums = [1, 1, 2, 2, 3]?
medium
A. [1, 2, 3]
B. [1, 1, 2, 3]
C. [1, 2, 2, 3]
D. [1, 3, 2]

Solution

  1. Step 1: Traverse and compare elements

    Start with i=0, j=1. Compare nums[j] with nums[i]. If different, increment i and copy nums[j].
  2. Step 2: Update array with unique elements

    After processing, unique elements at start are [1, 2, 3].
  3. Final Answer:

    [1, 2, 3] -> Option A
  4. Quick Check:

    Unique sorted elements = [1, 2, 3] [OK]
Hint: Unique elements stay at front in sorted order [OK]
Common Mistakes:
  • Leaving duplicates in the output
  • Mixing order of elements
  • Not updating the array in place
4. Consider this code snippet for removing duplicates from a sorted array nums. What is the bug?
let i = 0;
for (let j = 1; j < nums.length; j++) {
  if (nums[j] !== nums[i]) {
    i = j;
    nums[i] = nums[j];
  }
}
return i + 1;
medium
A. Pointer i should be incremented, not assigned j
B. The loop should start from j = 0
C. The comparison should be nums[j] === nums[i]
D. Return statement should be i instead of i + 1

Solution

  1. Step 1: Analyze pointer update

    i should move forward by incrementing to next unique position, not jump to j.
  2. Step 2: Correct pointer increment

    Use i++ to move i forward, then assign nums[i] = nums[j].
  3. Final Answer:

    Pointer i should be incremented, not assigned j -> Option A
  4. Quick Check:

    i++ to move pointer forward [OK]
Hint: Increment i to place unique elements, don't assign j to i [OK]
Common Mistakes:
  • Assigning i = j instead of i++
  • Starting loop at wrong index
  • Wrong comparison operator
5. Given a sorted array nums = [0,0,1,1,1,2,2,3,3,4], what will be the length of the array after removing duplicates using the two-pointer method, and what will the first part of the array look like?
hard
A. Length: 4, Array start: [0, 1, 2, 3]
B. Length: 6, Array start: [0, 1, 1, 2, 3, 4]
C. Length: 5, Array start: [0, 1, 2, 3, 4]
D. Length: 5, Array start: [0, 0, 1, 2, 3]

Solution

  1. Step 1: Apply two-pointer method on nums

    Traverse array, move unique elements forward: 0,1,2,3,4.
  2. Step 2: Count unique elements and array start

    There are 5 unique elements, so length is 5, and array start is [0,1,2,3,4].
  3. Final Answer:

    Length: 5, Array start: [0, 1, 2, 3, 4] -> Option C
  4. Quick Check:

    Unique count = 5, array front = [0,1,2,3,4] [OK]
Hint: Count unique elements, array front holds them [OK]
Common Mistakes:
  • Counting duplicates as unique
  • Not updating array in place
  • Miscounting length after removal
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard