All articles
Coding

The Two-Pointer Technique: When It Works and How to Spot It

Master the two-pointer technique for coding interviews. Learn how to identify the pattern, maintain the invariant, and solve array and string problems.

Published by Ansh Modi · Vrenic
11 min read
On this page
  1. The logic behind two pointers
  2. Spotting the pattern in a problem statement
  3. Pattern one: Opposite ends converging
  4. Pattern two: Fast and slow pointers
  5. Pattern three: The sliding window
  6. Why this technique reduces time complexity
  7. Before your next coding round
{}CODING

Technical interviews frequently use arrays and strings to evaluate foundational algorithmic thinking. These linear data structures represent a massive portion of the questions you face during a standard technical screen. Efficiently traversing them without triggering performance bottlenecks is a core competency expected by technical assessors. The two-pointer technique offers a systematic way to solve these problems by tracking two indices at once, drastically reducing a solution's time complexity and satisfying strict memory limits.

When writing code in a time-constrained environment, relying on nested loops usually leads to algorithms that scale poorly. A solution that works perfectly on an array of ten elements will crash or time out when evaluated against an array of a million elements. Interview platforms run your code through hidden test cases specifically designed to catch these inefficient approaches. Mastering pointer manipulation ensures your logic scales gracefully to handle massive inputs.

The logic behind two pointers

A naive approach to finding pairs, triplets, or specific sequences in an array often involves checking every possible combination. This standard methodology uses nested loops, meaning you must scan the entire remaining array for each individual element you visit. If you are looking for a specific pair, the inner loop discards elements one by one, resetting its position every time the outer loop advances. This constant resetting and re-evaluating creates severe mathematical inefficiency.

The two-pointer technique solves this inefficiency by maintaining two distinct indices that move through the data structure according to a strict, logical rule. By managing two pointers simultaneously, you coordinate their movement to evaluate the data structure in a single, continuous pass. You might start them at opposite ends, or at the same end moving at different speeds. The crucial mechanism is that every movement provides new information, allowing the algorithm to make a definitive decision about the current elements.

The core of this technique relies entirely on the concept of an invariant. An invariant is a logical condition that remains consistently true throughout the entire execution of your loop. Because this rule holds firm, you can safely eliminate vast sections of the search space without evaluating them individually.

Understanding state spaces is critical for coding interviews. A state space represents every possible combination of variables your program could potentially evaluate. Brute-force algorithms explore the entire state space blindly, wasting computing cycles on configurations that logically cannot be the answer. Two pointers drastically prune this state space by establishing a rigid rule for when a pointer moves, declaring entire sections of the array mathematically irrelevant.

Instead of repeatedly looping over the same elements, your pointers make deliberate, calculated steps. Each movement discards impossible candidates and brings you closer to the correct answer. This shift from brute-force checking to logical deduction transforms a slow, exhaustive search into an elegant and optimal algorithm.

Spotting the pattern in a problem statement

Interviewers rarely tell you which algorithmic pattern to apply to a problem. You have to infer the correct approach from the specific phrasing and constraints of the problem statement. Keywords like "sorted array", "contiguous subarray", or instructions to modify the data "in-place" are strong, reliable signals for a two-pointer approach. Words like "longest", "shortest", or "target" frequently accompany these prompts.

A sorted input is the most common trigger for this technique. When an array is ordered, the position of an element gives you mathematical guarantees about the elements that follow or precede it. This known order dictates exactly how to move your pointers to maintain your invariant. Moving an index to the left guarantees a smaller or equal value, and moving an index to the right guarantees a larger or equal value.

The constraints printed at the bottom of a problem description offer vital clues. If a problem states the input array length can reach 100,000 elements, an O(N^2) solution will reliably exceed the time limit during execution. This massive scale tells you instantly that an O(N) or O(N log N) solution is mandatory, directing your focus away from nested loops and toward single-pass pointer manipulation.

