Remove Duplicates from Sorted Array

Dated May 28, 2026; last modified on Thu, 28 May 2026

Given a sorted integer array, remove some duplicates in-place such that each unique element appears at most twice. Maintain the relative order of the elements. If there are \(k\) elements after removing the duplicates, the first \(k\) elements of the array should hold the final result.

This a two-pointer problem, where we have a tortoise and a hare. Establishing an invariant that must be maintained throughout the array is useful to avoid tripping up on index arithmetic. In this case, let tortoise be the index whose final value needs to be determined in the current iteration. [..., tortoise-1] (inclusive) is the processed range that won’t change. #two-pointer-algorithm

public int RemoveDuplicates(int[] nums) {
  if (nums.Length == 0)
    return 0;

  int tortoise = 1, count = 1;
  for (int hare = 1; hare < nums.Length; hare++)
  {
    bool hareMatchesPrevious = nums[hare] == nums[hare-1];
    count = hareMatchesPrevious ? count + 1 : 1;

    if (hareMatchesPrevious && count <= 2)
    {
      nums[tortoise] = nums[hare];
      tortoise += 1;
    }
    else if (!hareMatchesPrevious)
    {
      nums[tortoise] = nums[hare];
      tortoise += 1;
      count = 1;
    }
  }
  return tortoise;
}
  1. Remove Duplicates from Sorted Array II - LeetCode. leetcode.com . Accessed May 28, 2026.