Skip to main content

Count Ways To Build Good Strings - Solution & Explanation

MediumDynamic Programming16 min readAsked at: Amazon, Microsoft, Meta +5
Practice this problem

Problem Statement

Given the integers zero, one, low, and high, we can construct a string by starting with an empty string, and then at each step perform either of the following:

  • Append the character '0' zero times.
  • Append the character '1' one times.

This can be performed any number of times.

A good string is a string constructed by the above process having a length between low and high (inclusive).

Return the number of different good strings that can be constructed satisfying these properties. Since the answer can be large, return it modulo 109 + 7.

 

Example 1:

Input: low = 3, high = 3, zero = 1, one = 1
Output: 8
Explanation: 
One possible valid good string is "011". 
It can be constructed as follows: "" -> "0" -> "01" -> "011". 
All binary strings from "000" to "111" are good strings in this example.

Example 2:

Input: low = 2, high = 3, zero = 1, one = 2
Output: 5
Explanation: The good strings are "00", "11", "000", "110", and "011".

 

Constraints:

  • 1 <= low <= high <= 105
  • 1 <= zero, one <= low

Approach Overview

Problem Overview: You build binary strings by repeatedly appending blocks of size zero or one. A string is considered good if its final length lies between low and high. The task is to count how many such strings can be constructed. Since the count grows quickly, results are returned modulo 1e9 + 7.

Approach 1: Backtracking (Exponential Time)

This approach explores every possible construction path using recursion. Starting from length 0, recursively append a block of size zero or one and continue building the string. Whenever the current length falls within [low, high], increment the count. Recursion stops when the length exceeds high. This brute-force strategy tries all combinations, which leads to roughly O(2^(high / min(zero, one))) time complexity with O(high) recursion depth space. It demonstrates the problem structure but becomes impractical for large high.

Approach 2: Recursion with Memoization (Top-Down DP)

The repeated subproblem is the number of ways to build a valid string starting from a given length. Cache results for each length so the recursion does not recompute the same states. For a state len, the transitions are len + zero and len + one. Each state is solved once and stored in a memo table. This reduces the time complexity to O(high) with O(high) space for the cache and recursion stack. This version clearly shows the overlapping subproblems typical of dynamic programming and is easier to derive from the brute force recursion.

Approach 3: Bottom-Up Dynamic Programming (Optimal)

Instead of recursion, build the solution iteratively. Let dp[i] represent the number of ways to build a string of length i. Initialize dp[0] = 1 since an empty string is the starting state. For each length i from 1 to high, compute dp[i] by adding contributions from dp[i - zero] and dp[i - one] if those indices are valid. While filling the array, accumulate the answer whenever i lies between low and high. This runs in O(high) time with O(high) space. The iterative DP avoids recursion overhead and is the most common implementation in interviews. It is a classic counting pattern in dynamic programming and closely related to state-transition problems seen with memoization and recursion.

Recommended for interviews: The bottom-up dynamic programming approach is the expected solution. Interviewers want to see recognition of overlapping subproblems and a clean dp[i] state transition. Showing the backtracking idea first demonstrates understanding of the search space, but converting it into an O(high) DP solution shows strong algorithmic thinking.

Approach 1: Dynamic Programming Approach

We can solve this problem using a dynamic programming approach. The idea is to maintain a dp array where dp[i] represents the number of good strings of exact length i. Start with an empty string and attempt to form strings by appending '0's and '1's zero and one times respectively. For each length from low to high, we incrementally calculate the number of ways to achieve that length from smaller lengths and store them in dp[i].

The solution uses dynamic programming with an array dp where dp[i] stores the number of valid ways to form a string of length i. We start by initializing dp[0] to 1, which serves as our base case. From there, we loop through each length from 1 to high and calculate dp[i] as the sum of dp[i-zero] and dp[i-one], taking care to only add values when the indices are valid. Finally, we sum up all dp[i] from low to high to get our result.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(high)
Space Complexity: O(high)

Try this approach in the editor →

Approach 2: Backtracking Approach

In this approach, we explore every possible string configuration using backtracking to find strings whose lengths fall between low and high. We use recursion to build strings by appending zero or one '0's and '1's, tracking lengths and adding valid ones to a result set. Although not as efficient as the DP method due to exponential complexity, it serves as an insightful means to intuitively grasp the construction of such strings.

The backtracking solution in Python employs a recursive function to consider adding either zero or one characters to a string. It tracks the length of each created string and counts those which are valid. Once a length exceeds high, recursion stops further exploration from that branch.

Code

Python

Complexity

Time Complexity: O(2^n) where n is high / min(zero, one)
Space Complexity: O(n) because of the recursion stack

Try this approach in the editor →

Approach 3: Memoization Search

We design a function dfs(i) to represent the number of good strings constructed starting from the i-th position. The answer is dfs(0).

The computation process of the function dfs(i) is as follows:

  • If i > high, return 0;
  • If low leq i leq high, increment the answer by 1, then after i, we can add either zero number of 0s or one number of 1s. Therefore, the answer is incremented by dfs(i + zero) + dfs(i + one).

During the process, we need to take the modulus of the answer, and we can use memoization search to reduce redundant computations.

The time complexity is O(n), and the space complexity is O(n). Here, n = high.

Code

Python

Java

C++

Go

Try this approach in the editor →

Approach 4: Dynamic programming

Code

TypeScript

JavaScript

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Dynamic Programming Approach

Time Complexity: O(high)
Space Complexity: O(high)

Backtracking Approach

Time Complexity: O(2^n) where n is high / min(zero, one)
Space Complexity: O(n) because of the recursion stack

Memoization Search—
Dynamic programming—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
BacktrackingExponentialO(high)Useful for understanding the brute-force search tree and generating all possible constructions.
Recursion + MemoizationO(high)O(high)Good when deriving the DP from recursion and eliminating repeated subproblems.
Bottom-Up Dynamic ProgrammingO(high)O(high)Preferred interview solution. Iterative, simple state transitions, and no recursion overhead.

Video Solution

Count Ways to Build Good Strings - Leetcode 2466 - Python • NeetCodeIO • 11,113 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Count Ways To Build Good Strings easy or hard?
Count Ways To Build Good Strings is classified as Medium difficulty. The main challenge is recognizing the dynamic programming state transition and avoiding exponential recursion by storing results for each length.
Count Ways To Build Good Strings Python/Java solution
Both Python and Java implementations use the same DP idea. Create an array dp of size high + 1, initialize dp[0] = 1, and iteratively update dp[i] using dp[i - zero] and dp[i - one]. Add dp[i] to the result when i lies between low and high, applying modulo 1e9+7.
How to solve Count Ways To Build Good Strings in O(n)?
Treat each possible length as a DP state. Initialize dp[0] = 1 and iterate from 1 to high. For each i, add contributions from dp[i - zero] and dp[i - one] if those indices are valid. Sum dp[i] for all i in the range [low, high]. This produces an O(high) time solution.
What is the best approach for Count Ways To Build Good Strings?
The best approach is bottom-up dynamic programming. Define dp[i] as the number of ways to build a string of length i, then transition using dp[i - zero] and dp[i - one]. This computes all states up to high in O(high) time and O(high) space while accumulating valid lengths between low and high.
Is Count Ways To Build Good Strings asked at Google/Amazon/Meta?
This problem represents a common dynamic programming counting pattern frequently seen in interviews at large tech companies. Variations of length-based DP and state transitions appear in Google, Amazon, and Meta interview question sets.
What data structure is used in Count Ways To Build Good Strings?
The core data structure is a one-dimensional dynamic programming array where dp[i] stores the number of ways to construct a string of length i. Recursion with memoization may also use a hash map or array cache to store computed states.
What is the time complexity of Count Ways To Build Good Strings?
The optimal dynamic programming solution runs in O(high) time because each length from 1 to high is processed once. Space complexity is also O(high) for the DP array storing the number of ways to reach each length.

Ready to solve this problem?

Practice Count Ways To Build Good Strings with our built-in code editor and test cases.

Practice on FleetCode