Skip to content
Related Articles

Related Articles

Maximize product of lengths of strings having no common characters
  • Difficulty Level : Hard
  • Last Updated : 11 May, 2021

Given an array arr[] consisting of N strings, the task is to find the maximum product of length of the strings arr[i] and arr[j] for all unique pairs (i, j), where the strings arr[i] and arr[j] contains no common characters.

Examples: 

Input: arr[] = {“abcw”, “baz”, “foo”, “bar”, “xtfn”, “abcdef”}
Output: 16
Explanation: The strings “abcw” and “xtfn” have no common characters in it. Therefore, the product of the length of both the strings = 4 * 4 = 16, which is maximum among all possible pairs.

Input: arr[] = {“a”, “aa”, “aaa”, “aaaa”}
Output: 0

Naive Approach: The simplest approach to solve the given problem is to generate all possible pairs of the array of strings and print the maximum value of the product of the length of strings of pairs having no common characters between them



Time Complexity: O(N2 * M), where M is the maximum length of the string.
Auxiliary Space: O(M)

Efficient Approach: The above approach can also be optimized by converting each string into its bitmask integer equivalent. Follow the steps below to solve the problem:

  • Initialize a variable, say answer that stores the maximum product of the length of the pairs of strings having no common characters.
  • Initialize array bits[] that store the integer equivalents of all the given strings in the array arr[].
  • Traverse the array arr[] over the range [0, N – 1] and for each character ch in string arr[i] update bits[i] as the Bitwise OR of bits[i] and (1 << (arr[i] – ‘a’)).
  • Now, generate all possible pairs of the array bits[] and perform the following steps:
    • If the Bitwise AND of the bits[i] and bits[j] is 0, then update the value of answer as the maximum of answer and the product of the count of set bits in bits[i] and bits[j].
      Otherwise, check for the next possible pairs.
  • After completing the above steps, print the value of the answer as the resultant maximum product.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
 
using namespace std;
 
// Function to count the number
// of set bits in the integer n
int countSetBits(int n)
{
     
    // Stores the count
    // of set bits in n
    int count = 0;
 
    while (n > 0)
    {
        count += n & 1;
        n >>= 1;
    }
 
    // Return the count
    return count;
}
 
// Function to find the maximum
// product of pair of strings
// having no common characters
void maximumProduct(vector<string> words)
{
     
    // Stores the integer
    // equivalent of the strings
    vector<int> bits(words.size(), 0);
 
    // Traverse the array of strings
    for(int i = 0; i < words.size(); i++)
    {
         
        // Traverse the current string
        for(int j = 0; j < words[i].length(); j++)
        {
             
            // Store the current bit
            // position in bits[i]
            bits[i] = bits[i] | 1 << (words[i][j] - 'a');
        }
    }
 
    // Store the required result
    int result = 0;
 
    // Traverse the array, bits[]
    // to get all unique pairs (i, j)
    for(int i = 0; i < bits.size(); i++)
    {
        for(int j = i + 1; j < bits.size(); j++)
        {
             
            // Check whether the strings
            // have no common characters
            if ((bits[i] & bits[j]) == 0)
            {
                int L = countSetBits(bits[i]);
                int R = countSetBits(bits[j]);
 
                // Update the overall
                // maximum product
                result = max(L * R, result);
            }
        }
    }
 
    // Print the maximum product
    cout << result;
}
 
// Driver Code
int main()
{
    vector<string> arr = { "abcw", "baz", "foo",
                           "bar", "xtfn", "abcdef" };
    maximumProduct(arr);
 
    return 0;
}
 
// This code is contributed by Kingash

Java




// Java program for the above approach
 
import java.io.*;
 
class GFG {
 
    // Function to count the number
    // of set bits in the integer n
    public static int countSetBits(int n)
    {
        // Stores the count
        // of set bits in n
        int count = 0;
 
        while (n > 0) {
            count += n & 1;
            n >>= 1;
        }
 
        // Return the count
        return count;
    }
 
