Chaturmind
LearnDSASystem DesignBlogPremium
Sign inGet started
Chaturmind

Structured learning paths for engineers who want to go deep. Written by practitioners.

Learn

  • Java
  • DSA
  • System Design
  • Spring Boot
  • AI / ML

Company

  • Blog
  • Premium
  • Contact

Legal

  • Privacy Policy
  • Terms of Service

© 2026 Chaturmind. All rights reserved.

Built for engineers who want to go deep.

DSA›Two Pointers & Sliding Window›Remove Duplicates from Sorted Array
EasyTwo Pointers & Sliding Window

Remove Duplicates from Sorted Array

two-pointerssorted-arrayin-place

Problem

Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. Return the number of unique elements k; the first k elements of nums must hold the unique elements in order.

Examples

Example 1

Input: nums = [1,1,2]

Output: 2, nums = [1,2,_]

Explanation: First two elements become the unique values 1 and 2.

Example 2

Input: nums = [0,0,1,1,1,2,2,3,3,4]

Output: 5, nums = [0,1,2,3,4,_,_,_,_,_]

Explanation: 5 unique elements written to the front.

Constraints

  • •1 <= nums.length <= 3 * 10^4
  • •-100 <= nums[i] <= 100
  • •nums is sorted in non-decreasing order

Hints

Hint 1

This is a two-pointer problem where both pointers move through the same array, not toward each other.

Hint 2

One pointer (slow) marks where the next unique value should be written; another (fast) scans ahead looking for it.

Hint 3

Because the array is sorted, duplicates are always adjacent — you never need to look further than the last written value.

Solutions

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

Time: O(n) · Space: O(1)