Number of Ways to Select Buildings - Problem
Building Selection Challenge
You are a city inspector tasked with selecting exactly 3 buildings for random inspection along a street. The street is represented by a binary string
โข
โข
To ensure variety in your inspections, no two consecutive buildings in your selection can be of the same type. This means you must select buildings that form an alternating pattern.
Valid patterns:
Invalid patterns:
Example: Given street
Goal: Return the total number of valid ways to select 3 buildings for inspection.
You are a city inspector tasked with selecting exactly 3 buildings for random inspection along a street. The street is represented by a binary string
s where:โข
'0' represents an office buildingโข
'1' represents a restaurantTo ensure variety in your inspections, no two consecutive buildings in your selection can be of the same type. This means you must select buildings that form an alternating pattern.
Valid patterns:
"010" or "101"Invalid patterns:
"000", "111", "001", "011", "100", "110"Example: Given street
s = "001101", you cannot select buildings at indices 1, 2, 4 (forming "011") because positions 1 and 2 are consecutive and both are '1'.Goal: Return the total number of valid ways to select 3 buildings for inspection.
Input & Output
example_1.py โ Basic Pattern
$
Input:
s = "001101"
โบ
Output:
6
๐ก Note:
Valid selections are: (0,2,4), (0,2,5), (0,3,4), (1,2,4), (1,2,5), (1,3,4). Each forms either '010' or '101' pattern.
example_2.py โ Simple Alternating
$
Input:
s = "101"
โบ
Output:
1
๐ก Note:
Only one way to select 3 buildings: positions (0,1,2) forming pattern '101'.
example_3.py โ All Same Type
$
Input:
s = "111"
โบ
Output:
0
๐ก Note:
No valid selections possible since all buildings are restaurants. Any selection would violate the alternating constraint.
Constraints
- 3 โค s.length โค 105
- s[i] is either '0' or '1'
- Must select exactly 3 buildings
- Selected buildings must form alternating pattern
Visualization
Tap to expand
Understanding the Visualization
1
Identify Valid Patterns
Only '010' and '101' patterns are valid
2
Choose Middle Building
Each middle building determines the required pattern type
3
Count Combinations
Multiply available buildings of the required type on left and right
Key Takeaway
๐ฏ Key Insight: By recognizing that only two patterns ('010' and '101') are valid and treating each position as a potential middle building, we can count all valid combinations mathematically without generating them explicitly.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code