CODE THE HERO

Home › Learn › World 1: Array Plains

FREE

Reverse the Row

Two pointers, n/2 swaps

Level 1.2 of Code the Hero, in Array Plains: scan, swap and sort a row of crates.

The idea

Two pointers start at both ends and meet in the middle. Each swap fixes two positions, so n/2 swaps are enough.

The mission

The cart arrives from the other side, so the crates must face the other way. Reverse the whole row with crates.swap(i, j). The hero carries two crates past each other. Hint from an old farmer: swap the two ends, then step inward.

Goal: Reverse the order of the crates. No submit needed: the row is checked when your code ends.

The commands you get

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

crates.lengthHow many crates
crates.swap(i, j)Hero swaps crate i and crate j
crates.get(i)Read a crate (not needed here)

What it costs

TimeO(n)
Swapsn/2
Extra spaceO(1)

How the stars are earned

  1. Row reversed on every test
  2. At most n swaps
  3. At most n/2 swaps

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 Array Plains