Skip to content

2728. Count Houses in a Circular Street 👍

  • 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
/**
 * Definition for a street.
 * class Street {
 *  public:
 *   Street(vector<int> doors);
 *   void openDoor();
 *   void closeDoor();
 *   bool isDoorOpen();
 *   void moveRight();
 *   void moveLeft();
 * };
 */

class Solution {
 public:
  int houseCount(Street* street, int k) {
    for (int i = 0; i < k; ++i) {
      if (street->isDoorOpen())
        street->closeDoor();
      street->moveRight();
    }

    for (int ans = 0;; ++ans) {
      if (street->isDoorOpen())
        return ans;
      street->openDoor();
      street->moveRight();
    }

    throw;
  }
};
 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
/**
 * Definition for a street.
 * class Street {
 *   public Street(int[] doors);
 *   public void openDoor();
 *   public void closeDoor();
 *   public boolean isDoorOpen();
 *   public void moveRight();
 *   public void moveLeft();
 * }
 */

class Solution {
  public int houseCount(Street street, int k) {
    for (int i = 0; i < k; ++i) {
      if (street.isDoorOpen())
        street.closeDoor();
      street.moveRight();
    }

    for (int ans = 0;; ++ans) {
      if (street.isDoorOpen())
        return ans;
      street.openDoor();
      street.moveRight();
    }
  }
}
 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
# Definition for a street.
# class Street:
#   def openDoor(self):
#     pass
#   def closeDoor(self):
#     pass
#   def isDoorOpen(self):
#     pass
#   def moveRight(self):
#     pass
#   def moveLeft(self):
#     pass

class Solution:
  def houseCount(self, street: Optional['Street'], k: int) -> int:
    for _ in range(k):
      if street.isDoorOpen():
        street.closeDoor()
      street.moveRight()

    for ans in range(k + 1):
      if street.isDoorOpen():
        return ans
      street.openDoor()
      street.moveRight()