Data Structures & AlgorithmsVery hardProduct Company SDE · Amazon/Microsoft-style OA
Problem: Return the alien-dictionary letter order from a sorted list of words (Kahn's algorithm, ties alphabetical).
Problem: Return the alien-dictionary letter order from a sorted list of words (Kahn's algorithm, ties alphabetical).
import heapq
def alien(words):
letters = sorted(set(''.join(words)))
adj = {c: set() for c in letters}; indeg = {c: 0 for c in letters}
for a, b in zip(words, words[1:]):
for x, y in zip(a, b):
if x != y:
if y not in adj[x]: adj[x].add(y); indeg[y] += 1
break
else:
if len(a) > len(b): return ''
h = [c for c in letters if indeg[c] == 0]; heapq.heapify(h); out = ''
while h:
c = heapq.heappop(h); out += c
for d in sorted(adj[c]):
indeg[d] -= 1
if indeg[d] == 0: heapq.heappush(h, d)
return out if len(out) == len(letters) else ''
print(alien(["wrt", "wrf", "er", "ett", "rftt"]), repr(alien(["abc", "ab"])))What is printed?- A. wertf ''
- B. wertf 'abc'
- C. werft ''
- D. fwert ''
Correct answer: A. wertf ''
Each adjacent pair of words gives one constraint from its first differing letter: t < f, w < e, r < t, e < r. Topological order: w, e, r, t, f. If a longer word comes before its own prefix ("abc" before "ab"), the input is invalid → ''. O(total characters).
More Coding Interview Problems questions
- Problem: Count how many nodes are 'safe' (every path from them ends at a terminal node) in a directed graph. python def safe(g): color =…
- Problem: Find the minimum effort path in a grid where effort is the maximum absolute height difference between consecutive cells. python…
- Problem: Return the number of steps to reach the exit of a maze grid ('.' open, '+' wall) from an entrance, where an exit is an open…
- Problem: Count paths modulo 10⁹ + 7 from the top-left to the bottom-right of a 3 × 3 board whose centre is blocked, moving right, down or…
- Problem: Find the maximum number of points you can collect in a grid going right/down from top-left to bottom-right and then reconstruct…
- Problem: n ≤ 10⁵ tasks with durations and deadlines; complete as many tasks as possible, one at a time, each finishing by its deadline…