Skip to content
Related Articles

Related Articles

Count of triplets in Binary String such that Bitwise AND of S[i], S[j] and S[j], S[k] are same

View Discussion
Improve Article
Save Article
  • Last Updated : 05 May, 2022
View Discussion
Improve Article
Save Article

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>


Output

4

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>


Output

4

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


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!