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 Street INPUT T F T F You = Open (true) = Closed (false) street = [T, F, T, F] k = 4 (max houses) ALGORITHM STEPS 1 Close All Doors Move k times, close each All closed 2 Open Starting Door Mark where we start Start marked 3 Move Right + Count Count houses until open 4 Stop at Open Door Reached start: count=4 count: 1 --> 2 --> 3 --> 4 FINAL RESULT 1 2 3 4 Output 4 OK - 4 houses found! Full circle completed Key Insight: By closing ALL doors first (k iterations), then opening only the starting door, we create a unique marker. Moving right and counting until we find an open door again gives us the exact house count. Time: O(k), Space: O(1). Works regardless of initial door states! TutorialsPoint - Count Houses in a Circular Street | Close All Then Count Approach
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