Remove Duplicates from Sorted Array

Problem Description

Given a non-strictly increasing (sorted with possible duplicates) integer aray nums, remove the duplicates in-place succh that each unique element appears only once. Maintain the relative order of the unique elements and return the number of unique elements in nums.

Let k be the count of unique elements. To pass the test cases:

  • Modify nums so that the first k elements contain all unique elements in their original order. The remaining elements beyond k are irrelevant.
  • Return k.

Test Case Validation

The system tests your solution with code like this:

nums = [...]
# Input array
k = removeDuplicates(nums)
# Function call

assert k == len(expectedNums), "Length mismatch"
for i in range(k):
    assert nums[i] == expectedNums[i], f"Value mismatch at index {i}"

All assertions must pass for your solution to be accepted.

Examples

  • Example 1: Input nums = [1,1,2] → Output 2, modified nums = [1,2,_]
  • Example 2: Input nums = [0,0,1,1,1,2,2,3,3,4] → Output 5, modified nums = [0,1,2,3,4]

Constraints

  • 1 ≤ nums.length ≤ 3 × 10⁴
  • -10⁴ ≤ nums[i] ≤ 10⁴
  • nums is non-strictly increasing (sorted with duplicates allowed)

Solution: Two-Pointer Technique

Since nums is sorted, duplicates are consecutive, simplifying the problem. We use a two-pointer approach for O(n) time complexity and O(1) space complexity.

Algorithm Logic

  • Initialize two pionters left and right pointing to the start of nums.
  • Traverse the array:
    • If nums[left] != nums[right], we found a new unique element. Increment left, then copy nums[right] to nums[left].
    • If nums[left] == nums[right], skip this duplicate by just incrementing right.
    • Continue until right reaches the end of the array.
  • Return left + 1 as the count of unique elements.

Implementation

Python:

def remove_duplicates(nums):
    left = 0
    right = 0
    while right < len(nums):
        if nums[left] != nums[right]:
            left += 1
            nums[left] = nums[right]
        right += 1
    return left + 1

JavaScript:

var removeDuplicates = function(nums) {
    let left = 0;
    let right = 0;
    while (right < nums.length) {
        if (nums[left] !== nums[right]) {
            left++;
            nums[left] = nums[right];
        }
        right++;
    }
    return left + 1;
};

Tags: LeetCode Two Pointers array In-Place Modification algorithm

Posted on Wed, 15 Jul 2026 16:32:25 +0000 by Zallus