Open In App

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

Last Updated : 18 Feb, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  • Initialize a vector mask of size N to store the bitwise OR of a string in the array of strings words[].
  • Initialize the variable maxLength as 0 to store the answer.
  • Iterate over the range [0, N] using the variable i and performing the following tasks:
    • Iterate over the range [0, M] where M is the length of the string using the variable j and set the value of mask[i] as mask[i]|1<<(words[i][j] – ‘a’).
    • Iterate over the range [0, i] using the variable j and if the value bitwise AND of mask[i] and mask[j] is not 0, then set the value of maxLength as the maximum of maxLength or words[i].length() + words[j].length().
  • After completing the above steps, print the value of the maxLength as the result.

Below is the implementation of the above approach:

C++




// 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




// 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.


Python3




# 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


C#




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.


Javascript




<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)

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads