Skip to the code
cf.
+50 XP

#443 Decode a Custom Sort Order

hard

A localization tool received a list of words that some other system already sorted, using a letter order you don't know. All words use lowercase letters a to z.

Write letterOrder(words) that returns a string containing every distinct letter that appears in words exactly once, in an order consistent with how the words are sorted. When the words don't decide which of several letters comes next, put the one that comes first in the normal alphabet first. If no letter order could produce this sorting, return "".

Words are compared the usual way: at the first position where they differ, the word with the earlier letter comes first. If one word is a prefix of the other, the shorter word must come first.

Example 1

Input: words = ["bca","aaa","acb"]
Output: "bac"

bca before aaa means b comes before a. aaa before acb means a comes before c.

Example 2

Input: words = ["abc","ab"]
Output: ""

A word can't come after its own prefix in any letter order.

Constraints

  • 1 <= words.length <= 1000
  • 1 <= words[i].length <= 50
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).