Data Structures & AlgorithmsHardProduct Company SDE · two pointers

Problem: Water is poured into a container of heights [1, 8, 6, 2, 5, 4, 8, 3, 7]. Choose two lines to maximise the area of water they hold, using the two-pointer method. What is printed?

Problem: Water is poured into a container of heights [1, 8, 6, 2, 5, 4, 8, 3, 7]. Choose two lines to maximise the area of water they hold, using the two-pointer method. What is printed?
h = [1, 8, 6, 2, 5, 4, 8, 3, 7]
i, j = 0, len(h) - 1
best = 0
while i < j:
    best = max(best, min(h[i], h[j]) * (j - i))
    if h[i] < h[j]:
        i += 1
    else:
        j -= 1
print(best)
What is printed?
  1. A. 48
  2. B. 49
  3. C. 56
  4. D. 42

Correct answer: B. 49

The pair of heights 8 (index 1) and 7 (index 8) gives 7 * 7 = 49. Always moving the taller pointer skips this pair, so the shorter pointer must move.

More Coding Interview Problems questions

Exams that ask this topic