Skip to content
mlmentorship

Infer only forced character precedences, then order the graph

Use adjacent words' first differences, reject invalid prefixes and cycles, then report ambiguity or validate a proposed alphabet.

Published · 17 min read ·Specialist ·Advanced

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Infer only forced character precedences, then order the graph

Explain the mechanism, why it works, when it fails, and one alternative.

Problem

Input. A list of words sorted lexicographically under an unknown alphabet. Output. Return a string containing every observed character exactly once in a compatible alphabet order. Rules. At the first unequal character, the earlier word's character must come earlier in the alphabet. A word precedes any longer word that has it as a prefix. Return any compatible order if several exist, or "" if no order exists. An empty word list also returns "". Leave the words unchanged. Example. ["wrt", "wrf", "er", "ett", "rftt"] permits "wertf". ["abc", "ab"] returns "": a longer word cannot precede its own prefix.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

Use the first difference of each adjacent word pair as a directed edge, then emit zero-indegree letters with Kahn topological sorting.

Problem trace

Only the first unequal letters establish each ordering rule

Worked example: only the first unequal character creates an ordering edgeThe words wrt and wrf first differ at their third character. Infer t before f; the shared prefix supplies no new edge.Shared prefix columns supply noordering edgewrtwrfOnly the first unequal pair becomes tbefore ftf
Read it this way: The words wrt and wrf first differ at their third character. Infer t before f; the shared prefix supplies no new edge. Would a later mismatch supply a second edge after the first unequal character already decides this word pair?
Full interview answer 17 min read

Infer a possible alphabet from words already sorted under an unknown character order.

Problem

Input. A list of words sorted lexicographically under an unknown alphabet.

Output. Return a string containing every observed character exactly once in a compatible alphabet order.

Rules. At the first unequal character, the earlier word’s character must come earlier in the alphabet. A word precedes any longer word that has it as a prefix. Return any compatible order if several exist, or "" if no order exists. An empty word list also returns "". Leave the words unchanged.

Example. ["wrt", "wrf", "er", "ett", "rftt"] permits "wertf". ["abc", "ab"] returns "": a longer word cannot precede its own prefix.

Picture

Lexicographic comparison stops at the first difference. Record that one necessary directed edge; ignore later positions. If no difference exists, the longer word cannot precede its exact prefix. Include every observed character, even without incident edges, and deduplicate edges before incrementing indegrees.

Adjacent wordsForced edge
wrt, wrft -> f
wrf, erw -> e
er, ettr -> t
ett, rftte -> r

These rules form w -> e -> r -> t -> f. Emit zero-indegree characters, remove their outgoing obligations, and enqueue each newly unblocked character. Only w starts ready; the resulting order is wertf. Emitting fewer characters than exist proves a cycle prevents completion.

Problem trace

Only the first unequal letters establish each ordering rule

Input and goalInfer character order from words that are sorted in an unknown alphabet.
Initialize every characterCreate one vertex per observed character, including isolated letters, before recording any precedence rules.
wertf
Observed character inventory
w0e1r2t3f4
words[wrt, wrf, er, ett, rftt]rulesnone yetindegreew:0 e:0 r:0 t:0 f:0
words
[wrt, wrf, er, ett, rftt]
rules
none yet
indegree
w:0 e:0 r:0 t:0 f:0

Recognize it
Use this pattern when sorted composite values imply a hidden ordering among symbols and only the earliest differing position can establish precedence.
Keep true
After processing each word pair, every recorded edge is a necessary character precedence; during Kahn traversal, ready contains exactly known zero-indegree un-emitted characters and emitted never violates an edge.
Reuse it
Extract only logically forced local precedence constraints, include unconstrained nodes, reject malformed prefix input, then topologically order and verify every node was emitted.
Create one vertex per observed character, including isolated letters, before recording any precedence rules. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Which adjacent word pair forces t before f? Why do later letters in that pair add no rule?

A word cannot precede its complete shorter prefix

A word cannot precede its complete shorter prefixBoth words share every compared character.A shared prefix supplies no newletter ruleLonger word firstabcabinvalidShorter word firstababcvalidChanging the alphabet cannot fix alonger word placed before its entireprefix.
Both words share every compared character.
Reference drawing

Problem trace

Only the first unequal letters establish each ordering rule

Worked example: only the first unequal character creates an ordering edgeThe words wrt and wrf first differ at their third character. Infer t before f; the shared prefix supplies no new edge.Shared prefix columns supply noordering edgewrtwrfOnly the first unequal pair becomes tbefore ftf
Execution trace
Input and goalInfer character order from words that are sorted in an unknown alphabet.
Initialize every characterCreate one vertex per observed character, including isolated letters, before recording any precedence rules.
wertf
Observed character inventory
w0e1r2t3f4
words[wrt, wrf, er, ett, rftt]rulesnone yetindegreew:0 e:0 r:0 t:0 f:0
words
[wrt, wrf, er, ett, rftt]
rules
none yet
indegree
w:0 e:0 r:0 t:0 f:0

Recognize it
Use this pattern when sorted composite values imply a hidden ordering among symbols and only the earliest differing position can establish precedence.
Keep true
After processing each word pair, every recorded edge is a necessary character precedence; during Kahn traversal, ready contains exactly known zero-indegree un-emitted characters and emitted never violates an edge.
Reuse it
Extract only logically forced local precedence constraints, include unconstrained nodes, reject malformed prefix input, then topologically order and verify every node was emitted.
Create one vertex per observed character, including isolated letters, before recording any precedence rules. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Which adjacent word pair forces t before f? Why do later letters in that pair add no rule?
Read it this way: The words wrt and wrf first differ at their third character. Infer t before f; the shared prefix supplies no new edge. Would a later mismatch supply a second edge after the first unequal character already decides this word pair?

Code

from collections import deque

def _first_difference(first: str, second: str) -> tuple[str, str] | None:
   for first_char, second_char in zip(first, second, strict=False):
      if first_char != second_char:
         return first_char, second_char
   return None


def alien_order(words: list[str]) -> str:
   graph = {char: set() for word in words for char in word}
   indegree = {char: 0 for char in graph}

   for first, second in zip(words, words[1:], strict=False):
      difference = _first_difference(first, second)
      if difference is None:
         if len(first) > len(second):
            return ""
         continue

      first_char, second_char = difference
      if second_char not in graph[first_char]:
         graph[first_char].add(second_char)
         indegree[second_char] += 1

   ready = deque(char for char, count in indegree.items() if count == 0)
   order: list[str] = []

   while ready:
      char = ready.popleft()
      order.append(char)
      for next_char in graph[char]:
         indegree[next_char] -= 1
         if indegree[next_char] == 0:
            ready.append(next_char)

   return "".join(order) if len(order) == len(indegree) else ""

The source returns any consistent extension, not necessarily the lexically smallest or uniquely implied alphabet. Empty output also represents no observed characters; it does not distinguish that valid empty case from failure. For input characters, distinct characters and distinct edges, expected work is . Additional graph storage is .

Failure Check

["abc","ab"] fails by prefix ordering; ["z","x","z"] fails by a directed cycle. Sorting letters by first appearance invents unsupported constraints.

Change to an Order and Uniqueness Report

New task: Report validity and ambiguity while selecting the lexical minimum consistent alphabet.

Picture and change: Use a min-heap for ready characters and flag ambiguity whenever more than one choice is available.

import heapq

def alien_order_report(words):
   graph = {char: set() for word in words for char in word}
   indegree = dict.fromkeys(graph, 0)
   for first, second in zip(words, words[1:]):
      difference = _first_difference(first, second)
      if difference is None:
         if len(first) > len(second):
            return {"order": "", "valid": False, "unique": False}
      else:
         before, after = difference
         if after not in graph[before]:
            graph[before].add(after)
            indegree[after] += 1
   ready = [char for char in graph if indegree[char] == 0]
   heapq.heapify(ready)
   order, unique = [], True
   while ready:
      unique = unique and len(ready) == 1
      char = heapq.heappop(ready)
      order.append(char)
      for following in graph[char]:
         indegree[following] -= 1
         if indegree[following] == 0:
            heapq.heappush(ready, following)
   valid = len(order) == len(graph)
   return {"order": "".join(order) if valid else "", "valid": valid, "unique": unique and valid}

Check: ["ab","ac"] gives {"order":"abc","valid":True,"unique":False}. The letter a is unconstrained; choosing it first is policy, not evidence of its original rank. The invalid prefix example reports both flags false. Heap processing adds work; uniqueness concerns only the observed character set.

Use when: Determinism and underdetermination must both be explicit.

Change to Candidate Validation

New task: Check whether a supplied alphabet explains the observed word ordering.

Picture and change: Rank supplied characters, reject duplicates or missing observed symbols, then check adjacent-word first differences.

def consistent_alphabet(words, order):
   rank = {char: index for index, char in enumerate(order)}
   if len(rank) != len(order) or any(char not in rank for word in words for char in word):
      return False
   for first, second in zip(words, words[1:]):
      difference = _first_difference(first, second)
      if difference is None:
         if len(first) > len(second):
            return False
      elif rank[difference[0]] >= rank[difference[1]]:
         return False
   return True

Check: ["ab","ac"] accepts "abc" and rejects "cba". Extra unobserved characters are allowed; duplicated characters are not. Consistency does not establish uniqueness or historical truth. Both variations reuse the complete _first_difference helper above.

Use when: Another authority supplies the alphabet.

Transfer Check

Why are adjacent pairs sufficient?

Answer

A sequence is sorted exactly when every adjacent pair is nondecreasing under the same total order. Transitivity handles farther pairs.