Count of triplets in Binary String such that Bitwise AND of S[i], S[j] and S[j], S[k] are same
Last Updated :
23 Jul, 2025
Given a binary string S of length N, consisting of 0s and 1s. The task is to count the number of triplet (i, j, k) such that S[i] & S[j] = S[j] & S[k], where 0 ≤ i < j < k < N and & denotes bitwise AND operator.
Examples:
Input: N = 4, S = “0010”
Output: 4
Explanation: Following are 4 triplets which satisfy the condition S[i] & S[j] = S[j] & S[k]
(0, 1, 2) because 0 & 0 = 0 & 1,
(0, 1, 3) because 0 & 0 = 0 & 0,
(0, 2, 3) because 0 & 1 = 1 & 0,
(1, 2, 3) because 0 & 1 = 1 & 0.
Input: N = 5, S = "00101"
Output: 8
Explanation: 8 triplets satisfying the above condition are :
(0, 1, 2) because 0 & 0 = 0 & 1.
(0, 1, 3) because 0 & 0 = 0 & 0.
(0, 1, 4) because 0 & 0 = 0 & 1.
(0, 2, 3) because 0 & 1 = 1 & 0.
(1, 2, 3) because 0 & 1 = 1 & 0.
(0, 3, 4) because 0 & 0 = 0 & 1.
(1, 3, 4) because 0 & 0 = 0 & 1.
(2, 3, 4) because 1 & 0 = 0 & 1.
Naive Approach: The easiest way to solve the problem is to:
Generate all possible triplets and check if S[i] & S[j] = S[j] & S[k].
Follow the below steps to solve this problem:
- Declare and initialize a variable ans to 0 to store the total count.
- Now, there is a need of three nested loops to iterate over all the triplets.
- The first loop iterates over the index i, the second over index j starting from i+1, and the third over index k starting from j+1.
- Now, check the condition S[i] & S[j] = S[j] & S[k] is true or not. If true, the increment the ans by 1.
- Return the total count of triplets.
Below is the implementation of the above approach :
C++
// C++ program for above approach
#include <bits/stdc++.h>
using namespace std;
// Function to count total number of triplets
int countTriplets(int n, string& s)
{
// Stores the count of triplets.
int ans = 0;
// Iterate over all the triplets.
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
for (int k = j + 1; k < n; ++k) {
// Extract integer from 'S[i]',
// 'S[j]', 'S[k]'.
int x = s[i] - '0';
int y = s[j] - '0',
z = s[k] - '0';
// If condition 'S[i]' & 'S[j]'
// == 'S[j]' &'S[k]' is true,
// increment 'ans'.
if ((x & y) == (y & z)) {
ans++;
}
}
}
}
// Return the answer
return ans;
}
// Driver code
int main()
{
int N = 4;
string S = "0010";
// Function call
cout << countTriplets(N, S);
return 0;
}
Java
// JAVA program for above approach
import java.util.*;
class GFG {
// Function to count total number of triplets
public static int countTriplets(int n, String s)
{
// Stores the count of triplets.
int ans = 0;
// Iterate over all the triplets.
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
for (int k = j + 1; k < n; ++k) {
// Extract integer from 'S[i]',
// 'S[j]', 'S[k]'.
int x = s.charAt(i);
int y = s.charAt(j), z = s.charAt(k);
// If condition 'S[i]' & 'S[j]'
// == 'S[j]' &'S[k]' is true,
// increment 'ans'.
if ((x & y) == (y & z)) {
ans++;
}
}
}
}
// Return the answer
return ans;
}
// Driver code
public static void main(String[] args)
{
int N = 4;
String S = "0010";
// Function call
System.out.print(countTriplets(N, S));
}
}
// This code is contributed by Taranpreet
Python3
# Python3 program for above approach
# Function to count total number of triplets
def countTriplets(n, s):
# Stores the count of triplets.
ans = 0
# Iterate over all the triplets.
for i in range(n):
for j in range(i + 1, n):
for k in range(j + 1, n):
# Extract integer from 'S[i]', S[j], S[k]
x = ord(S[i]) - ord("0")
y = ord(S[j]) - ord("0")
z = ord(S[k]) - ord("0")
# If condition 'S[i]' & 'S[j]'
# == S[j]' & 'S[k]'
# is true, increment ans
if (x & y) == (y & z):
ans += 1
# return the answer
return ans
# Driver code
N = 4
S = "0010"
# function call
print(countTriplets(N, S))
# This code is contributed by hrithikgarg03188.
C#
// C# program for above approach
using System;
public class GFG{
// Function to count total number of triplets
static int countTriplets(int n, string s)
{
// Stores the count of triplets.
int ans = 0;
// Iterate over all the triplets.
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
for (int k = j + 1; k < n; ++k) {
// Extract integer from 'S[i]',
// 'S[j]', 'S[k]'.
int x = s[i];
int y = s[j], z = s[k];
// If condition 'S[i]' & 'S[j]'
// == 'S[j]' &'S[k]' is true,
// increment 'ans'.
if ((x & y) == (y & z)) {
ans++;
}
}
}
}
// Return the answer
return ans;
}
// Driver code
static public void Main ()
{
int N = 4;
string S = "0010";
// Function call
Console.Write(countTriplets(N, S));
}
}
// This code is contributed by hrithikgarg03188.
JavaScript
<script>
// JavaScript program for above approach
// Function to count total number of triplets
const countTriplets = (n, s) => {
// Stores the count of triplets.
let ans = 0;
// Iterate over all the triplets.
for (let i = 0; i < n; ++i) {
for (let j = i + 1; j < n; ++j) {
for (let k = j + 1; k < n; ++k) {
// Extract integer from 'S[i]',
// 'S[j]', 'S[k]'.
let x = s.charCodeAt(i) - '0'.charCodeAt(0);
let y = s.charCodeAt(j) - '0'.charCodeAt(0),
z = s.charCodeAt(k) - '0'.charCodeAt(0);
// If condition 'S[i]' & 'S[j]'
// == 'S[j]' &'S[k]' is true,
// increment 'ans'.
if ((x & y) == (y & z)) {
ans++;
}
}
}
}
// Return the answer
return ans;
}
// Driver code
let N = 4;
let S = "0010";
// Function call
document.write(countTriplets(N, S));
// This code is contributed by rakeshsahni
</script>
Time Complexity: O(N3)
Auxiliary Space: O(1)
Efficient Approach: The idea to solve the problem efficiently is based on the following observations:
Observations:
- Since S[i] ∈ {0, 1}, there can be only 8 possible distinct triplets. Let’s analyze how many of these actually satisfy the condition S[i] & S[j] == S[j] & S[k].
S[i] | S[j] | S[k] | S[i]&S[j]==S[j]&S[k] |
0 | 0 | 0 | 1 |
0 | 0 | 1 | 1 |
0 | 1 | 0 | 1 |
0 | 1 | 1 | 0 |
1 | 0 | 0 | 1 |
1 | 0 | 1 | 1 |
1 | 1 | 0 | 0 |
1 | 1 | 1 | 1 |
- After analyzing the truth table, observe that whenever S[j] == ‘0’, the condition is always satisfied. Also, when S[j] == ‘1’, then both S[i] and S[k] should be the same.
- Thus, iterate over all the S[j] values, and depending on the value of S[j], simply count the number of triplets.
- If S[j] == ‘0’, then S[i] and S[k] can be anything, So total possible ways of choosing any i and k is j * (N - j - 1).
- Otherwise, if S[j] == ‘1’, then S[i] and S[k] should be same. So only 0s can make pair with 0s and 1s with 1s. Say there was x1 0s in prefix and x2 0s in suffix and y1 and y2 1s in prefix and suffix. Then total possible pairs are x1*x2 + y1*y2
Follow the below steps to solve this problem:
- Declare a variable (say ans) to store the count of triplets and initialize it to 0.
- Create a prefix array pre and a suffix array suf. These two arrays store the number of zeros in the prefix and suffix of the array.
- For building prefix array, iterate from 0 to N - 1:
- If S[i] == '0', then pre[i] = pre[i - 1] + 1.
- If S[i]== '1', then pre[i] = pre[i - 1].
- For building suffix array, iterate from N - 1 to 0:
- If S[i] == '0', then suf[i] = suf[i + 1] + 1.
- If S[i] == '1', then suf[i] = suf[i + 1].
- Now iterate again, from 1 to N - 2 (we are iterating for S[j]):
- If S[j] == '0', then add j * (N - j - 1) to ans variable as per the observation.
- If S[j] == '1', then add ‘pre[j - 1]’ * ‘suf[j + 1]’ + (j - ‘pre[j - 1]’) * (N - j - 1 - ‘suf[j + 1]’) to ans as per the above observation.
- Now return the ans variable as that contains the final count of triplets.
Below is the implementation of the above approach :
C++
// C++ program for above approach
#include <bits/stdc++.h>
using namespace std;
// Function to count number of triplets
int countTriplets(int n, string& s)
{
// Stores the count of triplets.
int ans = 0;
// 'pre[i]', 'suf[i]', stores the
// number of zeroes in
// the prefix and suffix
vector<int> pre(n), suf(n);
// Build the prefix array
for (int i = 0; i < n; ++i) {
pre[i] = (i == 0 ? 0 : pre[i - 1])
+ (s[i] == '0');
}
// Build the suffix array.
for (int i = n - 1; i >= 0; --i) {
suf[i]
= (i == n - 1 ? 0 : suf[i + 1])
+ (s[i] == '0');
}
// Iterate over the middle index
// of the triplet.
for (int j = 1; j < n - 1; ++j) {
// If 'S[j]' == '0'
if (s[j] == '0') {
ans += j * (n - j - 1);
}
else {
// If 'S[j]' == '1'
ans += pre[j - 1] * suf[j + 1]
+ (j - pre[j - 1])
* (n - j - 1 - suf[j + 1]);
}
}
// Return the answer.
return ans;
}
// Driver code
int main()
{
int N = 4;
string S = "0010";
// Function call
cout << countTriplets(N, S);
return 0;
}
Java
// Java program for above approach
public class GFG {
// Function to count number of triplets
static int countTriplets(int n, String s)
{
// Stores the count of triplets.
int ans = 0;
// 'pre[i]', 'suf[i]', stores the
// number of zeroes in
// the prefix and suffix
int[] pre = new int[n];
int[] suf = new int[n];
// Build the prefix array
for (int i = 0; i < n; ++i) {
pre[i] = (i == 0 ? 0 : pre[i - 1])
+ ('1' - s.charAt(i));
}
// Build the suffix array.
for (int i = n - 1; i >= 0; --i) {
suf[i] = (i == n - 1 ? 0 : suf[i + 1])
+ ('1' - s.charAt(i));
}
// Iterate over the middle index
// of the triplet.
for (int j = 1; j < n - 1; ++j) {
// If 'S[j]' == '0'
if (s.charAt(j) == '0') {
ans += j * (n - j - 1);
}
else {
// If 'S[j]' == '1'
ans += pre[j - 1] * suf[j + 1]
+ (j - pre[j - 1])
* (n - j - 1 - suf[j + 1]);
}
}
// Return the answer.
return ans;
}
// Driver Code
public static void main(String[] args)
{
int N = 4;
String S = "0010";
// Function call
System.out.println(countTriplets(N, S));
}
}
// This code is contributed by phasing17
Python3
# Python3 program for above approach
# Function to count total number of triplets
def countTriplets(n, s):
# Stores the count of triplets.
ans = 0
# 'pre[i]', 'suf[i]', stores the
# number of zeroes in
# the prefix and suffix
pre = [0]*n
suf = [0]*n
# Build the prefix array
for i in range(0,n):
pre[i] = (0 if i == 0 else pre[i - 1]) + (s[i] == '0')
# Build the suffix array
for i in range(n-1,-1,-1):
suf[i] = (0 if i == n - 1 else suf[i + 1]) + (s[i] == '0')
# Iterate over the middle index
# of the triplet.
for j in range(1,n):
# If 'S[j]' == '0'
if (s[j] == '0'):
ans += j * (n - j - 1)
else :
# If 'S[j]' == '1'
ans = ans+ pre[j - 1] * suf[j + 1] + (j - pre[j - 1]) * (n - j - 1 - suf[j + 1])
# Return the answer.
return ans
# Driver code
N = 4
S = "0010"
# function call
print(countTriplets(N, S))
# This code is contributed by Pushpesh Raj
C#
// C# code to implement the above approach
using System;
class GFG
{
// Function to count number of triplets
static int countTriplets(int n, string s)
{
// Stores the count of triplets.
int ans = 0;
// 'pre[i]', 'suf[i]', stores the
// number of zeroes in
// the prefix and suffix
int[] pre = new int[n];
int[] suf = new int[n];
// Build the prefix array
for (int i = 0; i < n; ++i) {
pre[i] = (i == 0 ? 0 : pre[i - 1])
+ ('1' - s[i]);
}
// Build the suffix array.
for (int i = n - 1; i >= 0; --i) {
suf[i] = (i == n - 1 ? 0 : suf[i + 1])
+ ('1' - s[i]);
}
// Iterate over the middle index
// of the triplet.
for (int j = 1; j < n - 1; ++j) {
// If 'S[j]' == '0'
if (s[j] == '0') {
ans += j * (n - j - 1);
}
else {
// If 'S[j]' == '1'
ans += pre[j - 1] * suf[j + 1]
+ (j - pre[j - 1])
* (n - j - 1 - suf[j + 1]);
}
}
// Return the answer.
return ans;
}
// Driver code
public static void Main()
{
int N = 4;
string S = "0010";
// Function call
Console.Write(countTriplets(N, S));
}
}
// This code is contributed by sanjoy_62.
JavaScript
<script>
// JavaScript code for the above approach
function countTriplets(n, s)
{
// Stores the count of triplets.
let ans = 0;
// 'pre[i]', 'suf[i]', stores the
// number of zeroes in
// the prefix and suffix
let pre = new Array(n);
let suf = new Array(n);
// Build the prefix array
for (let i = 0; i < n; ++i) {
pre[i] = (i == 0 ? 0 : pre[i - 1])
+ ('1' - s[i]);
}
// Build the suffix array.
for (let i = n - 1; i >= 0; --i) {
suf[i] = (i == n - 1 ? 0 : suf[i + 1])
+ ('1' - s[i]);
}
// Iterate over the middle index
// of the triplet.
for (let j = 1; j < n - 1; ++j) {
// If 'S[j]' == '0'
if (s[j] == '0') {
ans += j * (n - j - 1);
}
else {
// If 'S[j]' == '1'
ans += pre[j - 1] * suf[j + 1]
+ (j - pre[j - 1])
* (n - j - 1 - suf[j + 1]);
}
}
// Return the answer.
return ans;
}
// Driver Code
let N = 4;
let S = "0010";
// Function call
document.write(countTriplets(N, S));
// This code is contributed by sanjoy_62.
</script>
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem