AlgoFrames

Alien dictionary

Challenge · Write code · about 25 min

An alien language uses lowercase English letters in an unknown order. words is sorted by that order, like a dictionary. Return a string with every letter that appears, in an order consistent with the words. Any valid order is accepted. Return "" if no order fits.

Example 1

Input:

[["wrt","wrf","er","ett","rftt"]]

Output:

wertf

wrt < wrf gives t → f; wrf < er gives w → e; er < ett gives r → t; ett < rftt gives e → r.

Example 2

Input:

[["z","x","z"]]

Output:

z before x and x before z cannot both hold.

Constraints

  • 1 ≤ words.length ≤ 100
  • 1 ≤ words[i].length ≤ 100
  • Words use lowercase English letters.

Learn the idea first: Topological sort: Kahn's algorithm and DFS finishing order, a visual lesson.

More Topological sort: Kahn's algorithm and DFS finishing order problems