Back to Benchmark

Two Pointers Technique - O(n) Complexity

Understanding how the two pointers technique achieves linear time for array and string problems

What is the Two Pointers Technique?

The two pointers technique uses two pointers (indices) that traverse an array or string, typically from opposite ends or both from the start. This technique is efficient for problems involving pairs, palindromes, or sorted arrays.

Common Patterns:

  • Opposite Ends: One pointer at start, one at end, moving towards each other
  • Same Direction: Both pointers start at beginning, moving at different speeds (fast/slow)
  • Sliding Window: Two pointers define a window that slides through the array

Think of it like two people walking towards each other from opposite ends of a hallway - they meet in the middle, and you only need to check each position once!

How Does Two Pointers Work?

1. Initialize Two Pointers

Start with two pointers, typically at opposite ends (left = 0, right = n-1) or both at the start (left = 0, right = 0).

2. Process and Move

Process the elements at both pointer positions, then move the pointers based on some condition (e.g., move left forward if sum is too small, move right backward if sum is too large).

3. Linear Time Complexity

Each element is visited at most once by each pointer. Since pointers move towards each other or in one direction, total operations are O(n):

Array with 10 elements → at most 10 pointer moves
Array with 100 elements → at most 100 pointer moves
Array with n elements → at most n pointer moves
Time complexity: O(n)

💡 Why It's Efficient

Instead of nested loops (O(n²)) checking all pairs, two pointers eliminate half the search space at each step, reducing complexity to O(n). This is especially powerful for sorted arrays!

Interactive Two Pointers Visualization
Watch how two pointers traverse an array from opposite ends!
0
5
1
15
2
25
3
35
4
45
5
55
6
65
7
75
8
85
9
95

Code Example:

// Two pointers: find two numbers that sum to target - O(n)
function twoSum(arr, target) {
  let left = 0;
  let right = arr.length - 1;

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

    if (sum === target) {
      return [left, right]; // Found!
    } else if (sum < target) {
      left++; // Need larger sum
    } else {
      right--; // Need smaller sum
    }
  }

  return null; // Not found
}
Built-in Functions and Patterns
While two pointers is typically implemented manually, here are common patterns and helper functions:

JavaScript/TypeScript

Manual implementation - O(n) - Most common
// Use while loop with left and right pointers
Array methods with indices - O(n)
// Can use for loop with two indices

Python

Manual implementation - O(n) - Standard approach
// while left < right: pattern
zip() with reversed - O(n) - Alternative pattern
// for a, b in zip(arr, reversed(arr))

Java

Manual implementation - O(n) - Classic approach
// int left = 0, right = arr.length - 1;
ListIterator - O(n) - For linked lists
// Can use iterators from both ends

C++

Manual implementation - O(n) - Standard approach
// int left = 0, right = arr.size() - 1;
std::reverse_iterator - O(n) - For reverse traversal
// Can combine forward and reverse iterators
Common Two Pointers Problems

1. Two Sum (Sorted Array)

Find two numbers that add up to a target in a sorted array.

// O(n) with two pointers
// vs O(n²) with nested loops

2. Valid Palindrome

Check if a string reads the same forwards and backwards.

// Start from both ends, compare characters

3. Remove Duplicates

Remove duplicates from sorted array in-place.

// One pointer for reading, one for writing

4. Container With Most Water

Find two lines that together form the container with most water.

// Two pointers from ends, move based on height

5. Trapping Rain Water

Calculate how much rainwater can be trapped between bars.

// Two pointers track left and right max heights
Why is Two Pointers O(n)?

1. Each Element Visited Once

Each pointer visits each element at most once. Since there are two pointers but they move towards each other, the total number of positions checked is at most n.

2. Eliminating Half the Space

At each step, you eliminate a portion of the search space:

If sum < target → move left forward (eliminate all pairs with current left)
If sum > target → move right backward (eliminate all pairs with current right)
This ensures each element is considered at most once per pointer

3. Comparison with Nested Loops

Two pointers vs nested loops:

Nested loops: O(n²) - Check all pairs (n × n combinations)
Two pointers: O(n) - Each pointer moves at most n times
Improvement: O(n²) → O(n) = n× faster!
Time Complexity Comparison
Problem TypeNested LoopsTwo PointersImprovement
Find Pair SumO(n²)O(n)n× faster
Check PalindromeO(n²)O(n)n× faster
Remove DuplicatesO(n²)O(n)n× faster
Three SumO(n³)O(n²)n× faster
Real-World Examples

🔍 Finding Pairs

E-commerce sites use two pointers to find product pairs within a price range. Instead of checking all combinations (O(n²)), two pointers find matches in O(n) time.

📝 Text Processing

Checking if text is a palindrome (reads same forwards/backwards) uses two pointers from both ends. Much faster than creating reversed string and comparing!

🎯 Matching Algorithms

Dating apps use two pointers to match users with compatible preferences in sorted lists. Efficient matching without checking all pairs!

💧 Water Management

The "Container With Most Water" problem models real scenarios like calculating water storage capacity between barriers, solved efficiently with two pointers.

🔢 Data Deduplication

Removing duplicates from sorted data (like logs or transactions) uses two pointers - one reads, one writes, processing in a single pass O(n) instead of O(n²).

Key Takeaways
  • Two pointers is O(n) - linear time

    Each pointer visits each element at most once, resulting in O(n) total operations

  • Much faster than nested loops

    Reduces O(n²) nested loop solutions to O(n) - a massive improvement!

  • Best for sorted arrays

    Sorting enables intelligent pointer movement, eliminating large portions of search space

  • Versatile technique

    Works for pairs, palindromes, sliding windows, and many other problems

Practice Exercises
Test your understanding of the two pointers technique with these exercises. Try to solve them yourself before checking the answers!