Date: 08-05-24
Problem
- We are given a input array with the numbers 0 and 1, where 1 represents someone sitting and 0 represents an empty seat. We’re trying to find an empty space where there’s no one to the left or right of us, however, there could instances where there’s an empty seat but only one seat that is available with someone to left and right. We need to find the best seat, therefore, the one with the max space to left and right would be the best and the least best would be one with less space. The leftmost and rightmost seat are always taken up. If there is not seat available we simply return
-1
.
Example:
# Best seat case scenario with three spaces
[1, 0, 0, 0, 1] - > we would return the index of the number in the middle between the two zeros.
Approach 1:
- In this approach we will be using two variables and two pointers to keep track of our current best seat. Initially we will have two variables called
max space
andbest seat
. Best seat will be initialized to-1
to account for no seats found andmax space
will be initialized to 0. To calculate the best seat and max space we will use two pointers. One pointer will begin ati
and the second pointer ati+1
. We check ifi + 1
is a value of 1, if so then we calculate themax space
using . This will give us the amount of space in between these two people. Now to calculate the best seat we will simply use the indices to find the median or the middle . Finally, we move the pointeri
to the last indexj
and we move the pointerj
until we find another value1
and do the same process over again.
Implementation
- Although we do have two while loops this is not an runtime of O(n^2) because we’re only iterating through the array once in one direction. Each element of the array is only processes a constant number of times
O(1)
.
Complexity Analysis
- Time Complexity:
- Space Complexity: