Instructions
An unknown language uses some lowercase English letters, but in its own alphabet the letters are in a different order. You are given a list words from this language. The list is said to be sorted in dictionary order using that unknown alphabet.
Dictionary order works as usual: compare two words letter by letter from the start. At the first position where they differ, the word whose letter comes earlier in the alphabet comes first. If one word runs out first and all its letters match the start of the other word, the shorter word comes first. Equal words may stand next to each other.
Return a string that contains every letter that appears in words, each exactly once, in an order that would make the list sorted.
- If no order of the letters makes the list sorted, return an empty string
"". This happens, for example, when a longer word comes before a word that is its own start (its prefix). - If several orders work, return the one that is smallest in normal a-z dictionary order. This makes the answer unique.
Hint: only neighbour words give information. The first different letter of two neighbour words tells you that one letter comes before another. Build a graph of these rules, then find a topological order. Always take the smallest letter that is ready.
Examples
Example 1
- Input:
- ["pt","pm","tm","tmq","m"]
- Output:
- "pqtm"
"pt" before "pm" gives t before m. "pm" before "tm" gives p before t. "tm" before "tmq" is fine, because the shorter word is the start of the longer one. "tmq" before "m" gives t before m again. So p, t, m must be in this order, and q can go anywhere. The smallest such string in a-z order puts q right after p: "pqtm".
Example 2
- Input:
- ["ab","b","ba","a"]
- Output:
- ""
"ab" before "b" says a comes before b. "ba" before "a" says b comes before a. Both rules cannot be true at the same time, so no alphabet works.
Example 3
- Input:
- ["bat","ba"]
- Output:
- ""
"ba" is the start of "bat", so in every alphabet "ba" must come first. Here the longer word comes first, so no alphabet can make this list sorted.
Constraints
1 <= words.length <= 101 <= words[i].length <= 6words[i]has only lowercase English letters.- All words together use at most 7 different letters.
3 examples run when you press Run. Submit checks every hidden test too.
- Input:
- ["pt","pm","tm","tmq","m"]
- Expected:
- "pqtm"
- Input:
- ["ab","b","ba","a"]
- Expected:
- ""
- Input:
- ["bat","ba"]
- Expected:
- ""
Run checks your code against the 3 examples. Submit checks it against all 203 tests and needs a free account. You can also try ideas in the free JavaScript or Python compiler.