Problem
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 (at least one is open).
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 closeDoor()
: Close the door of the house you are in front of.boolean isDoorOpen()
: Returnstrue
if the door of the current house is open andfalse
otherwise.void moveRight()
: Move to the right house.
Note that by circular street, we mean if you number the houses from
1
to n
, then the right house of housei
is housei+1
for i < n
, and the right house of housen
is house1
.
Return ans
which represents the number of houses on this street.
Examples
Example 1:
|
|
Example 2:
|
|
Constraints:
n == number of houses
1 <= n <= k <= 10^5
street
is circular by definition provided in the statement.- The input is generated such that at least one of the doors is open.
Solution
Method 1 – Mark and Move (Simulation, Only Close)
Intuition
Since the street is circular and at least one door is open, we can close each open door as we visit it, moving right each time. When we return to a house with a closed door, we’ve completed a full circle and counted all houses.
Approach
- Start at the initial house. If the door is open, close it and increment the count.
- Move right and repeat: if the door is open, close it and increment the count.
- Stop when you return to a house with a closed door (the starting house after a full circle).
- Return the count.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
, where n is the number of houses, as we may visit each house once. - 🧺 Space complexity:
O(1)
, only a constant amount of space is used.