Home › Learn › World 1: Array Plains
FREECount the Apples
Counting in one pass, O(n)
Level 1.3 of Code the Hero, in Array Plains: scan, swap and sort a row of crates.
The idea
A running counter over one pass. The same pattern answers 'how many', 'is there any' and 'are all' questions.
The mission
Only crates heavier than the limit are full of apples. The market wants to know how many are full. Keep a counter. Lift each crate once and add one when it's heavier than limit. Careful: heavier means strictly more than the limit, not equal to it.
Goal: Count the crates that weigh more than limit and submit(count).
The commands you get
You write real Python, Java or JavaScript. These are the moves the hero understands in this level:
limit | The weight a crate must beat |
crates.length | How many crates |
crates.get(i) | Hero lifts crate i and returns its weight |
crates.mark(i) | Plant a gold flag on crate i (free) |
submit(value) | Hand in your answer |
What it costs
| Time | O(n) |
| Extra space | O(1) |
How the stars are earned
- Correct count on every test
- At most 2n lifts
- At most n lifts
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
- 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)