CodeArchon

hardAdvanced GraphsFacebookGoogleAmazon

Lexicon Ordering

Linguists infer a lost alphabet's letter order by comparing adjacent words sorted in that unknown alphabet.

Given a list of words sorted lexicographically in an alien alphabet, return a string containing the alphabet's letters in order. Return '' if impossible.

Choose approach

e
f
r
t
w
cur
1/6
Narrationstep 1 of 6

Peel 'w' (zero in-degree). Order so far: "w".

1from collections import deque, defaultdict
2def alienOrder(words):
3 indeg = {c: 0 for w in words for c in w}
4 adj = defaultdict(set)
5 for a, b in zip(words, words[1:]):
6 if len(a) > len(b) and a.startswith(b): return ""
7 for x, y in zip(a, b):
8 if x != y:
9 if y not in adj[x]:
10 adj[x].add(y); indeg[y] += 1
11 break
12 q = deque(c for c, d in indeg.items() if d == 0)
13 out = []
14 while q:
15 c = q.popleft(); out.append(c)
16 for n in adj[c]:
17 indeg[n] -= 1
18 if indeg[n] == 0: q.append(n)
19 return ''.join(out) if len(out) == len(indeg) else ""
Variables
c=w
order=w

How to think about it

  1. Only the FIRST differing character per adjacent pair is an informative constraint.
  2. A prefix inconsistency (longer word before its prefix) is invalid.
  3. Topological sort yields any valid order; cycle -> ''.

Edge cases to catch in interview

  • Single word -> any permutation of its chars.
  • Prefix violation -> ''.

Examples

Example 1"wertf"
{"words":["wrt","wrf","er","ett","rftt"]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed