Core Module
12 min forge
Two Pointer Technique
Learn how to optimize array and string problems by using two indices that move toward each other or in the same direction.
βοΈ Two Pointer Technique: Dual Focus
Two pointer technique is a clever way to optimize nested loops. By using two separate indices (pointers) that move based on certain conditions, you can often reduce an $O(n^2)$ problem to $O(n)$ time.
π‘ The Logic (ELI5)
Imagine you're sorting a pile of laundry with your friend:
- Approach 1 (Brute Force): You pick one sock, then check every other sock in the pile for a match. Then repeat for the next.
- Approach 2 (Two Pointer):
- You stand at the left end of the pile, your friend stands at the right end.
- You look at your items, and if they meet a condition (e.g., both are white), you move toward the middle.
- You never look at the same sock twice because you only move forward.
π The Deep Dive
High-Level Patterns
- Opposite Directions: One pointer starts at the beginning (
start), and one starts at the end (end). They move toward each other. Great for:- Reversing an array.
- Finding Two Sum in a Sorted array.
- Palindrome checking.
- Same Direction (Slow/Fast): Both pointers start at the same side. One moves faster than the other. Great for:
- Removing duplicates.
- Detecting cycles in Linked Lists.
- Finding the middle of an array.
π οΈ Code Forge: Two Sum (Sorted)
javascript Standard/** * Finding two numbers in a SORTED array that add up to a Target. * Brute force: O(n^2) | Two Pointers: O(n) */ function twoSumSorted(nums, target) { let left = 0; let right = nums.length - 1; while (left < right) { const sum = nums[left] + nums[right]; if (sum === target) { return [left, right]; // Found the pair! } else if (sum < target) { // We need a larger sum, so move the left pointer forward left++; } else { // We need a smaller sum, so move the right pointer backward right--; } } return []; // No pair found } // Example const nums = [2, 7, 11, 15]; const target = 9; console.log(twoSumSorted(nums, target)); // [0, 1]
π― Interview Pulse
When to think of Two Pointers?
- Does the problem involve a Sorted array? (Always try two pointers first).
- Are you asked to find Pairs or Triplets?
- Are youasked to modify the array In-Place?
Variations to Practice
- 3Sum: Sorting + a loop + Two Pointers.
- Trapping Rain Water: A classic harder application of two opposite pointers.
- Container With Most Water: Dynamic movement of pointers based on height.
- Move Zeros: Slow and fast pointers moving in the same direction.