CODE THE HERO

Home › Learn › World 1: Array Plains

FREE

Rotate the Row

Rotation by three reversals, O(n)

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

The idea

Rotating right by k equals: reverse all, reverse the first k, reverse the rest. Each crate moves at most twice.

The mission

The last k crates should go to the front of the row, and everything else shifts right. Moving one crate at a time, k times over, wears out the hero. There's a neat trick! Reverse the whole row, then reverse the first k, then reverse the rest.

Goal: Rotate the row right by k places. 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:

kHow far to rotate (can be bigger than the row!)
crates.lengthHow many crates
crates.swap(i, j)Swap two crates (1 move)
crates.get(i)Lift a crate
crates.set(i, v)Repaint crate i with value v (1 move)

What it costs

TimeO(n)
Extra spaceO(1)

How the stars are earned

  1. Rotated correctly on every test
  2. At most 2n moves
  3. At most n moves

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