The Problem

Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Then return the number of unique elements.

Consider the number of unique elements to be k. You need to place the first k elements of nums equal to the unique values in order. It does not matter what you leave beyond the first k elements.

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

Interactive Visualization

Speed:
Array
Code
fun removeDuplicates(nums: IntArray): Int {    if (nums.size == 0) {        return 0 }    var slow = 0    for (fast in 1 until nums.size) {        if (nums[fast] != nums[slow]) {  // new unique            slow++            nums[slow] = nums[fast] }  // copy    }    return slow + 1 }  // count of unique
Current Step
Press Step or Play to begin.

How It Works

Key Insight

Because the array is already sorted, all duplicates are adjacent. We only need one pass with two pointers: a slow pointer tracking where to write the next unique value, and a fast pointer scanning ahead to find it. When nums[fast] != nums[slow], we have found a new unique element and copy it forward.

Algorithm Steps

  • Initialize: slow = 0 (the first element is always unique).
  • Scan: fast iterates from index 1 to the end.
  • Compare: If nums[fast] != nums[slow], we found a new unique value.
  • Write: Increment slow, then copy nums[fast] into nums[slow].
  • Skip: If nums[fast] == nums[slow], it is a duplicate — just advance fast.
  • Result: Return slow + 1 — the count of unique elements now in nums[0..slow].

Complexity

Time O(n)
Space O(1)

The fast pointer visits each element exactly once, and each write operation is O(1). No extra data structures are needed — everything happens in-place.