Fundamentals 5 min read

How to Remove Duplicates from a Sorted Array In-Place Using Two Pointers

This article walks through an interview-style solution for removing duplicates from a non‑strictly increasing sorted array in place, explaining the fast‑slow pointer technique, providing Java code, and analyzing its O(n) time and O(1) space complexities.

Xuanwu Backend Tech Stack
Xuanwu Backend Tech Stack
Xuanwu Backend Tech Stack
How to Remove Duplicates from a Sorted Array In-Place Using Two Pointers

Remove Duplicates from a Sorted Array

Given a non‑strictly increasing sorted integer array nums, remove duplicate elements in place so that each element appears only once, preserve the relative order, and return the new length k of the array.

Approach

Use two pointers: a slow pointer slow that tracks the position of the last unique element, and a fast pointer fast that scans the array.

Initialize slow = 0 and start fast from index 1.

Whenever nums[fast] != nums[slow], increment slow and copy nums[fast] to nums[slow].

After the loop, the number of unique elements is slow + 1.

Java implementation:

public int removeDuplicates(int[] nums) {
    if (nums == null || nums.length == 0) {
        return 0;
    }
    int slow = 0;
    for (int fast = 1; fast < nums.length; fast++) {
        if (nums[slow] != nums[fast]) {
            slow++;
            nums[slow] = nums[fast];
        }
    }
    return slow + 1;
}

The algorithm runs in O(n) time and O(1) extra space.

Summary : The fast‑slow pointer technique efficiently removes duplicates from a sorted array in a single pass without additional storage.

algorithmArrayduplicate removaltwo pointers
Xuanwu Backend Tech Stack
Written by

Xuanwu Backend Tech Stack

Primarily covers fundamental Java concepts, mainstream frameworks, deep dives into underlying principles, and JVM internals.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.