Skip to content

2753. Count Houses in a Circular Street II 👍

  • Time: $O(k)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
 * Definition for a street.
 * class Street {
 *  public:
 *   Street(vector<int> doors);
 *   void closeDoor();
 *   bool isDoorOpen();
 *   void moveRight();
 * };
 */
class Solution {
 public:
  int houseCount(Street* street, int k) {
    int ans = 0;

    // Go to the first open door.
    while (!street->isDoorOpen())
      street->moveRight();

    street->moveRight();

    for (int count = 1; count <= k; ++count) {
      // Each time we encounter an open door, there's a possibility that it's
      // the first open door we intentionally left open.
      if (street->isDoorOpen()) {
        ans = count;
        street->closeDoor();
      }
      street->moveRight();
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/**
 * Definition for a street.
 * class Street {
 *   public Street(int[] doors);
 *   public void closeDoor();
 *   public boolean isDoorOpen();
 *   public void moveRight();
 * }
 */
class Solution {
  public int houseCount(Street street, int k) {
    int ans = 0;

    // Go to the first open door.
    while (!street.isDoorOpen())
      street.moveRight();

    street.moveRight();

    for (int count = 1; count <= k; ++count) {
      // Each time we encounter an open door, there's a possibility that it's
      // the first open door we intentionally left open.
      if (street.isDoorOpen()) {
        ans = count;
        street.closeDoor();
      }
      street.moveRight();
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# Definition for a street.
# class Street:
#   def closeDoor(self):
#     pass
#   def isDoorOpen(self):
#     pass
#   def moveRight(self):
#     pass
class Solution:
  def houseCount(self, street: Optional['Street'], k: int) -> int:
    ans = 0

    # Go to the first open door.
    while not street.isDoorOpen():
      street.moveRight()

    street.moveRight()

    for count in range(k):
      # Each time we encounter an open door, there's a possibility that it's the
      # first open door we intentionally left open.
      if street.isDoorOpen():
        ans = count + 1
        street.closeDoor()
      street.moveRight()

    return ans