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.
Input: arr = [“abcd”, “cat”, “lto”, “car”, “wxyz”, “abcdef”]
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”]
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:
Time Complexity: O(max(N*M, N2)), where M is the maximum length of the string.
Auxiliary Space: O(N)