LeetCode 318: Maximum Product of Word Lengths
LeetCode 318 Solution Explanation
Explanation
To solve this problem, we can use bit manipulation to represent the presence of letters in a word. We can convert each word into a 26-bit integer where each bit represents the presence of a letter from 'a' to 'z'. By doing this conversion for all words, we can compare each pair of words to check if they have any common letters.
- Convert each word into a 26-bit integer representation.
- Compare each pair of words to check if they have any common letters using bitwise AND operation.
- Calculate the product of the lengths of words that do not share common letters.
- Keep track of the maximum product found.
Time Complexity: O(n^2 * m), where n is the number of words and m is the average length of a word. Space Complexity: O(n)
LeetCode 318 Solutions in Java, C++, Python
class Solution {
public int maxProduct(String[] words) {
int n = words.length;
int[] wordBits = new int[n];
for (int i = 0; i < n; i++) {
for (char c : words[i].toCharArray()) {
wordBits[i] |= 1 << (c - 'a');
}
}
int maxProduct = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if ((wordBits[i] & wordBits[j]) == 0) {
maxProduct = Math.max(maxProduct, words[i].length() * words[j].length());
}
}
}
return maxProduct;
}
}
Interactive Code Editor for LeetCode 318
Improve Your LeetCode 318 Solution
Use the editor below to refine the provided solution for LeetCode 318. Select a programming language and try the following:
- Add import statements if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.
Loading editor...