Target14
Current Sum
?
L
2
0
3
1
5
2
8
3
11
4
R
15
5

Converging Paths

The Two Pointers technique involves using two indices (pointers) to traverse access data. Often, they start at opposite ends and move towards each other.

Setup

We want to find two numbers that add up to 14. We place 'L' at the start (Smallest) and 'R' at the end (Largest).

Too Large

Current Sum is 17 (2 + 15). This is bigger than 14. To get a smaller sum, we MUST decrease the larger number. So, we move 'R' to the left.

Check Again

Now L is 2, R is 11. Sum is 13.

Too Small

13 is less than 14. We need a bigger sum. We can't move R right (we came from there), so we must increase the smaller number. Move 'L' to the right.

Third Time Lucky

Now L is 3, R is 11. Sum is 14.

Target Locked

Success! We found the pair (3, 11). By intelligently moving pointers based on the sorted order, we avoided checking every single pair.

Meeting in the Middle

Because L and R only move towards each other and never backwards, we process each element at most once. This is O(n), vastly better than the O(n²) naive approach.

Opposites Attract.

Two Pointers and Sliding Window are the twin pillars of Array optimization.

AlgoAnimator: Interactive Data Structures