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 office
  • s[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
Number of Ways to Select Buildings INPUT Binary String s = "001101" 0 1 2 3 4 5 0 0 1 1 0 1 0 = Office 1 = Restaurant Valid Patterns: "010" or "101" Goal: Count all ways to select 3 alternating buildings ALGORITHM STEPS 1 Track Counts Count 0s and 1s to left/right 2 Single Pass Iterate through string once 3 As Middle Building Each char as center of triplet 4 Multiply Counts left_opposite * right_opposite DP State Tracking: If s[i]='0': add left1s * right1s If s[i]='1': add left0s * right0s Example for i=4 (s[4]='0'): left1s=2, right1s=1 contributes: 2*1 = 2 ways FINAL RESULT 3 Valid Selections Found: 1. 0 1 0 idx: 0,2,4 2. 0 1 0 idx: 1,2,4 3. 1 0 1 idx: 2,4,5 Output: 3 OK - All patterns are alternating (010 or 101) Key Insight: For each building at index i, treat it as the MIDDLE of a valid triplet. If it's a '0', count 1s on the left multiplied by 1s on the right (to form "101"). Similarly for '1'. This DP approach achieves O(n) time complexity with a single pass through the string. TutorialsPoint - Number of Ways to Select Buildings | Dynamic Programming - Single Pass
Asked in
Google 15 Amazon 12 Microsoft 8
23.5K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen