Count Houses in a Circular Street Problem
Description
LeetCode Problem 2728.
You are given an object street of class Street that represents a circular street and a positive integer k which represents a maximum bound for the number of houses in that street (in other words, the number of houses is less than or equal to k). Houses' doors could be open or closed initially.
Initially, you are standing in front of a door to a house on this street. Your task is to count the number of houses in the street.
The class Street contains the following functions which may help you:
void openDoor(): Open the door of the house you are in front of.void closeDoor(): Close the door of the house you are in front of.boolean isDoorOpen(): Returnstrueif the door of the current house is open andfalseotherwise.void moveRight(): Move to the right house.void moveLeft(): Move to the left house.
Return ans which represents the number of houses on this street.
Example 1:
Input: street = [0,0,0,0], k = 10
Output: 4
Explanation: There are 4 houses, and all their doors are closed.
The number of houses is less than k, which is 10.
Example 2:
Input: street = [1,0,1,1,0], k = 5
Output: 5
Explanation: There are 5 houses, and the doors of the 1st, 3rd, and 4th house (moving in the right direction) are open, and the rest are closed.
The number of houses is equal to k, which is 5.
Constraints:
n == number of houses1 <= n <= k <= 10^3
Solution
Approach: Open Every Door, Then Close Them While Walking
We cannot see the number of houses, and the doors start in unknown states, so first erase that uncertainty. Walk k steps to the left, opening every door on the way. Because there are at most k houses, this visits each house at least once, so every door is now open and we are standing at a house k steps from where we started.
Now keep walking to the left: while the door in front of us is open, close it, count one more house and step left. After one full lap we are back at the first door we closed, which is now closed, so the loop stops and the counter holds the number of houses.
Complexity: O(k) time and O(1) space.
# Definition for a street.
# class Street:
# def openDoor(self):
# pass
# def closeDoor(self):
# pass
# def isDoorOpen(self):
# pass
# def moveRight(self):
# pass
# def moveLeft(self):
# pass
class Solution:
def houseCount(self, street: Optional["Street"], k: int) -> int:
for _ in range(k):
street.openDoor()
street.moveLeft()
ans = 0
while street.isDoorOpen():
street.closeDoor()
street.moveLeft()
ans += 1
return ans