Open In App

Maximum sum of lengths of a pair of strings with no common characters from a given array

Given an array arr[] consisting of N strings, the task is to find the maximum sum 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[] = [“abcd”, “cat”, “lto”, “car”, “wxyz”, “abcdef”]
Output: 8
Explanation:
The strings “abcd” and “wxyz” have no common characters in it. Therefore, the sum of the length of both the strings = 4 + 4 = 8, which is maximum among all possible pairs.

Input: arr[] = [“abcd”, “def”, “fghi”, “ijklm”]
Output: 8



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 sum 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 using the idea of Bit Manipulation. the idea is to convert each string into its bitmask integer equivalent and then find the pair of strings having no common characters having the maximum sum of their lengths. Follow the steps below to solve the problem:

Below is the implementation of the above approach:




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the maximum sum of
// length of pair of strings having
// no common characters
int maxSum(vector<string>& words)
{
    // Stores the bitmask of each strings
    vector<int> mask(words.size());
 
    // Initialize the result as zero
    int result = 0;
 
    // Iterate the given vector
    for (int i = 0; i < words.size(); ++i) {
 
        // For each of character
        for (char c : words[i]) {
 
            // If the ith value of
            // mask |= 1 left shift
            // that character - a
            mask[i] |= 1 << (c - 'a');
        }
 
        // Check for each ith character,
        // if the ith and jth value of
        // mask are not same, then add
        // and maximize them
        for (int j = 0; j < i; ++j) {
            if (!(mask[i] & mask[j])) {
                result
                    = max(result, int(words[i].size()
                                      + words[j].size()));
            }
        }
    }
 
    // Return maximum sum of lengths
    // of strings
    return result;
}
 
// Driver Code
int main()
{
    vector<string> words = { "abcd", "def",
                             "fghi", "ijklm" };
    cout << maxSum(words);
 
    return 0;
}




// Java program for the above approach
class GFG {
 
    // Function to find the maximum sum of
    // length of pair of strings having
    // no common characters
    public static int maxSum(String[] words) {
        // Stores the bitmask of each strings
        int[] mask = new int[words.length];
 
        // Initialize the result as zero
        int result = 0;
 
        // Iterate the given vector
        for (int i = 0; i < words.length; ++i) {
 
            // For each of character
            for (char c : words[i].toCharArray()) {
 
                // If the ith value of
                // mask |= 1 left shift
                // that character - a
                mask[i] |= 1 << (c - 'a');
            }
 
            // Check for each ith character,
            // if the ith and jth value of
            // mask are not same, then add
            // and maximize them
            for (int j = 0; j < i; ++j) {
                if ((mask[i] & mask[j]) < 1) {
                    result = Math.max(result, (int) words[i].length() + words[j].length());
                }
            }
        }
 
        // Return maximum sum of lengths
        // of strings
        return result;
    }
 
    // Driver Code
    public static void main(String args[]) {
        String[] words = { "abcd", "def", "fghi", "ijklm" };
        System.out.println(maxSum(words));
 
    }
}
 
// This code is contributed by saurabh_jaiswal.




# Function to find the maximum sum of
# length of pair of strings having
# no common characters
def maxSum(words):
   
    # Stores the bitmask of each strings
    mask = [0]*len(words)
     
    # Initialize the result as zero
    result = 0
     
        # Iterate the given vector
    for i in range(len(words)):
        for c in words[i]:
           
            # If the ith value of
            # mask |= 1 left shift
            # that character - a
            mask[i] |= 1 << (ord(c)-97)
             
         #  Check for each ith character,
        # if the ith and jth value of
        # mask are not same, then add
        # and maximize them
        for j in range(i):
            if not(mask[i] & mask[j]):
                result = max(result, len(words[i])+len(words[j]))
                 
     # Return maximum sum of lengths
    # of strings           
    return result
 
# Driver code
words = ["abcd", "def", "fghi", "ijklm"]
print(maxSum(words))
 
# This code is contributed by Parth Manchanda




using System;
 
public class GFG {
 
    public static int maxSum(String[] words)
    {
        // Stores the bitmask of each strings
        int[] mask = new int[words.Length];
 
        // Initialize the result as zero
        int result = 0;
 
        // Iterate the given vector
        for (int i = 0; i < words.Length; ++i) {
 
            // For each of character
            foreach  (char c in words[i]) {
               
                // If the ith value of
                // mask |= 1 left shift
                // that character - a
                mask[i] |= 1 << (c - 'a');
            }
 
            // Check for each ith character,
            // if the ith and jth value of
            // mask are not same, then add
            // and maximize them
            for (int j = 0; j < i; ++j) {
                if ((mask[i] & mask[j]) < 1) {
                    result = Math.Max(
                        result, (int)words[i].Length
                                    + words[j].Length);
                }
            }
        }
 
        // Return maximum sum of lengths
        // of strings
        return result;
    }
 
    static public void Main()
    {
        String[] words = { "abcd", "def", "fghi", "ijklm" };
        Console.WriteLine(maxSum(words));
    }
}
 
// This code is contributed by maddler.




<script>
 
// JavaScript program for the above approach
 
// Function to find the maximum sum of
// length of pair of strings having
// no common characters
function maxSum(words)
{
     
    // Stores the bitmask of each strings
    let mask = new Array(words.length);
 
    // Initialize the result as zero
    let result = 0;
 
    // Iterate the given vector
    for(let i = 0; i < words.length; ++i)
    {
         
        // For each of character
        for(let c = words[i]; c < words[i].length; c++)
        {
             
            // If the ith value of
            // mask |= 1 left shift
            // that character - a
            mask[i] |= 1 << (words[i].charCodeAt(0) -
                                  'a'.charCodeAt(0));
        }
 
        // Check for each ith character,
        // if the ith and jth value of
        // mask are not same, then add
        // and maximize them
        for(let j = 0; j < i; ++j)
        {
            if (!(mask[i] & mask[j]))
            {
                result = Math.max(result, words[i].length +
                                          words[j].length);
            }
        }
    }
 
    // Return maximum sum of lengths
    // of strings
    return result;
}
 
// Driver Code
let words = [ "abcd", "def",
              "fghi", "ijklm" ];
               
document.write(maxSum(words));
 
// This code is contributed by Potta Lokesh
 
</script>

Output: 
9

 

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

 


Article Tags :