You must also pay close attention to the memory constraints provided by the interviewer. Sometimes, a problem will explicitly ask for a solution with constant space complexity, written as O(1) space. Allocating a new array or creating a complex auxiliary structure scales memory linearly, which is O(N) space. While a hash map might solve a pair-finding problem with linear time complexity, it requires memory proportional to the input size.

Pattern one: Opposite ends converging

The converging pointers pattern places one index at the beginning of a sequence and the other at the end. The pointers step toward each other until they meet or cross. This is the standard, highly efficient approach for finding pairs that meet a specific condition in a sorted array.

A brute-force solution to finding a target sum takes the first element and adds it to every subsequent element. This requires a nested loop structure to exhaustively check every combination.

def two_sum_brute_force(numbers, target):
    for i in range(len(numbers)):
        for j in range(i + 1, len(numbers)):
            if numbers[i] + numbers[j] == target:
                return [i, j]
    return []

The outer loop selects an element, and the inner loop scans the remainder of the array. The inner loop restarts entirely for every single step of the outer loop, ignoring the fact that the array is already sorted. The converging two-pointer solution takes a smarter route by evaluating the sum of the smallest and largest available elements first, completely replacing the inner loop.

def two_sum_sorted(numbers, target):
    left = 0
    right = len(numbers) - 1

    while left < right:
        current_sum = numbers[left] + numbers[right]
        
        if current_sum == target:
            return [left, right]
        elif current_sum < target:
            left += 1
        else:
            right -= 1
            
    return []

The invariant here relies entirely on the array's sorted order. If the current_sum is too large, the right pointer must shift left to find a smaller value. If the sum is too small, the left pointer shifts right to increase the total value. Every single loop iteration moves at least one pointer, bringing them closer together.

Trace the algorithm using the sorted array [2, 7, 11, 15] and a target sum of 26. The left pointer starts at index 0 (value 2) and the right pointer starts at index 3 (value 15). The initial sum is 17. Because 17 is strictly less than 26, the left pointer increments to index 1 (value 7) to increase the sum.

The new sum is 22, which is still too small, prompting the left pointer to increment to index 2 (value 11). The sum of 11 and 15 is 26, hitting the target exactly, and the function returns the indices. Each step permanently eliminates an element that cannot possibly form the target sum with any remaining number, isolating the correct pair without redundant checks.

Pattern two: Fast and slow pointers

In this variation, both pointers begin at the first index and move in the exact same direction. They separate over time because they move at different speeds or advance under different logical conditions. This pattern excels at filtering data, removing duplicates, or modifying an array in place without requiring extra memory.

Consider the common problem of moving all zeroes to the end of an array while maintaining the relative order of the non-zero elements. A naive solution creates a completely new array, copies the non-zero elements over sequentially, and fills the remaining slots with zeroes. If the interviewer demands an in-place solution to conserve memory, you must deploy fast and slow pointers.

def move_zeroes(nums):
    slow = 0
    
    for fast in range(len(nums)):
        if nums[fast] != 0:
            nums[slow], nums[fast] = nums[fast], nums[slow]
            slow += 1
            
    return nums

The fast pointer acts as an explorer, examining every single element in the array one by one as the loop progresses. The slow pointer serves a completely different purpose. It acts as a strict placeholder for the exact position where the next valid, non-zero element should be inserted.

When the fast pointer encounters a non-zero value, you swap it with the value at the slow pointer and increment the slow pointer by one. The invariant ensures that all elements strictly before the slow pointer are non-zero and remain in their original relative order. All elements between the slow pointer and the fast pointer are guaranteed to be zeroes.

Imagine the input is [0, 1, 0, 3, 12]. At the start, both pointers sit at index 0. The fast pointer sees a 0 and advances, leaving the slow pointer behind.

At index 1, the fast pointer sees the non-zero value 1. It swaps the 1 with the 0 at the slow pointer's position, resulting in [1, 0, 0, 3, 12], and the slow pointer advances to index 1. This process repeats, shifting all non-zero values to the front while pushing the zeroes to the back in a single pass.

Pattern three: The sliding window

The sliding window is a highly specific application of the two-pointer technique used to evaluate contiguous subarrays or substrings. The indices form the left and right boundaries of a dynamic window that expands and contracts as it moves continuously through the data structure.

