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?- A. world
- B. banana
- C. apple
- 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
- Problem: s1[i] and s2[i] are declared equivalent letters (the relation is reflexive, symmetric and transitive). Replace every letter of…
- Problem: Find all roots that give a tree of minimum height, by repeatedly peeling off leaves. python def mht(n, edges): adj = [set() for…
- Problem: Build a Huffman code for symbol frequencies and report the total number of bits for the encoded message (Σ freq × code length)…
- Problem: Balloons span horizontal intervals [start, end]; an arrow shot at x bursts every balloon with start ≤ x ≤ end. Find the minimum…
- Problem: A knight walks from the top-left to the bottom-right cell moving only right or down; each cell adds its value to his health…
- Problem: Can s3 be formed by interleaving s1 and s2 (keeping each string's own order)? python def inter(s1, s2, s3): if len(s1) + len(s2)…