CODE THE HERO

Home › Learn › World 1: Array Plains

FREE

Count 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:

limitThe weight a crate must beat
crates.lengthHow 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

TimeO(n)
Extra spaceO(1)

How the stars are earned

  1. Correct count on every test
  2. At most 2n lifts
  3. 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.

▶ 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