Number of Ways to Select Buildings - Problem
You are given a 0-indexed binary string s which represents the types of buildings along a street where:
s[i] = '0'denotes that the ith building is an offices[i] = '1'denotes that the ith building 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 = "001101", we cannot select the 1st, 3rd, and 5th buildings as that would form "011" which is not allowed due to having two consecutive buildings of the same type.
Return the number of valid ways to select 3 buildings.
Input & Output
Example 1 — Basic Case
$
Input:
s = "001101"
›
Output:
3
💡 Note:
Valid selections: indices (0,2,4) forming "010", indices (0,2,5) forming "010", and indices (1,2,4) forming "010". All three are alternating patterns.
Example 2 — All Same Type
$
Input:
s = "11111"
›
Output:
0
💡 Note:
No valid selections possible since all buildings are restaurants (type 1), so any selection would have consecutive buildings of the same type.
Example 3 — Minimum Length
$
Input:
s = "010"
›
Output:
1
💡 Note:
Only one way to select 3 buildings from 3 total: indices (0,1,2) forming "010" which is a valid alternating pattern.
Constraints
- 3 ≤ s.length ≤ 105
- s[i] is either '0' or '1'
Visualization
Tap to expand
Understanding the Visualization
1
Input String
Binary string representing building types (0=office, 1=restaurant)
2
Valid Patterns
Find all subsequences of length 3 with alternating types
3
Count Result
Total number of valid 010 and 101 patterns
Key Takeaway
🎯 Key Insight: Only patterns 010 and 101 are valid - count them efficiently using dynamic programming
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code