Skip to main content

๐ŸŽฎ Two Pointers โ€” Interactive Practice

Companion to the Two Pointers guide. Watch the technique in motion, then solve it yourself in the live editor below โ€” all running in your browser.

๐ŸŽฌ Watch it work: Two Sum on a sorted arrayโ€‹

The converging pointers pattern: start at both ends, move inward based on whether the current sum is too small or too big. Press Play (or step through) to see why it's O(n) instead of O(nยฒ).

Two Sum II โ€” Converging PointersStep 1 / 3
Lโ–ผ
2
3
5
8
11
Rโ–ผ
15
Target = 13. Start: L at index 0, R at index 5.

Why it works: because the array is sorted, if the sum is too small the only way to increase it is to move the left pointer right; if too big, move the right pointer left. Every step eliminates one candidate, so we touch each element at most once.

๐Ÿ Your turn: implement itโ€‹

Fill in the two-pointer logic and run the tests. The starter already has a working solution โ€” try modifying it (e.g. return the values instead of indices, or handle "no solution").

Loading editorโ€ฆ

๐Ÿง  Challenge yourselfโ€‹

  1. Modify the function to return the values instead of indices.
  2. What happens on an unsorted array? (Try it โ€” then recall why sorting is a prerequisite.)
  3. Extend to 3Sum: fix one element, two-pointer the rest. Sketch it in the editor.

Ready for more? Continue the learning path โ†’ Sliding Window