
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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
- if i is same as 0, then
- 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
- Related Articles
- Program to check whether we can take all courses or not in Python
- Program to check whether we can unlock all rooms or not in python
- Program to check whether we can get N queens solution or not in Python
- Python program to check whether we can pile up cubes or not
- Program to check whether Amal can win stone game or not in Python
- Program to check whether all leaves are at same level or not in Python
- Program to check whether all palindromic substrings are of odd length or not in Python
- Python program to check whether a list is empty or not?
- Program to check whether one point can be converted to another or not in Python
- Program to check whether we can convert string in K moves or not using Python
- Program to check whether parentheses are balanced or not in Python
- Python program to check whether a given string is Heterogram or not
- Program to check whether a binary tree is complete or not in Python
- Program to check whether a binary tree is BST or not in Python
- Program to check whether two trees can be formed by swapping nodes or not in Python

Advertisements