VOOZH about

URL: https://www.geeksforgeeks.org/dsa/cses-solutions-bit-strings/

⇱ CSES Solutions - Bit Strings - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

CSES Solutions - Bit Strings

Last Updated : 23 Jul, 2025

Your task is to calculate the number of bit strings of length N. For example, if N=3, the correct answer is 8, because the possible bit strings are 000, 001, 010, 011, 100, 101, 110, and 111. Print the result modulo 109+7.

Examples:

Input: N = 2
Output: 4
Explanation: There are total 4 bit strings possible of length 2: 00, 01, 10 and 11.

Input: N = 10
Output: 1024
Explanation: There are total 1024 bit strings possible of length 10.

Approach: To solve the problem, follow the below idea:

We need to construct a string of length N where each character can either be a '0' or a '1'. So, for every index we have 2 choices and in total we have N characters so the number of bit strings that can be formed using N bits will be 2 ^ N. So, we can find the answer by computing (2 ^ N) % (109+7). This can be calculated using Binary Exponentiation.

Step-by-step algorithm:

  • Maintain a function, say power(base, expo) to calculate (base ^ power) % mod.
  • Return power(2, N) as the final answer.

Below is the implementation of algorithm:


Output
32

Time Complexity: O(logN), where N is the length of string we need to construct.
Auxiliary Space: O(1)

Comment
Article Tags: