![]() |
VOOZH | about |
There are n rooms in a straight line in Geekland State University's hostel. You are given a binary string s of length n, where s[i] = '1' means there is a WiFi router in the i-th room, and s[i] = '0' means there is no WiFi in that room.
Examples:
Input: x = 0, s = "010"
Output: false
Explanation: Since the range is 0, so Wifi is only accessible in second room while 1st & 3rd room have no wifi. Therefore answer is false for this test case.Input: x = 1, s = "10010"
Output: true
Explanation:
Index 0: WiFi is available.
Index 1: Since the range of the 0th index is 1, WiFi is available here.
Index 2: Since the range of the 3rd index is 1, WiFi is also available here.
Index 3: WiFi is available.
Index 4: The range of the 3rd index covers this position.
So, all the rooms have WiFi. Therefore, the answer is true.
Table of Content
The approach is to check every position in the string and verify whether it is covered by at least one WiFi router.
For each index i, we iterate through all indices j to find a router (s[j] == '1') such that the distance between them is within the allowed range x (i.e., |i - j| ≤ x). If such a router exists, the position is considered covered. If for any position no such router is found, we immediately return false. If all positions are successfully covered, we return true.
We can use prefix array and suffix array to preprocess the positions of the nearest wifi in the left and right directions for each room. .
Follow the steps to implement the approach:
true
We use a greedy approach by keeping track of the farthest position covered so. Whenever we find a WiFi router,, we extend the coverage range. In the end, we verify whether the entire string is covered.
maxReach = -1s[i] == '1', check if it able to able to cover all before it. If gap exists, return falsemaxReach = max(maxReach, i + x)maxReach >= n - 1true