SystemTutor
About
Sign in
Loading course documentation…
SystemTutor

COURSES

  • Data Structures & Algorithms
  • CSS MasterclassNew course
  • System DesignNew course

PRACTICE

  • Algorithm practice
  • CSS practice

LEGAL

  • Privacy Policy
  • Terms of Service
  • About

© 2026 SystemTutor. All rights reserved.

Built with 🫶 by Shatlyk

Course Overview
Algorithm Patterns OverviewFrequency CountersTwo SumValid AnagramGroup AnagramsFrequency Counters and Hash-Map LookupTwo PointersValid PalindromeTwo Sum IIContainer With Most WaterTwo-Pointer ReasoningSliding WindowMaximum Average Subarray ILongest Substring Without Repeating CharactersMinimum Size Subarray SumSliding-Window Reasoning
Algorithm Patterns

Two Pointers

Learn how the two pointers pattern searches sorted arrays, finds pairs that meet a condition, and replaces nested loops with linear-time scans.

The two pointers pattern uses two variables to track positions in a linear structure such as an array, string, or linked list. The pointers move according to a condition until they meet, cross, or reach the end.

In code, a pointer is usually just a number that stores an index:

A left pointer starts at index 0 and a right pointer starts at the last index of an eight-element array.

The pointers can move toward each other from opposite ends, move in the same direction, or move from the end toward the beginning. The important idea is that each pointer moves forward through the data instead of restarting a search for every item.

Core idea

Use two references to narrow the search space. When the input is sorted or has a useful left-to-right structure, pointer movement can replace nested loops and reduce a quadratic scan to linear time.

When this pattern fits

Two pointers are especially useful when:

  • The input is sorted, or the order gives you information about how to move.
  • You are looking for a pair of values that meets a condition.
  • You are comparing values from opposite ends of a structure.
  • You need to read a sequence while keeping track of a second position.

For a target-sum pair, sorted values justify eliminating an endpoint. A palindrome uses a different property: its first and last characters must match, regardless of alphabetic order.

Example: find a pair whose sum is zero

Write a function called sumZero that accepts a sorted array of integers. Return two values from distinct positions whose sum is zero. If no pair exists, return undefined in JavaScript or None in Python.

sumZero([-4, -3, -2, -1, 0, 1, 2, 5]) → [-2, 2]
sumZero([-4, -3, -2, 0, 1, 5]) → undefined

The array must be sorted from the smallest value to the largest value. That ordering lets us decide which pointer to move after each comparison.

The naive approach

The direct solution checks every possible pair with nested loops:

function sumZeroNaive(numbers) {
  for (let i = 0; i < numbers.length; i++) {
    for (let j = i + 1; j < numbers.length; j++) {
      if (numbers[i] + numbers[j] === 0) {
        return [numbers[i], numbers[j]];
      }
    }
  }

  return undefined;
}

For each value, the inner loop scans the remaining values. With n items and no matching pair, it checks n(n − 1)/2 pairs, giving O(n²) time.

The two-pointer approach

Place one pointer at the smallest value and one at the largest value:

left  = 0
right = numbers.length - 1

Then compare the values at those positions:

SumMeaningMove
0The pair matchesReturn both values
Greater than 0The sum is too largeMove right left to a smaller value
Less than 0The sum is too smallMove left right to a larger value

If the sum is too large, even the smallest remaining left value makes the right value too large. Every other remaining partner is at least as large, so discard that right endpoint. If the sum is too small, even the largest remaining right value falls short with the left value, so discard that left endpoint.

function sumZero(numbers) {
  let left = 0;
  let right = numbers.length - 1;

  while (left < right) {
    const sum = numbers[left] + numbers[right];

    if (sum === 0) {
      return [numbers[left], numbers[right]];
    }

    if (sum > 0) {
      right--;
    } else {
      left++;
    }
  }

  return undefined;
}

Trace the pointers

Start at the two ends of the sorted array. Before advancing, use the sum of the highlighted values to predict which pointer moves.

Enter up to 64 integers in brackets, smallest to largest. Equal values are allowed. Use [] for an empty array.

Step 1 of 4Target 0
  1. Index 0-4, highlighted↑L
  2. Index 1-3
  3. Index 2-2
  4. Index 3-1
  5. Index 40
  6. Index 51
  7. Index 62
  8. Index 75, highlighted↑R
Left value
-4
Right value
5
Sum
1

Step 1 of 4. Even with -4, the smallest remaining partner, 5 makes the sum too large. Move R one place left.

View all four comparisons
left valueright valueSumDecision
-451Too large, move right left
-42-2Too small, move left right
-32-1Too small, move left right
-220Return [-2, 2]

One endpoint moves on every unsuccessful comparison, reducing the distance between the pointers by one. A position can be compared several times while the opposite pointer moves, but there are at most n − 1 comparisons for a nonempty array. Its time complexity is O(n) and its extra space complexity is O(1).

Variations of two pointers

The pointers do not always start at opposite ends.

Comparing from opposite ends

To check whether a string is a palindrome, compare the first and last characters, then move inward:

function isPalindrome(text) {
  let left = 0;
  let right = text.length - 1;

  while (left < right) {
    if (text[left] !== text[right]) return false;
    left++;
    right--;
  }

  return true;
}

This scan also takes O(n) time and O(1) extra space when the input can be indexed directly.

Two pointers vs. nested loops

ApproachMain methodTypical timeExtra space
Nested loopsCompare each item with many other itemsO(n²)O(1)
Two pointersMove two positions based on a conditionO(n)O(1)

The linear solution depends on a property such as sorted order. Without that property, moving a pointer may discard a valid pair, so the optimization is not automatically safe.

Pattern checklist

Before using two pointers, ask: What does the order of the input tell me? Which pointer can move without skipping a valid answer? When should the pointers stop? Answering these questions makes the loop condition and pointer movement precise.


Key Takeaways

  • Linear Scan: Uses two index positions to scan data from opposite ends or at different speeds, replacing slow O(n²) nested loops with fast O(n) single passes.
  • Opposite Ends: Move pointers toward each other to find pairs (like two numbers that add up to zero) or check for palindromes.
  • Justify each move: A pair-sum search relies on sorted values. A palindrome check relies on matching mirrored positions.
  • Constant Space: Uses O(1) extra memory because it only tracks two index numbers without creating new arrays or maps.
  • When to Choose: Use Two Pointers when working with sorted arrays or strings. If the data is unsorted and you need to count items, use a Frequency Counter instead.

Apply the opposite-end scan to a sorted array in Two Sum II.

How is this lesson?

Previous lessonFrequency Counters and Hash-Map LookupNext lessonValid Palindrome
Edit on GitHubReport on GitHub
On this page
%

On this page

When this pattern fitsExample: find a pair whose sum is zeroThe naive approachThe two-pointer approachTrace the pointersVariations of two pointersComparing from opposite endsTwo pointers vs. nested loopsKey Takeaways