Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find maximum distance between empty and occupied seats in Python
Suppose we have a list with only 0s and 1s called seats, where seats[i] represents a seat. When it is 1, the seat is occupied; otherwise, it's free. Given that there is at least one free seat and at least one occupied seat, we need to find the maximum distance from a free seat to the nearest occupied seat.
For example, if the input is seats = [1, 0, 1, 0, 0, 0, 1], the output will be 2, because we can occupy seat seats[4], and the distance to the nearest occupied seat is 2.
Algorithm Approach
To solve this problem, we follow these steps:
res:= 0 (stores maximum distance found so far)last:= -1 (tracks position of last occupied seat)n:= size of seats-
For each position i from 0 to n-1:
-
If
seats[i]is 1 (occupied):res:= maximum of currentresand distance calculationUpdate
last:= i
-
Return maximum of
resand distance from last occupied seat to end
How It Works
The algorithm considers three cases:
Distance from start: If no occupied seat has been found yet, use full distance from start
Distance between occupied seats: Use half the distance between two occupied seats
Distance to end: Distance from last occupied seat to the end of array
Example
Let us see the following implementation to get better understanding ?
def solve(seats):
res, last, n = 0, -1, len(seats)
for i in range(n):
if seats[i]:
res = max(res, i if last < 0 else (i - last) // 2)
last = i
return max(res, n - last - 1)
seats = [1, 0, 1, 0, 0, 0, 1]
result = solve(seats)
print(f"Maximum distance: {result}")
The output of the above code is ?
Maximum distance: 2
Step-by-Step Execution
Let's trace through the example [1, 0, 1, 0, 0, 0, 1]:
def solve_with_trace(seats):
res, last, n = 0, -1, len(seats)
print(f"Initial: seats = {seats}")
for i in range(n):
if seats[i]:
distance = i if last < 0 else (i - last) // 2
res = max(res, distance)
print(f"Position {i}: occupied, distance = {distance}, max_res = {res}")
last = i
final_distance = n - last - 1
final_res = max(res, final_distance)
print(f"Distance to end: {final_distance}, final result: {final_res}")
return final_res
seats = [1, 0, 1, 0, 0, 0, 1]
solve_with_trace(seats)
The output shows the step-by-step process ?
Initial: seats = [1, 0, 1, 0, 0, 0, 1] Position 0: occupied, distance = 0, max_res = 0 Position 2: occupied, distance = 1, max_res = 1 Position 6: occupied, distance = 2, max_res = 2 Distance to end: 0, final result: 2
Conclusion
This algorithm efficiently finds the maximum distance by tracking occupied seats and calculating distances in three scenarios: from start, between occupied seats, and to the end. The time complexity is O(n) with O(1) space complexity.
