VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-valid-bitwise-operation-combinations-for-binary-strings/

⇱ Count valid Bitwise operation combinations for Binary Strings - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count valid Bitwise operation combinations for Binary Strings

Last Updated : 23 Jul, 2025

Given an odd integer N (N >= 3), a binary stringS of length N and another string O of length (N-1)/2. Here, each character in string O can be one of the following: '&', '|' or '^' representing Bitwise operationsAND OR, and XOR respectively, the task is to find the number of possible combinations for string O that satisfies the following conditions:

  • S[2] = S[0] O[0] S[1]
  • S[4] = S[2] O[1] S[3]
  • S[6] = S[4] O[2] S[5]
  • And so on, up to the last valid index of S.

Note: Output can be very large so modulo it by (10^9 + 7).

Examples:

Input: "110"
Output: 1
Explanation: The only operation string that satisfies the conditions is "^". S[0] ^ S[1] = S[2], that is 1 ^ 1 = 0

Input: "10101"
Output: 4
Explanation: There can be four possible strings. They are:

  • "^^" : S[0] ^ S[1] = S[2], that is 1 ^ 0 = 1 and S[2] ^ S[3] = S[4], that is 1 ^ 0 = 1
  • "^|" : S[0] ^ S[1] = S[2], that is 1 ^ 0 = 1 and S[2] | S[3] = S[4], that is 1 | 0 = 1
  • "|^" : S[0] | S[1] = S[2], that is 1 | 0 = 1 and S[2] ^ S[3] = S[4], that is 1 ^ 0 = 1
  • "||" : S[0] | S[1] = S[2], that is 1 | 0 = 1 and S[2] | S[3] = S[4], that is 1 | 0 = 1

Approach: To solve the problem follow the below idea:

The problem can be solved by using a combination based approach where at every index i (i >= 2 and i is odd), we multiply our answer with the number of possible operators which we can use between S[i-2] and S[i-1] to get S[i]. Suppose, if at any index i, the possible operators are '^' and '&', then we multiply our answer with 2 and so on.

Below are the steps to solve the problem:

  • Initialize a variable ans = 1 to store the number of possible strings for O.
  • Iterate over the string S starting from index i = 2.
    • Maintain a variable cnt = 0, to count the number of possible operators for that index.
    • Check if we can use Bitwise AND for this iteration. If yes, increment cnt by 1.
    • Check if we can use Bitwise OR for this iteration. If yes, increment cnt by 1.
    • Check if we can use Bitwise XOR for this iteration. If yes, increment cnt by 1.
    • Multiply ans by cnt.
    • Increment index i by 2.
  • Return ans to get the number of all possible combinations for string O.

Below is the implementation for the above approach:


Output
1
4

Time Complexity: O(N), where N is the length of string S.
Auxiliary Space: O(1)

Comment