← Back to Algorithms, page 1

algorithms-0015 · Easy fresher

Remove duplicates from a sorted list in place and return the number of unique values.

Because the list is sorted, duplicates are next to each other. Use a read pointer that scans every value and a write pointer that marks where the next unique value goes; copy a value only when it differs from the last value written. The first k positions then hold the unique values. O(n) time, O(1) extra space.

Full answer

Problem

Given a sorted list nums, remove duplicates in place so each value appears once, keep the relative order, and return k, the number of unique values. Only nums[:k] matters afterwards.

Example: [0, 0, 1, 1, 1, 2, 2, 3, 3, 4] returns 5 with nums[:5] == [0, 1, 2, 3, 4].

Constraints: 0 <= len(nums) <= 3 x 10^4, sorted in non-decreasing order, O(1) extra memory.

Brute force

sorted(set(nums)) gives the answer in a new list with O(n) extra space, which breaks the in-place rule. Deleting duplicates with del nums[i] inside a loop is O(n^2) because each deletion shifts the tail.

Optimal approach

  1. If the list is empty, return 0.
  2. write = 1 (the first value is always unique).
  3. For read from 1 to n - 1: if nums[read] != nums[write - 1], set nums[write] = nums[read] and increment write.
  4. Return write.

Why it works

Invariant: nums[:write] holds the unique values seen so far, in order. Since the list is sorted, a new value differs from the last unique one exactly when it is new. Copying never overwrites something unread, because write <= read at all times.

Complexity

O(n) time, O(1) extra space.

Code

python
def remove_duplicates(nums):
    """Remove duplicates from a sorted list in place; return the new length k.

    nums[:k] holds the unique values in their original order.
    """
    if not nums:
        return 0
    write = 1                          # next position for a new unique value
    for read in range(1, len(nums)):
        if nums[read] != nums[write - 1]:
            nums[write] = nums[read]
            write += 1
    return write


if __name__ == "__main__":
    a = [1, 1, 2]
    k = remove_duplicates(a)
    assert k == 2 and a[:k] == [1, 2]
    a = [0, 0, 1, 1, 1, 2, 2, 3, 3, 4]
    k = remove_duplicates(a)
    assert k == 5 and a[:k] == [0, 1, 2, 3, 4]
    assert remove_duplicates([]) == 0
    a = [7]
    assert remove_duplicates(a) == 1 and a == [7]
    a = [-3, -3, -3]
    assert remove_duplicates(a) == 1 and a[0] == -3
    print("all tests passed")

Save as a15_remove_duplicates.py and run python3 a15_remove_duplicates.py. It prints all tests passed (Python 3.13.5).

Edge cases

Empty list returns 0. One element returns 1. All values equal returns 1. Negative values. The input must be sorted; on unsorted input this method keeps only adjacent duplicates out.

Pattern

Read and write pointers moving in the same direction (fast and slow pointers on an array). Variants: allow at most two copies of each value (compare with nums[write - 2]), move zeroes to the end, remove a given value.

python
def remove_duplicates(nums):
    """Remove duplicates from a sorted list in place; return the new length k.

    nums[:k] holds the unique values in their original order.
    """
    if not nums:
        return 0
    write = 1                          # next position for a new unique value
    for read in range(1, len(nums)):
        if nums[read] != nums[write - 1]:
            nums[write] = nums[read]
            write += 1
    return write


if __name__ == "__main__":
    a = [1, 1, 2]
    k = remove_duplicates(a)
    assert k == 2 and a[:k] == [1, 2]
    a = [0, 0, 1, 1, 1, 2, 2, 3, 3, 4]
    k = remove_duplicates(a)
    assert k == 5 and a[:k] == [0, 1, 2, 3, 4]
    assert remove_duplicates([]) == 0
    a = [7]
    assert remove_duplicates(a) == 1 and a == [7]
    a = [-3, -3, -3]
    assert remove_duplicates(a) == 1 and a[0] == -3
    print("all tests passed")

Same-direction read and write pointers; the first k slots hold the answer.

Complexity

Time: O(n). Space: O(1) extra. Deleting elements with del inside a loop would make it O(n^2).

By level

Fresher: Writes the read and write pointer loop and explains it on the example list. Should explain why the list must be sorted for this method.

Mid: States the invariant, solves the at-most-k-copies variant and explains why deletion in a loop is slow. Can explain why the write pointer never passes the read pointer.

Senior: Discusses stability guarantees, generalisation to streams and deduplication of sorted data in external storage or database merges. Discusses in-place updates and their effect on other references to the list.

Key points

  • Sorted input puts duplicates next to each other
  • Read pointer scans, write pointer marks the next slot
  • Compare with the last written value
  • Invariant: nums[:write] is the unique prefix
  • O(n) time, O(1) extra space

Common mistakes

  • Using a set and breaking the in-place requirement
  • Deleting inside the loop and making it O(n^2)
  • Comparing with nums[read - 1] after overwriting values
  • Not handling the empty list

Follow-ups

  • How would you allow each value at most twice?
  • How would you move all zeroes to the end keeping order?
  • What if the list is not sorted?

Tips

  • State the invariant out loud
  • Handle the empty case first
  • Mention the at-most-twice variant

Evaluation rubric

  • Correct in-place algorithm
  • Correct return value and prefix contents
  • Handles edge cases
  • States the invariant