Tech Interview RoomStudy guides

Two Pointers

Remove duplicates from a sorted array in place (and move zeroes). Compare new collections, streams and read/write pointers.

Beginner · 2 min read · Lesson 2 of 5 in Two Pointers

Problem

Given a sorted array, keep each value once in place and return the new length k (the first k elements hold the result). [0, 0, 1, 1, 1, 2, 2, 3] → k = 4, [0, 1, 2, 3, ...].

Pattern

Read/write (slow/fast) pointers: a fast pointer reads every element; a slow pointer marks where the next kept element is written. Any "filter in place" problem fits this.

Approach 1: Copy into a LinkedHashSet (feasible, O(n) time, O(n) space, not in place)

java
import java.util.LinkedHashSet;
import java.util.Set;

class DedupSet {
    static int dedup(int[] nums) {
        Set<Integer> set = new LinkedHashSet<>();
        for (int x : nums) set.add(x);
        int i = 0;
        for (int x : set) nums[i++] = x;
        return set.size();
    }
}

Approach 2: Java 8 streams distinct (concise, allocates a new array)

java
import java.util.Arrays;

class DedupStreams {
    static int[] dedup(int[] nums) {
        return Arrays.stream(nums).distinct().toArray();
    }
}

Approach 3: Read/write pointers in place (O(n) time, O(1) space) — optimal

Because the array is sorted, a value is new exactly when it differs from the last written value.

java
class DedupTwoPointers {
    static int dedup(int[] nums) {
        if (nums.length == 0) return 0;
        int write = 1;
        for (int read = 1; read < nums.length; read++) {
            if (nums[read] != nums[write - 1]) nums[write++] = nums[read];
        }
        return write;
    }

    // Same pattern: move all zeroes to the end, keeping the order of non-zero elements
    static void moveZeroes(int[] nums) {
        int write = 0;
        for (int read = 0; read < nums.length; read++) {
            if (nums[read] != 0) {
                int tmp = nums[write]; nums[write] = nums[read]; nums[read] = tmp;   // swap keeps it one pass
                write++;
            }
        }
    }
}

class DedupDemo {
    public static void main(String[] args) {
        int[] a = {0, 0, 1, 1, 1, 2, 2, 3}, b = a.clone(), z = {0, 1, 0, 3, 12};
        int k1 = DedupSet.dedup(a), k2 = DedupTwoPointers.dedup(b);
        System.out.println(k1 + " " + java.util.Arrays.toString(java.util.Arrays.copyOf(a, k1)) + " | "
            + k2 + " " + java.util.Arrays.toString(java.util.Arrays.copyOf(b, k2)));     // 4 [0, 1, 2, 3] | 4 [0, 1, 2, 3]
        System.out.println(java.util.Arrays.toString(DedupStreams.dedup(new int[] {0, 0, 1, 1, 1, 2, 2, 3})));
        DedupTwoPointers.moveZeroes(z);
        System.out.println(java.util.Arrays.toString(z));                                // [1, 3, 12, 0, 0]
    }
}

Feasible → optimal

A LinkedHashSet or distinct() is O(n) but uses O(n) extra memory and is not truly in place; read/write pointers are O(n) time, O(1) space, one pass.

Follow-up questions interviewers ask

Try answering each one before you open it.

Related (same pattern): remove duplicates allowing at most two copies.

Compare with the element two positions back: keep nums[read] if write < 2 || nums[read] != nums[write - 2]. The same template generalises to "at most k copies".

Related (same pattern): merge two sorted arrays in place (nums1 has room at the end).

Fill from the back with three pointers: i at the last real element of nums1, j at the end of nums2, write at the end of nums1; place the larger of nums1[i] and nums2[j] at write--. Going backwards never overwrites unread data. O(m + n) time, O(1) space, versus copying and sorting in O((m + n) log(m + n)).

Related (same pattern): sort colours (Dutch national flag: 0s, 1s and 2s).

Three pointers: low (next 0 position), mid (current), high (next 2 position from the end). If nums[mid] == 0 swap with low and advance both; if 1 advance mid; if 2 swap with high and decrement high (do not advance mid). One pass, O(n), O(1), versus Arrays.sort O(n log n) or counting sort (two passes).