CODE THE HERO

Home › Learn › World 2: Twin Rivers

FREE

Row to the Pair

Two pointers on sorted data, O(n)

Level 2.1 of Code the Hero, in Twin Rivers: two pointers and sliding windows.

The idea

In sorted data, the sum of the two ends tells you which end is useless: a too-small sum can't use the left barrel with anything, so drop it.

The mission

The barrels float in order, lightest to heaviest. I need two that add up to the target exactly. Pip starts at the left end and Pix at the right. Each can read the barrel under it. Sum too small? Move Pip right. Too big? Move Pix left. They never need to go back.

Goal: Find two barrels whose weights add up to target, then submit(pip.index, pix.index).

The commands you get

You write real Python, Java or JavaScript. These are the moves the hero understands in this level:

targetThe sum you need
pip.read() / pix.read()Weight of the barrel under that drone
pip.right()Move Pip one barrel right
pix.left()Move Pix one barrel left
pip.index / pix.indexWhere each drone is
submit(i, j)Hand in the two positions

What it costs

TimeO(n)
Extra spaceO(1)

How the stars are earned

  1. Correct pair on every test
  2. Solved
  3. At most one read per drone per step

Your code is also checked on hidden inputs, so it has to work for any case, not only the one on screen.

▶ Play this level free

No sign-up. Levels open in order, so if this one is still locked you start at the first level that isn't.

More in Twin Rivers