Magicsheet logo

Number of Ways to Select Buildings

Medium
62.8%
Updated 6/1/2025

Number of Ways to Select Buildings

What is this problem about?

The Number of Ways to Select Buildings problem gives you a binary string representing buildings (0 or 1). Count the number of ways to select 3 buildings at indices i < j < k where no two adjacent selected buildings are of the same type — i.e., the sequence forms "010" or "101". This coding problem uses DP with prefix counts.

Why is this asked in interviews?

DE Shaw, Amazon, and Dream11 ask this to test efficient triplet counting with the "fix the middle element" technique using prefix sums. The string, dynamic programming, and prefix sum interview pattern is directly demonstrated.

Algorithmic pattern used

Fix middle element with prefix counts. For each middle position j with value v: count how many valid (i,k) pairs exist. For "010" pattern: j has value 0, count i<j with value 1, count k>j with value 1. For "101": j has value 1, count 0s on each side. Maintain prefix count of 0s and 1s seen so far. For suffix counts, precompute or maintain running counts from the right.

Two-pass approach: for each j, ways += (count of 1s before j) * (count of 1s after j) if s[j]='0', plus (count of 0s before j) * (count of 0s after j) if s[j]='1'.

Example explanation

s="001101". Pattern "010" or "101". Pre-compute suffix 0s and 1s. For each j:

  • j=2 (s[2]='1'): 0s before j=2, 0s after j (positions 3..5: "101"→ 0s=1). Contribution=2*1=2.
  • j=3 (s[3]='1'): 0s before=2, 0s after=1. Contribution=2*1=2.
  • j=4 (s[4]='0'): 1s before=2, 1s after=1. Contribution=2*1=2. ... sum all. Answer = 9 (example estimate).

Common mistakes candidates make

  • Using O(n³) brute force.
  • Not considering both "010" and "101" patterns.
  • Off-by-one in prefix/suffix count computation.
  • Recomputing suffix counts from scratch for each middle position.

Interview preparation tip

Triplet pattern counting (fix middle, multiply left/right counts) is a standard O(n) technique. Precompute prefix counts of 0s and 1s, and their suffix counterparts. For each middle position, the product of left-matching count and right-matching count gives the number of valid triplets with that middle. Practice "count subsequences of pattern XYX" using this fix-middle approach across various pattern types.

Similar Questions