Number of Ways to Select Buildings Problem
Description
LeetCode Problem 2222.
You are given a 0-indexed binary string s which represents the types of buildings along a street where:
s[i] = '0'denotes that thei^thbuilding is an office ands[i] = '1'denotes that thei^thbuilding is a restaurant.
As a city official, you would like to select 3 buildings for random inspection. However, to ensure variety, no two consecutive buildings out of the selected buildings can be of the same type.
- For example, given
s = "0**0**1**1**0**1**", we cannot select the1^st,3^rd, and5^thbuildings as that would form"0**11**"which is not allowed due to having two consecutive buildings of the same type.
Return the number of valid ways to select 3 buildings.
Example 1:
Input: s = "001101"
Output: 6
Explanation:
The following sets of indices selected are valid:
- [0,2,4] from "001101" forms "010"
- [0,3,4] from "001101" forms "010"
- [1,2,4] from "001101" forms "010"
- [1,3,4] from "001101" forms "010"
- [2,4,5] from "001101" forms "101"
- [3,4,5] from "001101" forms "101"
No other selection is valid. Thus, there are 6 total ways.
Example 2:
Input: s = "11100"
Output: 0
Explanation: It can be shown that there are no valid selections.
Constraints:
3 <= s.length <= 10^5s[i]is either'0'or'1'.
Solution
Approach: Count Around the Middle Building
A valid selection is three buildings with no two adjacent chosen ones of the same type, so the types must alternate: 010 or 101. Fix the middle building of type x; the left one and the right one must both have type x ^ 1. The number of choices is therefore (count of type x ^ 1 on the left) × (count of type x ^ 1 on the right).
Keep the counts l for the buildings already passed and r for those still ahead, update them as the middle building moves, and sum the products.
Complexity: O(n) time and O(1) extra space.
class Solution:
def numberOfWays(self, s: str) -> int:
l = [0, 0]
r = [s.count("0"), s.count("1")]
ans = 0
for x in map(int, s):
r[x] -= 1
ans += l[x ^ 1] * r[x ^ 1]
l[x] += 1
return ans