Given a string array words, return the maximum value oflength(word[i]) * length(word[j])where the two words do not share common letters. If no such two words exist, return 0.
publicintmaxProduct(String[] words) {
List<Set<Character>> listOfSet =new ArrayList<>();
for (int i = 0; i < words.length; i++) {
String word = words[i];
Set<Character> set =new HashSet<>();
for (char c: word.toCharArray()) {
set.add(c);
}
listOfSet.add(set);//added at ith index }
int max = 0;
for (int i = 0; i < words.length; i++) {
for (int j = i + 1; j < words.length; j++) {
Set<Character> intersection =new HashSet<>(listOfSet.get(j));
intersection.retainAll(listOfSet.get(i));
if (intersection.isEmpty()) {
max = Math.max(max, words[i].length() * words[j].length());
}
}
}
return max;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
classSolution:
defmaxProduct(self, words: List[str]) -> int:
list_of_sets: List[Set[str]] = []
# Create list of sets for each wordfor word in words:
char_set = set(word)
list_of_sets.append(char_set)
max_product =0# Compare each pair of wordsfor i in range(len(words)):
for j in range(i +1, len(words)):
if list_of_sets[i].isdisjoint(list_of_sets[j]):
max_product = max(max_product, len(words[i]) * len(words[j]))
return max_product
⏰ Time complexity: O(n^2 * m), where n is the number of words and m 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:
1
2
3
4
5
6
7
// a 1 -> 1
// b 2 -> 10
// c 4 -> 100
// ab 3 -> 11
// ac 5 -> 101
// abc 7 -> 111
// az 33554433 -> 10000000000000000000000001
We can then use the and operator& to check if two words share common letters.
classSolution:
defmaxProduct(self, words: List[str]) -> int:
ifnot words:
return0 n = len(words)
arr = [0] * n
# Convert each word to its binary representationfor i in range(n):
for char in words[i]:
arr[i] |=1<< (ord(char) - ord('a'))
max_product =0# Compare all pairs to find the max productfor i in range(n):
for j in range(i +1, n):
if arr[i] & arr[j] ==0:
max_product = max(max_product, len(words[i]) * len(words[j]))
return max_product
⏰ Time complexity: O(n^2 * m), where n is the number of words and m 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.