CodingNodes / Advanced Graphs / Alien Dictionary System design Space play · ←→ step · R restart

Problem

A visiting species writes words with the lowercase English letters, but sorts them with an alphabet of its own: the same 26 letters, in an unknown order. You get a list words that is already sorted by that alphabet.

Return a string that lists every letter used in words in an order consistent with the sorting. If the list cannot be sorted by any alphabet (the facts contradict each other, or a longer word comes before its own beginning), return an empty string.

Several answers can be valid when the words do not pin the order down. In the examples the order is unique, so the expected output is exact.

Constraints

  • 1 ≤ words.length ≤ 100
  • 1 ≤ words[i].length ≤ 100
  • words[i] uses only lowercase English letters

Examples: pick one to animate

Solutions

TimeO(C) SpaceO(1)

Time: Every letter of every word is read a constant number of times (marking, then comparing neighbours). C is the total number of letters. The 26 by 26 arrow table adds only a fixed amount of work.

Space: The seen flags, the indegree counts, the 26 by 26 arrow table and the queue have a size that depends on the alphabet (26), not on the input.

Two neighbouring words give exactly one fact: at their first differing position, the letter of the earlier word comes before the letter of the later one. If there is no differing position and the earlier word is longer, the list is impossible. Record each fact as an arrow between two letters and count, for every letter, how many arrows point at it (its indegree). Letters with indegree 0 can go first. Take one, append it to the order and remove its arrows, which may free more letters. If the order ends up with every letter that appeared, it is valid. If it is shorter, some letters wait for each other in a circle.