Skip to content
Algorithms for Beginners

Problems / Two pointers

Biggest tank

medium

New here? How this page works
  1. Read the Problem tab. Read it twice. Look at the examples: what goes in, what should come out.
  2. Open Break it down. Answer the questions in your own words. This is your plan.
  3. Write code on the right. Start small. Stuck on a blank page? Press “Write my plan as comments”.
  4. Press Run examples. See which examples pass. Red ones show what your code gave and what was expected.
  5. Stuck? Use Hints, one at a time. Still stuck after all of them? Read the Walkthrough. That's learning, not cheating.
  6. Press Submit. It runs hidden tests too. Pass them all, and it's solved.

A row of walls stands 1 metre apart. heights[i] is the height of the wall at position i.

Pick any two walls. Together with the ground between them, they make a tank. The water can only rise as high as the shorter of the two walls, so the tank holds (distance between the walls) × (height of the shorter wall) units of water. Walls in between don't get in the way.

Return the most water any tank can hold.

Examples

  1. Example 1

    Input
    heights = [2, 7, 4, 1, 6, 3, 7, 5]
    Output
    35

    The walls at positions 1 and 6 are both 7 high and 5 apart: 5 × 7 = 35.

  2. Example 2

    Input
    heights = [3, 3]
    Output
    3

    1 apart, both 3 high: 1 × 3 = 3.

  3. Example 3

    Input
    heights = [4, 1, 1, 1, 4]
    Output
    16

    The two 4s are 4 apart: 4 × 4 = 16. The short walls between them don't matter.

Rules

  • heights has between 2 and 100,000 walls.
  • Heights are whole numbers from 0 to 100,000.
Words on this page, in plain English (1)Open if any word is new to you
Index (position)
Where an item sits in a list. Counting starts at 0, not 1, so the first item is at position 0.

Every word, explained simply

Your solution

JavaScript · Press Esc then Tab to leave the editor

function biggestTank(heights) {
  // Return the most water two walls can hold.
}

Blank page fear? (uses your answers from Break it down; comments don’t run).

Results

Run the examples to check your code, then Submit to run every test.

Next steps in two pointers

  • Learn the two pointers pattern

    Walk through a list from both ends (or at two speeds) at once.

  • Three to zero

    Medium. Find every different set of three numbers in a list that adds up to zero.

  • Mirror phrase

    Easy. Check whether a phrase reads the same backwards, ignoring spaces, punctuation and capitals.

  • Flip in place

    Easy. Reverse a list by swapping items inside it, without building a new list.

  • Pair in a sorted list

    Easy. Find two prices that add up to a budget, when the prices are already sorted.

  • Squash repeats

    Easy. Remove repeated values from a sorted list in place, keeping one of each.