Two Pointers Visualization & Animation

Uses left and right indices moving toward each other to solve pair-sum and partitioning problems in O(n).

## What is it? The Two Pointers technique uses two index variables that move through the array, typically from opposite ends toward the middle, or both moving in the same direction at different speeds. It converts naive O(n²) brute-force solutions into O(n). ## How it works **Opposite-ends variant (e.g., Two Sum II):** - Place `left = 0`, `right = n-1` - Compute the sum of `arr[left] + arr[right]` - If sum == target → found - If sum < target → move `left` right to increase the sum - If sum > target → move `right` left to decrease the sum - Repeat until `left >= right` ## When to use - Finding pairs with a target sum in a sorted array - Removing duplicates in-place - Reversing arrays and strings - Checking palindromes - Container with most water, Trapping Rain Water ## Key Points - Works best on **sorted** arrays - Reduces O(n²) brute force to O(n) - No extra space needed — O(1) - Both pointers together traverse the array at most once

Category: algorithms

Difficulty: intermediate

Time Complexity: O(n)

Space Complexity: O(1)

Two Pointers

intermediate

Uses left and right indices moving toward each other to solve pair-sum and partitioning problems in O(n).

2
[0]
5
[1]
7
[2]
11
[3]
15
[4]
20
[5]
Two pointers: L at index 0, R at index 5. Looking for two numbers that add up to 18.