CODE THE HERO

Home › Learn › World 2: Twin Rivers

FREE

Palindrome Ferry

Two pointers from both ends, O(n)

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

The idea

Compare mirrored positions from the outside in; stop at the first mismatch.

The mission

The ferry only sails if the barrel row reads the same from both banks, like a palindrome. Pip reads from the left, Pix from the right. Compare, then both step inward. One mismatch is enough to say no. If they meet in the middle, the row is a palindrome.

Goal: submit(true) if the row reads the same both ways, otherwise submit(false).

The commands you get

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

pip.read() / pix.read()Barrel under each drone
pip.right() / pix.left()Move a drone inward
pip.index / pix.indexWhere each drone is
submit(bool)Hand in your verdict

What it costs

TimeO(n)
Extra spaceO(1)

How the stars are earned

  1. Correct verdict 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