Two pointers coding pattern for interviews
Photo by Unsplash

Two Pointers Pattern for Coding Interviews 2026

Two pointers coding pattern for interviews

The two pointers technique is one of the most versatile and frequently tested patterns in coding interviews for 2026. Whether you are preparing for FAANG rounds or startup technical screens, mastering two pointers will help you solve dozens of array and string problems in O(n) time. In this guide, we cover the two pointers pattern, its variations, Java templates, worked examples, and a practice plan to sharpen your skills.

What Is the Two Pointers Pattern?

The two pointers pattern uses two index variables that traverse a data structure—usually a sorted array or a linked list—simultaneously. Instead of brute-forcing every pair with nested loops in O(n²), you move the pointers strategically to converge on the answer in O(n). Interviewers love this pattern because it tests whether you can optimize naïve solutions and reason about pointer invariants under pressure.

When to Use Two Pointers

Reach for two pointers whenever you see these signals in a problem statement: the input is sorted (or can be sorted), you need to find a pair or triplet that meets a condition, the task involves removing or partitioning elements in place, or the problem asks about palindromes or symmetric structures. Classic examples include Two Sum II, 3Sum, Container With Most Water, Remove Duplicates, and Valid Palindrome.

Software engineer preparing for coding interview

Two Pointers Variations

1. Opposite-Direction Pointers

One pointer starts at the beginning and the other at the end. They move toward each other until they meet. This works for problems on sorted arrays where you want to find pairs that sum to a target, or for container/area problems where width decreases as pointers converge.

2. Same-Direction (Fast and Slow) Pointers

Both pointers start at the beginning. A slow pointer tracks a position (like the boundary of a valid sub-array), while a fast pointer scans ahead. This is ideal for in-place removal, deduplication, and partitioning.

3. Linked List Pointers

A slow pointer moves one step and a fast pointer moves two steps. This classic technique detects cycles, finds the middle node, and identifies the start of a cycle in O(n) time with O(1) space.

Java Template: Opposite-Direction Pointers

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};
        } else if (sum < target) {
            left++;
        } else {
            right--;
        }
    }
    return new int[]{-1, -1};
}

How it works: Because the array is sorted, if the current sum is too small we advance the left pointer to increase it; if too large we retreat the right pointer. Each element is visited at most once, giving O(n) time.

Java Template: Same-Direction (Fast/Slow)

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;
}

How it works: The slow pointer marks the last unique element. The fast pointer scans forward; whenever it finds a new value, it copies it to slow + 1. The result is an in-place deduplication in O(n) time and O(1) space.

Algorithm problem solving on laptop

Common Two Pointers Problems and Patterns

Pair Sum / Target Sum

Given a sorted array, find two numbers that add up to a target. Use opposite-direction pointers. This extends to 3Sum by fixing one element and running two pointers on the remainder, and to 4Sum by adding another loop.

Container With Most Water

Place pointers at both ends. Calculate area, then move the pointer at the shorter line inward. The greedy insight is that moving the shorter side is the only way to potentially find a taller line and a larger area.

Palindrome Checking

Set left at index 0 and right at the last index. Compare characters, skipping non-alphanumeric ones, and move both pointers inward. If they ever disagree, the string is not a palindrome.

Linked List Cycle Detection

Floyd's algorithm: move slow by one node and fast by two. If they meet, a cycle exists. To find the cycle start, reset one pointer to the head and advance both by one step until they meet again.

Trapping Rain Water

Maintain left and right pointers with running max heights from each side. At each step, process the pointer with the smaller max height, accumulate water as maxHeight minus current height, and advance that pointer. This solves the problem in O(n) time and O(1) space.

Complexity Analysis

Time complexity: Most two pointers solutions run in O(n), since each pointer traverses the array at most once. For k-sum variants (3Sum, 4Sum), the outer loops add factors, giving O(n²) for 3Sum and O(n³) for 4Sum—still far better than brute force.

Space complexity: Two pointers itself uses O(1) extra space. Sorting, if required, takes O(log n) stack space for in-place sorts. This constant-space property makes two pointers a favorite in interviews where memory efficiency matters.

Worked Example: 3Sum

Given nums = [-1, 0, 1, 2, -1, -4], find all unique triplets that sum to zero.

Step 1: Sort the array → [-4, -1, -1, 0, 1, 2].

Step 2: Fix i = 0 (value -4). Set left = 1, right = 5. Sum = -4 + (-1) + 2 = -3 < 0, so advance left. Continue until no valid pair exists.

Step 3: Fix i = 1 (value -1). Set left = 2, right = 5. Sum = -1 + (-1) + 2 = 0 → record [-1, -1, 2]. Move both pointers. Next, sum = -1 + 0 + 1 = 0 → record [-1, 0, 1].

Step 4: Skip duplicate values of i. Fix i = 3 (value 0). No valid pair. Done.

Result: [[-1, -1, 2], [-1, 0, 1]].

Developer workspace for interview preparation

7-Day Practice Plan

Day 1–2: Solve Two Sum II, Valid Palindrome, and Remove Duplicates from Sorted Array to build your foundation with both opposite-direction and same-direction pointers.

Day 3–4: Tackle 3Sum and Container With Most Water. Focus on handling duplicates and reasoning about the greedy invariant.

Day 5–6: Move to Trapping Rain Water and Linked List Cycle II. These test your ability to maintain auxiliary state alongside the pointers.

Day 7: Timed mock: pick two unseen medium problems from LeetCode tagged "Two Pointers" and solve each in under 25 minutes. Review your solutions for edge cases.

Key Takeaways

The two pointers pattern transforms O(n²) brute-force searches into elegant O(n) solutions. Recognize the signals—sorted input, pair/triplet conditions, in-place operations, and palindrome structure—and the technique almost writes itself. Drill the templates until they are second nature, and you will handle a large chunk of array and string interview questions with confidence.

Looking for structured, AI-powered interview coaching that adapts to your skill level? Niraswa AI builds personalized prep plans, tracks your weak spots, and gives you targeted practice so every hour of study counts. Start your free prep session today.

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 *