Search~35 min2s · 256 MBtarget O(total + 26^3) time, O(26) spacetopological-sort
A search index sorts its terms with a custom letter order, and the order itself was lost. All that remains is a list of terms that is known to be sorted by that order.
The first letter where two neighbouring terms differ shows which of the two letters comes first. You want the letters whose place is certain, meaning every order that could have sorted the list puts them at the same position.
Write fixed_letters(words).
words is the list of terms, sorted by an unknown order of the letters that appear in it.words puts it at the same position."!" when no order of the letters can sort words.Input: words = ["ad", "ddd", "dgg", "fd", "fff", "eg"]
Output: "ad"Five letters appear: a, d, g, f and e. Each pair of neighbours gives one fact at its first different letter.
| Pair | First difference | Fact |
|---|---|---|
| ad, ddd | a and d | a before d |
| ddd, dgg | d and g | d before g |
| dgg, fd | d and f | d before f |
| fd, fff | d and f | d before f |
| fff, eg | f and e | f before e |
Chaining the facts gives a before d, g, f and e, and d before g, f and e. The letters g and f are never compared. The table counts the letters that must come before and after each letter.
| Letter | Before it | After it | Total |
|---|---|---|---|
| a | 0 | 4 | 4 |
| d | 1 | 3 | 4 |
| g | 2 | 0 | 2 |
| f | 2 | 1 | 3 |
| e | 3 | 0 | 3 |
A place is certain when the total is 4, the number of other letters. That holds for a and d, so the answer is "ad".
Input: words = ["bat", "bar", "car", "cab", "ace"]
Output: ""The facts are t before r, b before c, r before b and c before a. Together they order t, r, b, c, a. The letter e appears in ace but is never compared, so every letter could move next to it and no place is certain.
Input: words = ["tab", "tar", "rar", "rat", "bat"]
Output: "!"The pair tar, rar says t before r, and the pair rar, rat says r before t. No order can satisfy both.
1 ≤ words.length ≤ 100,000a to z.Trying every order of the letters that appear can mean 26! orders, which is about 4 × 10^26. The facts come only from neighbouring terms, so reading the list costs at most 100,000 × 20 = 2 × 10^6 steps. The chaining step works on 26 letters, so it costs 26^3 = 17,576 steps.