Skip to content
ExamSpine

Write it

Seats together

A functionPython or Java13 tests, 8 of them hidden

On a phone? Put the lines in order instead

The Lumen cinema's booking system stores one row of seats as a list (an array in Java) of whole numbers: 0 is a free seat and 1 is a booked seat. Seat positions start at 0. A group wants to sit together. Write a function that returns the position of the first seat of the first block of n free seats next to each other.

The design team wrote this plan for it:

RUN = 0
loop through the row from position 0
    if the seat is free, add 1 to RUN
    otherwise set RUN back to 0
    if RUN equals n, return the position
      of the first seat of this block
return -1
  1. A block is n free seats in positions next to each other. If there is more than one such block, return the position of the first seat of the one that comes first (the lowest position).
  2. If the row has no block of n free seats, return -1.
  3. A block may reach the last seat of the row.
  4. n is a whole number from 1 to 30. The row holds only 0s and 1s, has at most 30 seats, and can be empty.

Only the number your function returns is checked.

def first_block(row: list[int], n: int) -> int

Examples

Your function is tested on 13 cases: the 5 examples below, and 8 hidden ones that check the rules above.

  • first_block([1, 0, 0, 1, 0], 2) should return 1: the block is seats 1 and 2, so the answer is the first of them, 1 (rule 1)
  • first_block([0, 1, 0, 0, 0], 3) should return 2: a block that reaches the last seat still counts (rule 3)
  • first_block([0, 1, 0, 1, 0], 2) should return -1: three free seats, but no two next to each other (rules 1 and 2)
  • first_block([1, 1, 1], 1) should return -1: every seat is booked, so -1, not 0 (rule 2)
  • first_block([0, 0, 1, 0, 0], 2) should return 0: two separate blocks of 2, and the first one wins (rule 1)

public static int firstBlock(int[] row, int n)

Checking whether Java answers can run here.

Examples

Your function is tested on 13 cases: the 5 examples below, and 8 hidden ones that check the rules above.

  • firstBlock(new int[]{1, 0, 0, 1, 0}, 2) should return 1: the block is seats 1 and 2, so the answer is the first of them, 1 (rule 1)
  • firstBlock(new int[]{0, 1, 0, 0, 0}, 3) should return 2: a block that reaches the last seat still counts (rule 3)
  • firstBlock(new int[]{0, 1, 0, 1, 0}, 2) should return -1: three free seats, but no two next to each other (rules 1 and 2)
  • firstBlock(new int[]{1, 1, 1}, 1) should return -1: every seat is booked, so -1, not 0 (rule 2)
  • firstBlock(new int[]{0, 0, 1, 0, 0}, 2) should return 0: two separate blocks of 2, and the first one wins (rule 1)
solution.pySolution.java