VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-a-seat-with-distance-between-nearest-occupied-seats-maximised/

⇱ Find 0 with Farthest 1s in a Binary Array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find 0 with Farthest 1s in a Binary Array

Last Updated : 22 Mar, 2025

Given a string (seats) of 1s and 0s, where 1 represents a filled seat and 0 represents an empty seat in a row. Find an empty seat with maximum distance from an occupied seat. Return the maximum distance.

Examples:

Input: Seats = "1000101"
Output: 2
Explanation: Geek can take 3rd place and have a distance of 2 in left and 2 in right.

Input: Seats = "1000"
Output: 3
Explanation: Geek can take the rightmost seat to have a distance of 3.

[Naive Approach] Using Extra Array – O(n) Time and O(n) Space

This approach involves preprocessing the string to the identify the distance of the each empty seat from the nearest left occupied and right seats.

Step by Step Approach

  • Traverse the given string and fill closest one distance (in an array leftDist) on left for every 0.
  • Traverse again (this time from right to left) and fill closest one distance (in an array rightDist) on left for every 0.
  • In the final traversal, find the 0 which has maximum of mins of left and right distances

Output
2

[Expected Approach] Using One variable – O(n) Time and O(1) Space

We need to mainly find length of the longest subarray with 0s and place the Geek at the mid of it. So we traverse the array and keep track of empty 0s. If half of the current count is more than the current result, we update the result. One corner case that we need to handle is the case when we have 0s in the beginning and then a 1. We explicitly handle it by initializing result as -1 and then updating the result as count of 0s at the beginning.


Output
2
Comment
Article Tags: