Program to check whether all can get a seat or not in Python


Suppose we have a number n, there are n number of people searching for a seat, we also have a list of bits where 1 represents an already occupied seat and 0 represents empty seat. No two people can sit next to each other, so we have to check whether all n people can find a seat or not.

So, if the input is like n = 2 seats = [1, 0, 0, 0, 1, 0, 0], then the output will be True, because they can seat at index 2 and 6.

To solve this, we will follow these steps −

  • insert 0 at beginning of seats and insert [0, 1] at the end of seats
  • res := 0, gap := 0
  • for each i in seats, do
    • if i is same as 0, then
      • gap := gap + 1
    • otherwise when gap > 0, then
      • res := res + floor of (gap - 1)/2
      • gap := 0
  • return true when res >= n otherwise false

Example

Let us see the following implementation to get better understanding −

def solve(n, seats):
   seats = [0] + seats + [0, 1]
   res = 0
   gap = 0
   for i in seats:
      if i == 0:
         gap += 1
      elif gap > 0:
         res += (gap - 1) // 2
         gap = 0
   return res >= n

n = 2
seats = [1, 0, 0, 0, 1, 0, 0]
print(solve(n, seats))

Input

2, [1, 0, 0, 0, 1, 0, 0]

Output

True

Updated on: 14-Oct-2021

424 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements