VOOZH about

URL: https://www.geeksforgeeks.org/dsa/bitwise-or-triplets-in-a-binary-string/

⇱ Bitwise OR Triplets in a Binary String - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Bitwise OR Triplets in a Binary String

Last Updated : 23 Jul, 2025

Given a binary string S of length N, where S[i] represents an integer value. the task is to count the number of ways to choose three different indices ( 0 <= i < j < k < N) such that the bitwise OR of the adjacent chosen element should be one (i.e, S[i] OR S[j] == 1 AND S[j] OR S[k] == 1).

Examples:

Input: S = "00110"
Output: 4
Explanation: Below are the different possible three indices:

  • indices {0, 2, 4} forms "010" such that S[0] | S[2] == 1 && S[2] | S[4] == 1
  • {0, 3, 4} forms "010"such that S[0] | S[3] == 1 && S[3] | S[4] == 1
  • {1, 2, 4} forms "010" such that S[1] | S[2] == 1 && S[2] | S[4] == 1
  • {1, 3, 4} forms "010" such that S[1] | S[3] == 1 && S[3] | S[4] == 1

Thus, there are 4 total ways.

Input: S = "11100"
Output: 0

Bitwise OR Triplets in a Binary String using PrefixSum Technique:

The idea is of Keep track of the number of zeros and ones on the left and right at any indices. At any index i, if the ith digit is zero then for this index we can select (number of ones on the left * number of ones on the right). Similarly, if the digit is 1, check for the 0s to the left and right. Keep adding the number of ways for every index in the result and finally return it.

Step-by-step approach:

  • Calculate the totalZero and totalOne in the binary string.
  • Initialize currZero and currOne to 0 to keep track of the number of zeros and ones until the current index i.
  • Initialize a variable result to keep track of the answer.
  • Iterate through the string:
    • If the current digit is '0':
      • Add the value of (number of ones to the left * number of ones to the right) to result.
      • Increment currZero by 1.
    • If the current digit is '1':
      • Add the value of (number of zeros to the left * number of zeros to the right) to result.
      • Increment currOne by 1.
  • Finally, return result as the answer.

Below is the implementation of the above approach:


Output
4

Time Complexity: O(N)
Auxiliary Space: O(1)

Comment