Monday, September 23, 2024
Google search engine
HomeData Modelling & AITotal character pairs from two strings, with equal number of set bits...

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

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 character have the same number of set bits. Print the total number of such pairs.

Examples:

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 = “neveropen”, s2 = “forneveropen” 
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 arr1[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 = "neveropen";
    string s2 = "forneveropen";
    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 = "neveropen";
        String s2 = "forneveropen";
        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 = "neveropen";
    s2 = "forneveropen";
    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 = "neveropen";
    string s2 = "forneveropen";
    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 = "neveropen";
      var s2 = "forneveropen";
      document.write(totalPairs(s1, s2));
    </script>


Output: 

17

 

Time Complexity: O(32 * (n1 + n2)), where n1 and n2 are the length of the given two strings.
Auxiliary Space: O(1), no extra space is required, so it is a constant.

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments