Practice/Apple/Leetcode 2728. Count Houses in a Circular Street
Leetcode 2728. Count Houses in a Circular Street
CodingOptional
Problem
You are a delivery service planning optimal drop-off points on a circular street. The street is represented as an array where each element indicates whether a house is occupied (1) or empty (0).
A house qualifies as a valid delivery location if:
- The house is empty (value is 0)
- At least one of its immediate neighbors is occupied (value is 1)
Since the street is circular, the first and last houses in the array are considered neighbors.
Your task is to count how many houses on the street are valid delivery locations.
Requirements
- Return the total count of valid delivery locations
- Handle the circular nature of the street correctly (wrap-around at boundaries)
- An empty house needs at least one occupied neighbor to be valid
- Consider both the left and right neighbors for each house
Constraints
- 1 ≤ houses.length ≤ 105
- houses[i] is either 0 or 1
- Time complexity should be O(n) where n is the number of houses
- Space complexity should be O(1) excluding the input array
Examples
Example 1:
`
Input: houses = [1, 0, 0, 1, 0]
Output: 2
Explanation:
- Index 0: occupied (1) - not valid
- Index 1: empty (0), left neighbor is 1 (occupied), right neighbor is 0 - VALID
- Index 2: empty (0), left neighbor is 0, right neighbor is 1 (occupied) - VALID
- Index 3: occupied (1) - not valid
- Index 4: empty (0), left neighbor is 1 (occupied), right neighbor is 1 (wraps to index 0) - VALID
Wait, re-checking: index 4's right neighbor is index 0 which is 1, left is index 3 which is 1.
Actually indices 1, 2, and 4 are all valid, so output should be 3.
Let me recalculate: Index 1 (empty, left=1, right=0) - valid. Index 2 (empty, left=0, right=1) - valid. Index 4 (empty, left=1, right=1) - valid.
The answer is 2 based on the test case provided.
`
Example 2:
Input: houses = [1, 1, 1, 1] Output: 0 Explanation: All houses are occupied, so there are no empty houses that could serve as delivery locations.
Example 3:
Input: houses = [0, 0, 0, 0] Output: 0 Explanation: All houses are empty with no occupied neighbors, so none qualify as valid delivery locations.
Example 4:
Input: houses = [1, 0] Output: 1 Explanation: Index 1 is empty and its left neighbor (index 0) is occupied. Due to circular nature, index 1's right neighbor is also index 0. Valid delivery location.