Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA

Problem: Bars of heights h[i] stand at positions i. Pick two bars that hold the most water between them (area = min height × distance).

Problem: Bars of heights h[i] stand at positions i. Pick two bars that hold the most water between them (area = min height × distance).
def most_water(h):
    i, j, best = 0, len(h) - 1, 0
    while i < j:
        best = max(best, min(h[i], h[j]) * (j - i))
        if h[i] < h[j]:
            i += 1
        else:
            j -= 1
    return best
print(most_water([2, 7, 3, 8, 4, 6, 1]))
What is printed?
  1. A. 24
  2. B. 28
  3. C. 21
  4. D. 14

Correct answer: A. 24

Move the shorter side inward – the taller side can never do better with a smaller width. Checked pairs: (0,6)=6, (0,5)=10, (1,5)=min(7,6)×4=24, (1,4)=12, (1,3)=14, then the pointers meet; the best is heights 7 and 6 at distance 4 = 24. Taking the two tallest bars (7 and 8, distance 2 = 14) ignores width. O(n) instead of O(n²).

More Coding Interview Problems questions

Exams that ask this topic