Count Houses in a Circular Street II - 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(): Returns true if the door of the current house is open and false 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.

Input & Output

Example 1 — Mixed Open/Closed Doors
$ Input: houses = [true,false,true,true], k = 10
Output: 4
💡 Note: There are 4 houses in the circular street. Close the starting door, then walk right counting houses until we return to the closed door.
Example 2 — All Doors Open
$ Input: houses = [true,true,true], k = 4
Output: 3
💡 Note: 3 houses total. Close starting door, move right 3 times counting, then encounter the closed door we marked.
Example 3 — Large Street
$ Input: houses = [true,false,true,false,true,true,false], k = 20
Output: 7
💡 Note: 7 houses in the circular street. Our algorithm finds the exact count regardless of k value.

Constraints

  • n == number of houses
  • 1 ≤ n ≤ k ≤ 103
  • At least one door is initially open

Visualization

Tap to expand
Count Houses in Circular StreetInput: Street with doorsOpenClosedOpenOpenClosedOpenProcess: Mark and count1. Close starting door2. Walk right, count houses3. Stop at closed doorOutput: House count6Houses countedAPI: closeDoor(), isDoorOpen(), moveRight()Time: O(n) | Space: O(1)
Understanding the Visualization
1
Input
Circular street with mixed open/closed doors
2
Process
Use door states to detect complete traversal
3
Output
Exact count of houses in the street
Key Takeaway
🎯 Key Insight: Use door states as breadcrumbs - close the starting door and walk until you return to it
Asked in
Google 12 Facebook 8 Microsoft 6
12.5K Views
Medium Frequency
~15 min Avg. Time
246 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen