Maximum Product of Word Lengths - Problem

Given an array of unique strings, find the maximum product of lengths of two words that share no common letters.

Your task is to identify pairs of words where:

  • No character appears in both words
  • The product of their lengths is maximized

For example, given ["abcw", "baz", "foo", "bar", "xtfn", "abcdef"], the words "abcw" and "xtfn" share no common letters, so their product is 4 ร— 4 = 16.

If no such pair exists, return 0.

Input & Output

example_1.py โ€” Basic Case
$ Input: ["abcw", "baz", "foo", "bar", "xtfn", "abcdef"]
โ€บ Output: 16
๐Ÿ’ก Note: The two words "abcw" and "xtfn" share no common letters, and their length product is 4 ร— 4 = 16, which is the maximum possible.
example_2.py โ€” No Valid Pairs
$ Input: ["a", "aa", "aaa", "aaaa"]
โ€บ Output: 0
๐Ÿ’ก Note: All words contain the letter 'a', so no two words can be found that don't share common letters.
example_3.py โ€” Single Characters
$ Input: ["a", "b", "c", "d"]
โ€บ Output: 1
๐Ÿ’ก Note: Any two single-character words with different letters will work. The maximum product is 1 ร— 1 = 1.

Constraints

  • 2 โ‰ค words.length โ‰ค 1000
  • 1 โ‰ค words[i].length โ‰ค 1000
  • words[i] consists only of lowercase English letters
  • All strings in words are unique

Visualization

Tap to expand
๐Ÿ•ต๏ธ Secret Agent Codebook MatchingAgent A"abcw"4 lettersAgent B"baz"3 lettersAgent C"xtfn"4 lettersโŒ Common: a,bโœ… No overlap!Mission Capacity: 4 ร— 4 = 16Bitmask TechniqueAgent A: "abcw" โ†’ Bitmask: 00001111 (bits 0,1,2,22)Agent C: "xtfn" โ†’ Bitmask: 10101000 (bits 5,13,19,23)Bitwise AND: 00001111 & 10101000 = 00000000Result = 0 means no common letters! โœ…O(1) compatibility check vs O(k) set intersection!
Understanding the Visualization
1
Agent Recruitment
Each agent brings a codebook with unique letters
2
Compatibility Check
Two agents are compatible if their alphabets don't overlap
3
Mission Capacity
Mission success depends on total vocabulary size (product of lengths)
4
Optimal Pairing
Find the compatible pair with maximum combined capacity
Key Takeaway
๐ŸŽฏ Key Insight: Bitmasks transform character set comparisons from O(k) set operations to O(1) bitwise operations, making pair checking extremely efficient for small alphabets.
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 25
42.5K Views
Medium Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen