Home › Learn › World 1: Array Plains
FREEReverse 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.length | How 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
| Time | O(n) |
| Swaps | n/2 |
| Extra space | O(1) |
How the stars are earned
- Row reversed on every test
- At most n swaps
- 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.
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)
- Count the Apples: Counting in one pass, O(n)
- Irrigation Channels: Prefix sums: O(n) build, O(1) query
- Rotate the Row: Rotation by three reversals, O(n)
- Bubble Sort Machine: Sorting by adjacent swaps, O(n²)
- Storm Harvester: Kadane's algorithm, O(n)