#2222

Number of Ways to Select Buildings

Medium
StringDynamic ProgrammingPrefix SumDynamic ProgrammingPrefix Sum
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach involves counting the valid '01' and '10' pairs in the string and using these counts to calculate the total combinations. This reduces the problem to linear time complexity.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize two arrays to count the number of '01' and '10' pairs up to each index.
  2. 2Step 2: Traverse the string to fill these arrays based on the current and previous characters.
  3. 3Step 3: For each '0' found, add the count of '10' pairs that can be formed with '0' as the last building.
  4. 4Step 4: For each '1' found, add the count of '01' pairs that can be formed with '1' as the last building.
solution.py24 lines
1# Full working Python code
2
3def countWays(s):
4    n = len(s)
5    count01 = [0] * n
6    count10 = [0] * n
7    count = 0
8
9    for i in range(1, n):
10        count01[i] = count01[i - 1]
11        count10[i] = count10[i - 1]
12        if s[i - 1:i + 1] == '01':
13            count01[i] += 1
14        elif s[i - 1:i + 1] == '10':
15            count10[i] += 1
16
17    for i in range(n):
18        if s[i] == '0':
19            count += count10[i]
20        elif s[i] == '1':
21            count += count01[i]
22
23    return count
24

Complexity note: This complexity is linear because we only traverse the string a couple of times, making it efficient for larger inputs.

  • 1The problem can be simplified by focusing on the patterns of '01' and '10'.
  • 2Counting valid pairs allows us to avoid the inefficiencies of checking every combination.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.