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

Input & Output

Example 1 — Mixed Door States
$ Input: street = [true, false, true, false], k = 4
Output: 4
💡 Note: There are 4 houses in the circular street. We can mark the starting house and count until we return to it.
Example 2 — All Doors Closed
$ Input: street = [false, false, false], k = 10
Output: 3
💡 Note: All 3 doors are initially closed. We open the first door as a marker, then count 2 more houses before returning to the open door.
Example 3 — Single House
$ Input: street = [true], k = 2
Output: 1
💡 Note: Only one house in the street. After opening/closing operations, we determine there's exactly 1 house.

Constraints

  • 1 ≤ number of houses ≤ k
  • k ≤ 103
  • Houses are arranged in a circular street

Visualization

Tap to expand
Count Houses in a Circular StreetOPENCLOSEDOPENCLOSEDInput: Circular StreetMixed door statesOutput: 4Total houses countedWalk & CountUse door states to detect when full circle is completed
Understanding the Visualization
1
Input
Circular street with houses having open/closed doors
2
Process
Use door manipulation to mark position and detect full circle
3
Output
Total count of houses in the street
Key Takeaway
🎯 Key Insight: Use door manipulation as breadcrumbs to detect when you've walked the full circle
Asked in
Meta 15 Google 12
23.5K Views
Medium Frequency
~15 min Avg. Time
842 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