Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Maximum length product of unique words in JavaScript
We need to find two strings from an array that share no common characters and have the maximum product of their lengths. This problem efficiently uses bitwise operations to represent character sets.
Problem Statement
Given an array of lowercase strings, find two strings with no common characters that have the maximum length product. Return 0 if no such pair exists.
For example:
const arr = ["karl", "n", "the", "car", "mint", "alpha"]; // Expected output: 20 (mint: 4 chars × alpha: 5 chars = 20)
How It Works
The solution uses bit manipulation to represent each string's character set as a bitmask. Each bit position represents a letter (a=0, b=1, etc.). Two strings share no common characters if their bitwise AND equals 0.
Example Implementation
const arr = ["karl", "n", "the", "car", "mint", "alpha"];
const maxLengthProduct = (arr = []) => {
const array = [];
// Convert each string to bitmask
arr.forEach(str => {
let curr = 0;
for(let i = 0; i < str.length; i++){
curr |= 1 << (str.charCodeAt(i) - 97);
};
array.push(curr);
});
let res = 0;
// Check all pairs for no common characters
for(let i = 0; i < array.length; i++) {
for(let j = i + 1; j < array.length; j++) {
if((array[i] & array[j]) === 0) {
res = Math.max(res, arr[i].length * arr[j].length);
}
}
}
return res;
};
console.log(maxLengthProduct(arr));
20
Step-by-Step Breakdown
Step 1: Convert strings to bitmasks using 1
Step 2: Check each pair using bitwise AND - if result is 0, no common characters exist
Step 3: Track maximum length product among valid pairs
Key Points
- Time complexity: O(n² + m) where n is array length, m is total characters
- Bitwise operations make character comparison very efficient
- Only works with lowercase English letters (26 bits max)
- Returns 0 when no valid pairs exist
Conclusion
This solution elegantly uses bitmasks to represent character sets, making pair comparison O(1). The bitwise AND operation efficiently determines if two strings share common characters.
