Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
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.
Example 1:
Input: words = ["abcw","baz","foo","bar","xtfn","abcdef"] Output: 16 Explanation: The two words can be "abcw", "xtfn".
Example 2:
Input: words = ["a","ab","abc","d","cd","bcd","abcd"] Output: 4 Explanation: The two words can be "ab", "cd".
Example 3:
Input: words = ["a","aa","aaa","aaaa"] Output: 0 Explanation: No such pair of words.
Constraints:
2 <= words.length <= 10001 <= words[i].length <= 1000words[i] consists only of lowercase English letters.Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Bit Manipulation
["abcw","baz","foo","bar","xtfn","abcdef"]
["a","ab","abc","d","cd","bcd","abcd"]
["a","aa","aaa","aaaa"]
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #318: Maximum Product of Word Lengths
class Solution {
public int maxProduct(String[] words) {
int n = words.length;
int[] mask = new int[n];
int ans = 0;
for (int i = 0; i < n; ++i) {
for (char c : words[i].toCharArray()) {
mask[i] |= 1 << (c - 'a');
}
for (int j = 0; j < i; ++j) {
if ((mask[i] & mask[j]) == 0) {
ans = Math.max(ans, words[i].length() * words[j].length());
}
}
}
return ans;
}
}
// Accepted solution for LeetCode #318: Maximum Product of Word Lengths
func maxProduct(words []string) (ans int) {
n := len(words)
mask := make([]int, n)
for i, s := range words {
for _, c := range s {
mask[i] |= 1 << (c - 'a')
}
for j, t := range words[:i] {
if mask[i]&mask[j] == 0 {
ans = max(ans, len(s)*len(t))
}
}
}
return
}
# Accepted solution for LeetCode #318: Maximum Product of Word Lengths
class Solution:
def maxProduct(self, words: List[str]) -> int:
mask = [0] * len(words)
ans = 0
for i, s in enumerate(words):
for c in s:
mask[i] |= 1 << (ord(c) - ord("a"))
for j, t in enumerate(words[:i]):
if (mask[i] & mask[j]) == 0:
ans = max(ans, len(s) * len(t))
return ans
// Accepted solution for LeetCode #318: Maximum Product of Word Lengths
struct Solution;
use std::collections::HashMap;
impl Solution {
fn max_product(words: Vec<String>) -> i32 {
let mut hm: HashMap<u32, usize> = HashMap::new();
for word in words {
let mut mask: u32 = 0;
for c in word.bytes() {
mask |= 1 << (c - b'a');
}
let size = hm.entry(mask).or_default();
*size = word.len().max(*size);
}
let mut res = 0;
for (&ka, &va) in &hm {
for (&kb, &vb) in &hm {
if ka & kb == 0 {
res = res.max(va * vb);
}
}
}
res as i32
}
}
#[test]
fn test() {
let words = vec_string!["abcw", "baz", "foo", "bar", "xtfn", "abcdef"];
let res = 16;
assert_eq!(Solution::max_product(words), res);
let words = vec_string!["a", "ab", "abc", "d", "cd", "bcd", "abcd"];
let res = 4;
assert_eq!(Solution::max_product(words), res);
let words = vec_string!["a", "aa", "aaa", "aaaa"];
let res = 0;
assert_eq!(Solution::max_product(words), res);
}
// Accepted solution for LeetCode #318: Maximum Product of Word Lengths
function maxProduct(words: string[]): number {
const n = words.length;
const mask: number[] = Array(n).fill(0);
let ans = 0;
for (let i = 0; i < n; ++i) {
for (const c of words[i]) {
mask[i] |= 1 << (c.charCodeAt(0) - 'a'.charCodeAt(0));
}
for (let j = 0; j < i; ++j) {
if ((mask[i] & mask[j]) === 0) {
ans = Math.max(ans, words[i].length * words[j].length);
}
}
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Sort the array in O(n log n), then scan for the missing or unique element by comparing adjacent pairs. Sorting requires O(n) auxiliary space (or O(1) with in-place sort but O(n log n) time remains). The sort step dominates.
Bitwise operations (AND, OR, XOR, shifts) are O(1) per operation on fixed-width integers. A single pass through the input with bit operations gives O(n) time. The key insight: XOR of a number with itself is 0, which eliminates duplicates without extra space.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.