Lesson 4/25 ยท ๐Ÿ“‹ Linear Structures
๐Ÿ“‹ Linear StructuresLesson 4/25
Phase 1 ยท Linear Structures18 min

Two Pointers Technique

Turn O(nยฒ) brute force into elegant O(n) solutions

Here is a row of numbers, sorted small to large. You want two of them that add up to a target. The obvious way is to try every pair, but that is slow: with a hundred numbers, that is thousands of pairs.
The two pointers trick is smarter. Put one finger on the smallest number and one on the biggest, then close them in. Too big a sum? Pull the right finger in to a smaller number. Too small? Push the left finger out to a bigger one. The fingers march toward each other and the answer falls out in a single pass. Try it below.
That is the whole idea, and it turns a slow O(n squared) hunt (every pair) into a quick O(n) one (a single walk). It works whenever the data is sorted, or whenever moving one end in a known direction always brings you closer to the answer. It is one of the most loved patterns in interviews for exactly that reason.
Two Sum on a sorted array, O(n)python
def two_sum_sorted(nums, target):
    """Find two numbers that sum to target. nums is sorted."""
    left, right = 0, len(nums) - 1

    while left < right:
        current_sum = nums[left] + nums[right]
        if current_sum == target:
            return [left, right]
        elif current_sum < target:
            left += 1   # Need bigger sum โ†’ move left pointer right
        else:
            right -= 1  # Need smaller sum โ†’ move right pointer left
    return []

print(two_sum_sorted([1, 2, 3, 4, 6], 6))  # โ†’ [1, 3]

"racecar", compare rโ†”r, aโ†”a, cโ†”c, all match โ†’ palindrome

๐Ÿ”€In the Real World...

Merging two sorted arrays in merge sort uses two pointers, one for each array, advancing the pointer for whichever element is smaller. This is what makes merge sort O(n log n) instead of O(nยฒ).

๐Ÿค”Quick Check

When is the two-pointer technique applicable?

Practice Exercises

0/2 solved
Exercise 1 of 2medium
โฑ 00:00

Palindrome Check

Use two pointers to check if a string is a palindrome (ignoring non-alphanumeric characters and case).
Expected output:TrueFalse
solution.py
1 / 2
Exercise 2 of 2medium
โฑ 00:00

Container With Most Water

Given heights of walls, find two walls that form a container with maximum water area.Area = min(height[left], height[right]) ร— (right - left)
Expected output: 49
solution.py
2 / 2
Solve all 2 exercises to unlock completion