Remove Duplicates from Sorted Array in Java: Explanation & Practice

Remove duplicates in-place and return new length

Problem summary

Given a sorted array, remove duplicates in-place such that each element appears only once. Return the new length. Modify array in-place with O(1) extra memory.

Starter code

public class Main {
    public static void main(String[] args) {
        int[] nums = {1, 1, 2, 2, 3, 4, 4};
        
        // Two pointer: slow (write position) and fast (read position)
        // Only write when we find a new unique element
        // Print: New length: 4
        // Print: Array: 1 2 3 4
    }
}

Expected output and test cases

  • [1,1,2,2,3,4,4] → length 4
    New length: 4
    Array: 1 2 3 4
  • [1,1,2] → length 2
    New length: 2
    Array: 1 2
  • [0,0,1,1,1,2,2,3,3,4] → length 5
    New length: 5
    Array: 0 1 2 3 4

Hints

  1. Use slow pointer to track position where next unique element should go
  2. Fast pointer scans through the array
  3. When fast finds a different element than slow, copy it to slow+1
  4. Return slow+1 as the new length

Related Data Structures & Algorithms exercises

Practice all Data Structures & Algorithms exercises · Run this idea in the Java compiler