Start learning free

LESSON 338 OF 410 · DYNAMIC PROGRAMMING

Binary Strings Without Consecutive Ones in Python (Time Complexity: O(N))

Practice O(n) Read the full explanation

Given a non-negative integer N return the number of binary strings of length N without 2 consecutive ones

Example:

Input: N = 3
Output: 5
Explanation: [
    "000",
    "001",
    "010",
    "100",
    "101",
]
Notes: N <= 30
STEP 1 OF 5
    Ctrl + Enter to check

    PYTHON · DYNAMIC PROGRAMMING

    Binary Strings Without Consecutive Ones in Python, explained

    Understanding the Problem

    The core challenge of this problem is to generate binary strings of a given length N such that no two consecutive '1's appear in the string. This problem has applications in coding theory, data transmission, and error detection where certain patterns need to be avoided.

    Potential pitfalls include misunderstanding the constraints and generating strings that do not meet the criteria.

    Approach

    To solve this problem, we can use dynamic programming. The idea is to build the solution for length N based on the solutions for smaller lengths.

    Let's define two arrays:

    • dp0[i]: Number of binary strings of length i ending with '0' without consecutive '1's.
    • dp1[i]: Number of binary strings of length i ending with '1' without consecutive '1's.

    The total number of valid binary strings of length i is the sum of dp0[i] and dp1[i].

    Initial Naive Solution

    A naive solution would involve generating all possible binary strings of length N and then filtering out those with consecutive '1's. This approach is not optimal due to its exponential time complexity.

    Optimized Solution

    Using dynamic programming, we can achieve a linear time complexity solution. The recurrence relations are:

    • dp0[i] = dp0[i-1] + dp1[i-1]: A string ending in '0' can be formed by appending '0' to any string of length i-1.
    • dp1[i] = dp0[i-1]: A string ending in '1' can only be formed by appending '1' to a string of length i-1 that ends in '0'.

    Algorithm

    1. Initialize dp0[1] and dp1[1] to 1, as there are two valid strings of length 1: "0" and "1".

    2. Iterate from 2 to N and fill the dp0 and dp1 arrays using the recurrence relations.

    3. The result is the sum of dp0[N] and dp1[N].

    Code Implementation

    def count_binary_strings(N):
        # Base cases
        if N == 0:
            return 1
        if N == 1:
            return 2
        
        # Initialize dp arrays
        dp0 = [0] * (N + 1)
        dp1 = [0] * (N + 1)
        
        # Base cases for dp arrays
        dp0[1] = 1
        dp1[1] = 1
        
        # Fill dp arrays using the recurrence relations
        for i in range(2, N + 1):
            dp0[i] = dp0[i - 1] + dp1[i - 1]
            dp1[i] = dp0[i - 1]
        
        # The result is the sum of dp0[N] and dp1[N]
        return dp0[N] + dp1[N]
    
    # Example usage
    N = 3
    print(count_binary_strings(N))  # Output: 5
    

    Complexity Analysis

    The time complexity of this approach is O(N) because we iterate from 2 to N once. The space complexity is also O(N) due to the storage of the dp0 and dp1 arrays.

    Edge Cases

    Consider the following edge cases:

    • N = 0: The output should be 1 (an empty string).
    • N = 1: The output should be 2 ("0" and "1").

    Testing

    To test the solution comprehensively, consider a variety of test cases:

    • Simple cases: N = 0, N = 1
    • Small cases: N = 2, N = 3
    • Edge cases: N = 30 (upper limit)

    Thinking and Problem-Solving Tips

    When approaching such problems:

    • Break down the problem into smaller subproblems.
    • Look for patterns and recurrence relations.
    • Consider dynamic programming for optimization.
    • Practice similar problems to improve problem-solving skills.

    Conclusion

    Understanding and solving problems like this one is crucial for developing strong algorithmic thinking. Practice and exploration of different approaches can significantly enhance problem-solving skills.

    Additional Resources

    For further reading and practice:

    Keep going with PythonAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free