पाठ 7 / 26

Two Pointers

Converging from both ends.

Each move discards impossible answers

With a sorted array, place pointers at both ends: if the sum is too small move the left pointer right, if too large move the right pointer left. Each step safely discards candidates, giving O(n). In "container with most water", always move the shorter side, because moving the taller one can never increase the area. Same-direction pointers handle in-place tasks such as removing duplicates.

Move boundaries, not loops

Moving two indices cleverly replaces nested loops for sorted arrays and contiguous ranges.

Three ideas: two pointers, sliding windows, monotonic deques.
Figure 3.1 — Two pointers, windows and deques.

Pair sum and maximum water container, run

I ran this with Python 3.12.3 (standard library only). The pair summing to 10 is at indices 2 and 3 (4 + 6); no pair reaches 100; the best container holds 49 units.

# Two pointers on a sorted array and for max water container
def pair_with_sum(sorted_nums, target):
    lo, hi = 0, len(sorted_nums) - 1
    while lo < hi:
        s = sorted_nums[lo] + sorted_nums[hi]
        if s == target:
            return lo, hi
        if s < target:
            lo += 1
        else:
            hi -= 1
    return None

def max_area(heights):
    lo, hi, best = 0, len(heights) - 1, 0
    while lo < hi:
        best = max(best, (hi - lo) * min(heights[lo], heights[hi]))
        if heights[lo] < heights[hi]:
            lo += 1                      # moving the taller side can never help
        else:
            hi -= 1
    return best

print(pair_with_sum([1, 3, 4, 6, 8, 11], 10))
print(pair_with_sum([1, 2, 3], 100))
print(max_area([1, 8, 6, 2, 5, 4, 8, 3, 7]))

Output:

(2, 3)
None
49

Justify each pointer move

Interviewers want to hear why discarding candidates is safe, not just the code.

त्वरित जाँच: In "container with most water", which pointer should move?

  • The one at the shorter line
  • The one at the taller line
  • Both always
  • Neither; use nested loops
Answer

The one at the shorter line — The shorter side limits the area.