Problem
Given a string array words
, return the maximum value of length(word[i]) * length(word[j])
where the two words do not share common letters. If no such two words exist, return 0
.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Constraints
2 <= words.length <= 1000
1 <= words[i].length <= 1000
words[i]
consists only of lowercase English letters.
Solution
Method 1 - Using Hashset and Intersection
Here is the approach:
- Create Sets for Each Word:
- For each word in the input list, create a set of its characters. This will help in quickly checking for common characters between words.
- Compare Each Pair of Words:
- Iterate through all possible pairs of words. For each pair, check if the two sets of characters have any intersection.
- If the sets are disjoint (no common characters), calculate the product of the lengths of these two words.
- Track the Maximum Product:
- Keep track of the maximum product found during the comparisons.
- Return the maximum product as the result.
But the above solution now gives TLE.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n^2 * m)
, wheren
is the number of words andm
is the average length of the words. This accounts for creating sets and checking for common characters. - 🧺 Space complexity:
O(n * m)
, for storing the sets of characters for each word.
Method 2 - Convert String to Binary Representation Based on Prescence of Char
Since the string contains only lowercase characters from a
to z
, we can convert the string to a binary representation. If a character like a
is present, we set the 0th bit from the right, and if z
is present, we set the 25th bit from the right. We can use an integer for this representation.
To set the bit, we use the operation: arr[i] |= (1 << (c - 'a'));
For example:
|
|
We can then use the and operator
&
to check if two words share common letters.
Approach
- Binary Representation of Words:
- Convert each word into a binary representation where each bit represents the presence of a specific character.
- Setting Bits:
- For each character in the word, set the corresponding bit in an integer.
- Calculate Maximum Product:
- Use nested loops to compare the binary representations of all pairs of words.
- If two words do not share any characters (checked using the
&
operator), calculate their product and update the maximum product if necessary.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n^2 * m)
, wheren
is the number of words andm
is the average length of the words. This accounts for converting each word to a binary representation and comparing all pairs of words. - 🧺 Space complexity:
O(n)
, for storing the binary representations of the words.