![]() |
VOOZH | about |
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
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:
Below is the implementation of the above approach:
4
Time Complexity: O(N)
Auxiliary Space: O(1)