Code editor showing an algorithm, representing the two pointers pattern for coding interviews

Two Pointers Pattern for Coding Interviews 2026

The two pointers pattern is one of the highest-leverage techniques you can master for coding interviews. It converts brute-force O(n²) scans into elegant O(n) solutions, appears constantly in array, string, and linked list problems, and interviewers at every major tech company use it as a baseline test of algorithmic maturity. This walkthrough covers the three core variants, worked Java solutions, and the practice set that makes the pattern stick.

What Is the Two Pointers Pattern?

Instead of nesting loops to compare every pair of elements, you maintain two indices that traverse the data structure according to a rule. Because each pointer moves at most n steps, the total work stays linear. The pattern shines when the input is sorted, when you need to work in place, or when the answer involves a pair or window of positions.

Recognize it by these problem signals: “find a pair that sums to X in a sorted array,” “remove duplicates in place,” “check if a string is a palindrome,” “detect a cycle in a linked list,” or “merge two sorted arrays.”

Variant 1: Converging Pointers (Opposite Ends)

Start one pointer at each end and move them toward each other based on a comparison. The classic example is Two Sum II on a sorted array:

public int[] twoSumSorted(int[] nums, int target) {
    int left = 0, right = nums.length - 1;
    while (left < right) {
        int sum = nums[left] + nums[right];
        if (sum == target) return new int[]{left, right};
        if (sum < target) left++;   // need a bigger sum
        else right--;                // need a smaller sum
    }
    return new int[]{-1, -1};
}

Why it works: sorting gives you a decision rule. If the sum is too small, only moving left rightward can increase it; if too large, only moving right leftward can decrease it. You never miss a valid pair, and you touch each element once — O(n) time, O(1) space.

The same skeleton solves Valid Palindrome, Container With Most Water, and 3Sum (fix one element, run converging pointers on the rest — O(n²) overall, but optimal).

Developer writing Java code on a laptop while practicing two pointers problems

Variant 2: Fast and Slow Pointers (Same Direction)

Both pointers move forward, but the fast one advances under looser rules. The workhorse example is Remove Duplicates from Sorted Array in place:

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

Here slow marks the boundary of the “clean” region while fast explores. This reader-writer structure also solves Move Zeroes, Remove Element, and string compression problems — anything phrased as “do it in place with O(1) extra space.”

Floyd’s Cycle Detection

On linked lists, fast and slow pointers become Floyd’s tortoise-and-hare algorithm. Advance one pointer by one node and the other by two; if the list has a cycle, they must meet:

public boolean hasCycle(ListNode head) {
    ListNode slow = head, fast = head;
    while (fast != null && fast.next != null) {
        slow = slow.next;
        fast = fast.next.next;
        if (slow == fast) return true;
    }
    return false;
}

Interviewers love follow-ups here: find the cycle’s start, find the middle of a list, or find the k-th node from the end — all fast/slow variations worth rehearsing.

Variant 3: Two Sequences

One pointer per input, advancing whichever is “behind.” This drives Merge Two Sorted Arrays, Intersection of Two Arrays, and subsequence checks:

public boolean isSubsequence(String s, String t) {
    int i = 0, j = 0;
    while (i < s.length() && j < t.length()) {
        if (s.charAt(i) == t.charAt(j)) i++;
        j++;
    }
    return i == s.length();
}

How to Choose the Right Variant

  • Sorted input + pair/target condition → converging pointers from both ends.
  • In-place rewrite or partition → slow writer, fast reader.
  • Linked list structure questions → fast/slow with different speeds.
  • Two inputs compared element by element → one pointer per sequence.

If the array is unsorted and sorting would break the required output (like returning original indices), pause: a hash map may beat two pointers. Saying this trade-off out loud in an interview earns real credit.

Notebook and coffee on a desk for planning coding interview practice

Practice Set: 10 Problems in Difficulty Order

  1. Valid Palindrome
  2. Two Sum II — Input Array Is Sorted
  3. Remove Duplicates from Sorted Array
  4. Move Zeroes
  5. Merge Sorted Array
  6. Linked List Cycle
  7. Middle of the Linked List
  8. Container With Most Water
  9. 3Sum
  10. Trapping Rain Water (hard — converging pointers with running maxima)

Time-box each to 25–35 minutes and narrate your reasoning as you code. After solving, ask: which variant was this, and what signal in the problem statement pointed to it? That reflection step is what turns solved problems into a reusable pattern.

Common Mistakes to Avoid

Moving both pointers in the same iteration without justification. Forgetting boundary checks (left < right versus left <= right changes correctness for even and odd lengths). Skipping duplicate handling in 3Sum. And reaching for two pointers on unsorted data where the decision rule no longer holds — always state why pointer movement is safe.

Start Practicing Today

Two pointers is learnable in a weekend and pays off for years of interviews. Work through the ten problems above, write out the three variant skeletons from memory, and rehearse explaining the “why” behind each pointer move. If you want structured, realistic practice, Niraswa AI can help — but the key is to start today and keep the streak alive.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *