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 s where:

โ€ข '0' represents an office building
โ€ข '1' represents a restaurant

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: "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
Building Selection: Pattern RecognitionValid Pattern: 0100Office1Restaurant0OfficeDifferent โ†’ Same โ†’ DifferentValid Pattern: 1011Restaurant0Office1RestaurantDifferent โ†’ Same โ†’ DifferentAlgorithm Strategy1. For each building position i, consider it as the middle building2. If s[i] = '1': count zeros on left ร— zeros on right (for '010' pattern)3. If s[i] = '0': count ones on left ร— ones on right (for '101' pattern)โšก Time: O(n) | Space: O(1)Optimal solution using mathematical combinatorics
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.
Asked in
Amazon 45 Microsoft 32 Google 28 Meta 22
62.4K Views
Medium Frequency
~15 min Avg. Time
2.8K 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