Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: Return the longest word that can be built one letter at a time from other words in the list (every prefix must be present); ties go to the lexicographically smaller word.

Problem: Return the longest word that can be built one letter at a time from other words in the list (every prefix must be present); ties go to the lexicographically smaller word.
def longest(words):
    S, best = set(words), ""
    for w in words:
        if all(w[:k] in S for k in range(1, len(w))):
            if len(w) > len(best) or (len(w) == len(best) and w < best):
                best = w
    return best
print(longest(["w", "wo", "wor", "worl", "world", "b", "ba", "ban", "bana", "banan", "banana", "apple", "appl"]))
What is printed?
  1. A. world
  2. B. banana
  3. C. apple
  4. D. banan

Correct answer: B. banana

'banana' has every prefix b, ba, ban, bana, banan in the list and is longer than 'world'. 'apple' fails because a, ap and app are missing even though 'appl' is present.

More Coding Interview Problems questions

Exams that ask this topic