Explorer
Data Structures & Algorithms

Remove duplicates in-place such that each unique element appears only once.

Problem Statement

Given an integer array sorted in non-decreasing order, remove the duplicates in-place. Return the number of unique elements.

Examples

Input: arr = [1, 1, 2]

Output: 2

Explanation: Array becomes [1, 2, _]. Unique elements count is 2.

Constraints

Standard constraints

Complexity

Time Complexity: O(N)

Space Complexity: O(1)

Hints

šŸ’” Hint 1: The array is already sorted. Duplicates will always be adjacent to each other. šŸ’” Hint 2: Use a two-pointer technique: one slow pointer k tracking the placement of unique elements, and a fast pointer i scanning. šŸ’” Hint 3: Whenever nums[i] !== nums[k - 1], write nums[k] = nums[i] and increment k.

Editorial & Approach

Problem Overview & Intuition

Because the input array is already sorted, all identical elements are placed consecutively. Using two pointers allows in-place overwriting of duplicates without allocating extra memory.

Step-by-Step Approach

  1. If nums.length === 0, return 0.
  2. Initialize a write pointer k = 1.
  3. Iterate i from 1 to nums.length - 1.
  4. If nums[i] !== nums[k - 1], place nums[k] = nums[i] and increment k++.
  5. Return k, which is the count of unique elements.

Optimal Implementation (JavaScript)

function removeDuplicates(nums) {
  if (nums.length === 0) return 0;
  let k = 1;
  for (let i = 1; i < nums.length; i++) {
    if (nums[i] !== nums[k - 1]) {
      nums[k] = nums[i];
      k++;
    }
  }
  return k;
}

Complexity Analysis

Time Complexity O(N) — single traversal of the input array.
Space Complexity O(1) — in-place modification with no extra data structures.

Edge Cases & Corner Traps Handled

  • Empty array: returns 0.
  • All elements unique: returns nums.length.
  • All elements identical: returns 1.

Remove Duplicates from Sorted Array

Easy
Given an integer array sorted in non-decreasing order, remove the duplicates in-place. Return the number of unique elements.
Example Scenarios
1Example 1
Input: arr = [1, 1, 2]
Output: 2
Explanation:

Array becomes [1, 2, _]. Unique elements count is 2.

Constraints
•Standard constraints
Editor
Loading Editor...
arr =
[1, 1, 2]
Output:Click "Run" above to execute and verify your code here.
2