Home › Learn › World 1: Array Plains
FREERotate 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:
k | How far to rotate (can be bigger than the row!) |
crates.length | How 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
| Time | O(n) |
| Extra space | O(1) |
How the stars are earned
- Rotated correctly on every test
- At most 2n moves
- 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.
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
- The Heaviest Crate: Linear scan, O(n)
- Reverse the Row: Two pointers, n/2 swaps
- Count the Apples: Counting in one pass, O(n)
- Irrigation Channels: Prefix sums: O(n) build, O(1) query
- Bubble Sort Machine: Sorting by adjacent swaps, O(n²)
- Storm Harvester: Kadane's algorithm, O(n)