Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Total character pairs from two strings, with equal number of set bits in their ascii value

  • Difficulty Level : Easy
  • Last Updated : 14 May, 2021

Given two strings s1 and s2. The task is to take one character from the first string and one character from the second string and check if the ASCII values of both the character have the same number of set bits. Print the total number of such pairs.

Examples:

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Input: s1 = “xcd”, s2 = “swa” 
Output:
Only valid pair is (d, a) with ASCII values as 100 and 97 respectively. 
Both of which contains 3 set bits.
Input: s1 = “geeks”, s2 = “forgeeks” 
Output: 17 



Approach: 

  • Make two arrays arr1 and arr2 of size 6 with all values initialized to 0 to store the frequency of the number of set bits. Since the maximum number of set bits in lower case alphabets is 6.
  • Traverse the string s1, and find the ASCII value of each character. Store the frequency of the number of set bits of each ASCII value in an array arr1. (For example, if there are 3 characters with 4 set bits, then store 3 at arr[4])
  • Do a similar operation for string s2 and store its value in another array arr2.
  • Initialize a count variable with 0.
  • For total number of pairs, keep on adding (arr1[i] * arr2[i]) in count variable for all valid values of i.

Below is the implementation of the above approach: 

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the count of valid pairs
int totalPairs(string s1, string s2)
{
    int count = 0;
 
    int arr1[7], arr2[7];
 
    // Initialise both arrays with 0
    for (int i = 1; i <= 6; i++) {
        arr1[i] = 0;
        arr2[i] = 0;
    }
 
    // Store frequency of number of set bits for s1
    for (int i = 0; i < s1.length(); i++) {
        int set_bits = __builtin_popcount((int)s1[i]);
        arr1[set_bits]++;
    }
 
    // Store frequency of number of set bits for s2
    for (int i = 0; i < s2.length(); i++) {
        int set_bits = __builtin_popcount((int)s2[i]);
        arr2[set_bits]++;
    }
 
    // Calculate total pairs
    for (int i = 1; i <= 6; i++)
        count += (arr1[i] * arr2[i]);
 
    // Return the count of valid pairs
    return count;
}
 
// Driver code
int main()
{
    string s1 = "geeks";
    string s2 = "forgeeks";
    cout << totalPairs(s1, s2);
 
    return 0;
}

Java




// Java implementation of the approach
class GFG
{
 
    // Function to return the count of valid pairs
    static int totalPairs(String s1, String s2)
    {
        int count = 0;
 
        int[] arr1 = new int[7];
        int[] arr2 = new int[7];
 
        // Default Initialise both arrays 0
        // Store frequency of number of set bits for s1
        for (int i = 0; i < s1.length(); i++)
        {
            int set_bits = Integer.bitCount(s1.charAt(i));
            arr1[set_bits]++;
        }
 
        // Store frequency of number of set bits for s2
        for (int i = 0; i < s2.length(); i++)
        {
            int set_bits = Integer.bitCount(s2.charAt(i));
            arr2[set_bits]++;
        }
 
        // Calculate total pairs
        for (int i = 1; i <= 6; i++)
        {
            count += (arr1[i] * arr2[i]);
        }
 
        // Return the count of valid pairs
        return count;
    }
 
    // Driver code
    public static void main(String[] args)
    {
 
        String s1 = "geeks";
        String s2 = "forgeeks";
        System.out.println(totalPairs(s1, s2));
    }
}
 
// This code has been contributed by 29AjayKumar

Python3




# Python3 implementation of the approach
 
# Function to get no of set bits in binary
# representation of positive integer n
def countSetBits(n):
    count = 0
    while (n):
        count += n & 1
        n >>= 1
    return count
     
# Function to return the count
# of valid pairs
def totalPairs(s1, s2) :
     
    count = 0;
 
    arr1 = [0] * 7; arr2 = [0] * 7;
 
    # Store frequency of number
    # of set bits for s1
    for i in range(len(s1)) :
        set_bits = countSetBits(ord(s1[i]))
        arr1[set_bits] += 1;
     
    # Store frequency of number of
    # set bits for s2
    for i in range(len(s2)) :
        set_bits = countSetBits(ord(s2[i]));
        arr2[set_bits] += 1;
 
    # Calculate total pairs
    for i in range(1, 7) :
        count += (arr1[i] * arr2[i]);
 
    # Return the count of valid pairs
    return count;
 
# Driver code
if __name__ == "__main__" :
 
    s1 = "geeks";
    s2 = "forgeeks";
    print(totalPairs(s1, s2));
 
# This code is contributed by Ryuga

C#




// C# implementation of the approach
using System;
using System.Linq;
 
class GFG
{
     
// Function to return the count of valid pairs
static int totalPairs(string s1, string s2)
{
    int count = 0;
 
    int[] arr1 = new int[7];
    int[] arr2 = new int[7];
 
    // Default Initialise both arrays 0
 
    // Store frequency of number of set bits for s1
    for (int i = 0; i < s1.Length; i++)
    {
        int set_bits = Convert.ToString((int)s1[i], 2).Count(c => c == '1');
        arr1[set_bits]++;
    }
 
    // Store frequency of number of set bits for s2
    for (int i = 0; i < s2.Length; i++)
    {
        int set_bits = Convert.ToString((int)s2[i], 2).Count(c => c == '1');
        arr2[set_bits]++;
    }
 
    // Calculate total pairs
    for (int i = 1; i <= 6; i++)
        count += (arr1[i] * arr2[i]);
 
    // Return the count of valid pairs
    return count;
}
 
// Driver code
static void Main()
{
    string s1 = "geeks";
    string s2 = "forgeeks";
    Console.WriteLine(totalPairs(s1, s2));
}
}
 
// This code is contributed by chandan_jnu

Javascript




<script>
      // JavaScript implementation of the approach
      // Function to get no of set bits in binary
      // representation of positive integer n
      function countSetBits(n) {
        var count = 0;
        while (n) {
          count += n & 1;
          n >>= 1;
        }
        return count;
      }
 
      // Function to return the count
      // of valid pairs
      function totalPairs(s1, s2) {
        var count = 0;
 
        var arr1 = new Array(7).fill(0);
        var arr2 = new Array(7).fill(0);
 
        // Store frequency of number
        // of set bits for s1
        for (let i = 0; i < s1.length; i++) {
          set_bits = countSetBits(s1[i].charCodeAt(0));
          arr1[set_bits] += 1;
        }
        // Store frequency of number of
        // set bits for s2
        for (let i = 0; i < s2.length; i++) {
          set_bits = countSetBits(s2[i].charCodeAt(0));
          arr2[set_bits] += 1;
        }
        // Calculate total pairs
        for (let i = 1; i < 7; i++) {
          count += arr1[i] * arr2[i];
        }
 
        // Return the count of valid pairs
        return count;
      }
      // Driver code
      var s1 = "geeks";
      var s2 = "forgeeks";
      document.write(totalPairs(s1, s2));
    </script>
Output: 
17

 




My Personal Notes arrow_drop_up
Recommended Articles
Page :