CODE THE HERO

Home › Learn › World 2: Twin Rivers

FREE

Remove Duplicates

Read pointer and write pointer, O(n)

Level 2.3 of Code the Hero, in Twin Rivers: two pointers and sliding windows.

The idea

A slow write pointer and a fast read pointer compact a sorted array in place in one pass.

The mission

The sorted barrels have copies. Traders only want one of each weight, packed at the front. Walk the row with a reader. Keep a writer spot for the next new weight. Because the row is sorted, copies always sit next to each other.

Goal: Move one of each weight to the front, in order, then submit how many different weights there are.

The commands you get

You write real Python, Java or JavaScript. These are the moves the hero understands in this level:

crates.lengthHow many barrels
crates.get(i)Read barrel i
crates.set(i, v)Repaint barrel i with weight v
submit(count)Hand in the number of different weights

What it costs

TimeO(n)
Extra spaceO(1)

How the stars are earned

  1. Correct front and count on every test
  2. At most 2n reads
  3. At most n reads

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 Twin Rivers