Home › Learn › World 1: Array Plains
FREEThe Heaviest Crate
Linear scan, O(n)
Level 1.1 of Code the Hero, in Array Plains: scan, swap and sort a row of crates.
The idea
Walk the row once, remembering the best value so far. Every item must be looked at once, so no method can beat one pass.
The mission
King Brute scrambled my crates! I need the heaviest one for the harvest cart. Write code to walk the row. crates.get(i) makes our hero lift crate i and tell you its weight. Every lift takes time. A good farmer lifts each crate only once.
Goal: Find the weight of the heaviest crate and hand it in with submit(weight).
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 are in the row |
crates.get(i) | Hero walks to crate i, lifts it and returns its weight |
submit(value) | Hand in your answer. This ends the run |
hero.say(text) | Make the hero speak |
console.log(x) | Print to the Log tab |
What it costs
| Time | O(n) |
| Extra space | O(1) |
How the stars are earned
- Correct answer on every test
- At most 2n lifts
- At most n lifts: one pass
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. It runs in your browser, on a phone or a laptop.
More in Array Plains
- 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
- 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)