Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Find the maximum product len(w1) · len(w2) over pairs of words that share no letter, using a 26-bit letter mask per word.

Problem: Find the maximum product len(w1) · len(w2) over pairs of words that share no letter, using a 26-bit letter mask per word.
def max_prod(words):
    masks = [sum(1 << (ord(c) - 97) for c in set(w)) for w in words]
    best = 0
    for i in range(len(words)):
        for j in range(i + 1, len(words)):
            if masks[i] & masks[j] == 0: best = max(best, len(words[i]) * len(words[j]))
    return best
print(max_prod(["graph", "tree", "heap", "stack", "queue", "trie"]))
What is printed?
  1. A. 16
  2. B. 20
  3. C. 30
  4. D. 25

Correct answer: D. 25

Two words share no letter iff their masks AND to 0 – an O(1) test instead of comparing letters. "stack" × "queue" and "graph" × "queue" are disjoint 5 × 5 pairs → 25; pairs such as "graph"/"stack" share 'a'. set(w) avoids adding a repeated letter's bit twice (which would corrupt the mask via carries). O(n² + total length).

More Coding Interview Problems questions

Exams that ask this topic