157. The Order Behind the Words
Hard
A list of words is sorted according to an unknown alphabet. Every word contains only lowercase letters, but the order of those letters may differ from the usual order.
Deduce a valid order for all letters that appear in words. If multiple valid orders exist, return the lexicographically smallest one using the usual letter order to break ties. Return an empty string if no valid order exists. This happens when the deduced relationships form a cycle or when a word appears before another word of which it is a prefix.
Example 1
Input: words = ["za", "zb", "ca", "cb"]
Output: "abzc"
Explanation: The relationships require `a` to come before `b` and `z` to come before `c`; tie-breaking chooses the smallest valid order.
Example 2
Input: words = ["baa", "abcd", "abca", "cab", "cad"]
Output: "bdac"
Explanation: Comparisons between the words determine the relationships that lead to this order.
Example 3
Input: words = ["abcd", "ab"]
Output: ""
Explanation: A word cannot come before another word of which it is a prefix.
Constraints
- 1 <= words.length <= 1000
- 1 <= words[i].length <= 100
- words[i] contains only lowercase letters from 'a' to 'z'.
GraphsStringsBFS
Saved in this browser
Caso 1
words =
["za","zb","ca","cb"]
Expected =
"abzc"
Caso 2
words =
["baa","abcd","abca","cab","cad"]
Expected =
"bdac"
Caso 3
words =
["abcd","ab"]
Expected =
""
Run checks these 3 cases. Submit runs all 12, including hidden ones.