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?- A. 16
- B. 20
- C. 30
- 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
- Problem: Sum (a[i] XOR a[j]) over all pairs i < j in O(n · bits): at bit b, a pair contributes 2^b exactly when one value has the bit and…
- Problem: Count triples (i, j, k) with i < j ≤ k such that XOR(a[i..j−1]) == XOR(a[j..k]). This holds iff XOR(a[i..k]) = 0, i.e. prefix[i]…
- Problem: Write an integer in base −2 (digits 0/1, place values 1, −2, 4, −8, …). When Python's divmod by −2 gives a negative remainder…
- Problem: Convert a fraction to a decimal string, putting a repeating part in parentheses: remember at which output position each remainder…
- Problem: Fibonacci numbers modulo m repeat with the Pisano period π(m). Use it to get F(10¹⁸) mod 10 without big loops. python def…
- Problem: Compute 3^(5^20) mod p for the prime p = 10⁹ + 7. By Fermat, exponents can be reduced modulo p − 1 (since gcd(3, p) = 1). Which…