A classic interview problem asks for the length of the longest substring without repeating characters. A brute-force approach generates every possible substring, measures its length, and iterates through each character to check for duplicates. The sliding window achieves the exact same result in a single, continuous sweep over the string.

def length_of_longest_substring(s):
    seen = set()
    left = 0
    max_length = 0
    
    for right in range(len(s)):
        while s[right] in seen:
            seen.remove(s[left])
            left += 1
            
        seen.add(s[right])
        max_length = max(max_length, right - left + 1)
        
    return max_length

The right pointer continuously expands the window to include new characters, adding them to the tracking set. The invariant governing this process dictates that the current window bounded by the left and right pointers must never contain duplicate characters at the end of any iteration. The mathematical length of the current valid window is always calculated as right - left + 1.

When the right pointer encounters a character that is already present in the window, the invariant is instantly broken. The left pointer must then advance sequentially, removing characters from the tracking set one by one, until the problematic duplicate is gone. Only when the duplicate is removed is the invariant successfully restored, allowing the right pointer to resume its forward expansion.

Consider tracing the string "abcabcbb". The right pointer adds 'a', 'b', and 'c' safely, making the maximum length 3. At index 3, the right pointer hits a second 'a'.

The while loop triggers, forcing the left pointer to remove the first 'a' from the set and advance to index 1. The window is now valid again, containing 'b', 'c', and the new 'a'. This dynamic adjustment guarantees that you find the longest valid sequence without ever looking backward.

Why this technique reduces time complexity

Analysing the time complexity is a mandatory part of any coding interview. To prove your solution is optimal, you must confidently contrast the mathematical performance of the two-pointer approach against a brute-force alternative. An inefficient solution often works on small local examples but fails spectacularly on the massive inputs used during automated testing.

For an input size N, a nested loop structure compares every element to every other element. This executes roughly N × (N - 1) / 2 operations, which simplifies algorithmically to an O(N^2) time complexity. Assume the input array contains 10,000 elements; this exhaustive approach requires almost 50,000,000 separate operations. The two-pointer technique flattens this parabolic growth curve into an O(N) linear time complexity, requiring exactly 10,000 operations for the exact same input size.

Candidates sometimes worry that the while loop nested inside the for loop in the sliding window example creates an O(N^2) time complexity. This is an incorrect assumption. Across the entire execution of the program, the right pointer visits each element exactly once, and the left pointer visits each element at most once. Because the maximum number of total visits per element is strictly capped at two, the total number of operations scales linearly.

The space complexity benefit is equally significant and often strictly required by interviewers. Aside from the sliding window pattern, which may require a set to track characters, standard converging or fast-and-slow pointers operate with a highly efficient O(1) space complexity. Managing two integer variables requires a tiny, constant amount of memory, satisfying the strictest constraints and demonstrating your ability to write highly optimised code.

Before your next coding round

  • Check the input structure. Ask the interviewer if the array is sorted before you start writing any code on the board. The presence of a sorted structure often decides immediately whether converging pointers will yield a correct answer.
  • Define the invariant explicitly. You should be able to state the specific rule governing your pointers aloud before placing them in your code. If you cannot explain the logical condition that makes it safe to move a pointer, your algorithm is fundamentally incomplete.
  • Trace the pointer movements manually. Run through a small input example line by line to catch edge cases where pointers might cross prematurely or skip an element entirely. Manual tracing proves your code works before you execute it, which interviewers grade highly.
  • Verify your loop termination condition. Ensure your while left < right or while left <= right condition is strictly correct for the problem context to prevent out-of-bounds errors or infinite loops.
  • Test your implementation under pressure. You can practise applying these patterns efficiently using Vrenic's Proctored coding assessments on the Premium plan. The environment provides an AI-generated problem where your code runs against test cases in your browser and is graded on correctness, complexity, code quality and approach.
Published by
Ansh Modi · Vrenic

Founder of Vrenic, the interview coach that grades every answer against a real rubric.

More from Vrenic