    // Function to find the maximum
    // product of pair of strings
    // having no common characters
    public static void maximumProduct(
        String[] words)
    {
        // Stores the integer
        // equivalent of the strings
        int[] bits = new int[words.length];
 
        // Traverse the array of strings
        for (int i = 0;
             i < words.length; i++) {
 
            // Traverse the current string
            for (int j = 0;
                 j < words[i].length();
                 j++) {
 
                // Store the current bit
                // position in bits[i]
                bits[i] = bits[i]
                          | 1 << (words[i].charAt(j)
                                  - 'a');
            }
        }
 
        // Store the required result
        int result = 0;
 
        // Traverse the array, bits[]
        // to get all unique pairs (i, j)
        for (int i = 0;
             i < bits.length; i++) {
 
            for (int j = i + 1;
                 j < bits.length; j++) {
 
                // Check whether the strings
                // have no common characters
                if ((bits[i] & bits[j]) == 0) {
 
                    int L = countSetBits(
                        bits[i]);
                    int R = countSetBits(
                        bits[j]);
 
                    // Update the overall
                    // maximum product
                    result
                        = Math.max(L * R, result);
                }
            }
        }
 
        // Print the maximum product
        System.out.println(result);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        String arr[] = { "abcw", "baz",
                         "foo", "bar",
                         "xtfn", "abcdef" };
        maximumProduct(arr);
    }
}

Python3




# Python3 program for the above approach
 
# Function to count the number
# of set bits in the integer n
def countSetBits(n):
     
    # Stores the count
    # of set bits in n
    count = 0
     
    while (n > 0):
        count += n & 1
        n >>= 1
 
    # Return the count
    return count
 
# Function to find the maximum
# product of pair of strings
# having no common characters
def maximumProduct(words):
     
    # Stores the integer
    # equivalent of the strings
    bits = [0 for i in range(len(words))]
 
    # Traverse the array of strings
    for i in range(len(words)):
         
        # Traverse the current string
        for j in range(len(words[i])):
 
            # Store the current bit
            # position in bits[i]
            bits[i] = bits[i] | 1 << (ord(words[i][j]) - 97)
 
    # Store the required result
    result = 0
 
    # Traverse the array, bits[]
    # to get all unique pairs (i, j)
    for i in range(len(bits)):
        for j in range(i + 1, len(bits)):
             
            # Check whether the strings
            # have no common characters
            if ((bits[i] & bits[j]) == 0):
                L = countSetBits(bits[i])
                R = countSetBits(bits[j])
 
                # Update the overall
                # maximum product
                result = max(L * R, result)
 
    # Print the maximum product
    print(result)
 
# Driver Code
if __name__ == '__main__':
     
    arr = [ "abcw", "baz", "foo",
            "bar", "xtfn", "abcdef" ]
    maximumProduct(arr)
 
# This code is contributed by ipg2016107

C#




// C# program for the above approach
using System;
public class GFG
{
   
        // Function to count the number
    // of set bits in the integer n
    public static int countSetBits(int n)
    {
       
        // Stores the count
        // of set bits in n
        int count = 0;
 
        while (n > 0) {
            count += n & 1;
            n >>= 1;
        }
 
        // Return the count
        return count;
    }
 
    // Function to find the maximum
    // product of pair of strings
    // having no common characters
    public static void maximumProduct(
        string[] words)
    {
       
        // Stores the integer
        // equivalent of the strings
        int[] bits = new int[words.Length];
 
        // Traverse the array of strings
        for (int i = 0;
             i < words.Length; i++)
        {
 
            // Traverse the current string
            for (int j = 0;
                 j < words[i].Length;
                 j++) {
 
                // Store the current bit
                // position in bits[i]
                bits[i] = bits[i]
                          | 1 << (words[i][j]
                                  - 'a');
            }
        }
 
        // Store the required result
        int result = 0;
 
        // Traverse the array, bits[]
        // to get all unique pairs (i, j)
        for (int i = 0;
             i < bits.Length; i++) {
 
            for (int j = i + 1;
                 j < bits.Length; j++) {
 
                // Check whether the strings
                // have no common characters
                if ((bits[i] & bits[j]) == 0) {
 
                    int L = countSetBits(
                        bits[i]);
                    int R = countSetBits(
                        bits[j]);
 
                    // Update the overall
                    // maximum product
                    result
                        = Math.Max(L * R, result);
                }
            }
        }
 
        // Print the maximum product
        Console.WriteLine(result);
    }
   
  // Driver code
    static public void Main (){
    string[] arr = { "abcw", "baz",
                         "foo", "bar",
                         "xtfn", "abcdef" };
        maximumProduct(arr);
    }
}
 
// This code is contributed by offbeat
Output: 
16

 

Time Complexity: O(N2), where M is the maximum length of the string.
Auxiliary Space: O(N)

My Personal Notes arrow_drop_up
Recommended Articles
Page :