FastPrepMaximize Distance to the Closest Occupied Seat

Maximize Distance to the Closest Occupied Seat

Amazon logoAmazon● EasyFULLTIMEPHONE SCREENONSITE INTERVIEW
Learn

Problem statement

You are given an array seats, where seats[i] = 1 means seat i is occupied and seats[i] = 0 means it is empty. At least one seat is empty and at least one seat is occupied.

Choose an empty seat that maximizes its distance to the closest occupied seat, and return the zero-based index of that seat. If several seats have the same maximum distance, return the smallest index.

Function

bestSeat(seats: int[]) → int

Examples

Example 1

seats = [1,0,0,0,1,1]return = 2

Seat 2 is two positions from the nearest occupied seat. Every other empty seat is only one position away.

Example 2

seats = [1,0,0,0]return = 3

The last seat is three positions from the only occupied seat.

Example 3

seats = [0,1]return = 0

Seat 0 is the only empty seat.

Example 4

seats = [1,0,0,1,0,0,1]return = 1

Seats 1, 2, 4, and 5 all have nearest-person distance one, so the smallest index is returned.

Constraints

  • 2 <= seats.length <= 20000
  • seats[i] is 0 or 1.
  • At least one seat is empty.
  • At least one seat is occupied.
  • If several empty seats have the same best distance, return the smallest index.

More Amazon problems

See Amazon hiring insights
public int bestSeat(int[] seats) {
    // Write your code here.
}
seats[1,0,0,0,1,1]
expected2
Checking account…