← Back to libraryQuestion 84 of 273
⌨️Java CodingIntermediate

Remove Duplicates from a Sorted Array

📌 Definition:

Given a sorted array, remove duplicates in place so each element appears once, returning the new length (e.g. [1,1,2,3,3] -> [1,2,3], length 3).

📖 Detailed Explanation:

Because the array is sorted, duplicates are adjacent. Use a slow pointer marking the last unique position and a fast pointer scanning ahead; when the fast element differs from the last unique, copy it forward. O(n) time, O(1) space.

💻 Solutions:
public static int removeDuplicates(int[] a) {
    if (a.length == 0) return 0;
    int slow = 0;
    for (int fast = 1; fast < a.length; fast++) {
        if (a[fast] != a[slow]) a[++slow] = a[fast];
    }
    return slow + 1;
}
function removeDuplicates(a) {
  if (a.length === 0) return 0;
  let slow = 0;
  for (let fast = 1; fast < a.length; fast++) {
    if (a[fast] !== a[slow]) a[++slow] = a[fast];
  }
  return slow + 1;
}
def remove_duplicates(a):
    if not a:
        return 0
    slow = 0
    for fast in range(1, len(a)):
        if a[fast] != a[slow]:
            slow += 1
            a[slow] = a[fast]
    return slow + 1
🔑 Key Points:
  • Sorted -> duplicates are adjacent
  • Two pointers: slow (write) and fast (read)
  • In place, O(1) extra space
  • Return the new logical length
🌍 Real-World Example:

In-place two-pointer compaction is a fundamental array technique reused for filtering and partitioning without extra allocation.

🎯 Scenario-Based Interview Question:

Why does the in-place approach rely on the array being sorted?