Skip to the content

The loneliest seat

Problem

Irene boards the last car of the night train, ready to sleep. The seats run in a single row, and she wants the free one that sits as far as possible from the closest passenger.

Write a function that takes car, a string of "1" (taken) and "0" (free) with at least one of each, and returns a whole number: the index of the free seat whose distance to the closest taken seat is the largest. That taken seat can be on its left or on its right, and the distance is how many places apart they are.

With "10001", index 1 is 1 away from the closest taken seat, index 2 is 2 away and index 3 is 1 away: it returns 2. At the ends there are passengers on one side only: with "0001" index 0 is 3 away, so it returns 0. If two seats tie, return the one with the smaller index.

Examples

  • The example

    "10001" → 2

  • The left end wins

    "0001" → 0

  • The right end wins

    "1000" → 3

  • A single free seat

    "01" → 0

Besides these, the challenge has hidden tests that are revealed when you submit your solution.

You start with this

Python

def best_seat(car):
    pass

JavaScript

function bestSeat(car) {
}
Solve this challenge

It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.

More O(n²) challenges

See all challenges →