Skip to content
BASA DSA

Alien Dictionary

HardAdvanced Graphs

Words are sorted according to an unknown order of lowercase letters. Return any ordering of exactly the letters that occur, consistent with this sorted list. Return an empty string for a contradictory order or a longer word before its own prefix.

Example 1

Character precedence from the first differing letters of adjacent words: za, zb, ca, cb. A longer word before its own prefix is invalid.Character precedence from the first differing letters of adjacent words: za, zb, ca, cb. A longer word before its own prefix is invalid. Vertices: node 0: a, node 1: b, node 2: c, node 3: z. Edges: node 0 (a) → node 1 (b); node 3 (z) → node 2 (c).abcz
Character precedence from the first differing letters of adjacent words: za, zb, ca, cb. A longer word before its own prefix is invalid.

Input
words = ["za","zb","ca","cb"]
Output
"abzc"

Explanation

Comparisons require a before b and z before c; abzc contains all letters and respects both.

Example 2

Character precedence from the first differing letters of adjacent words: abc, ab. A longer word before its own prefix is invalid.Character precedence from the first differing letters of adjacent words: abc, ab. A longer word before its own prefix is invalid. Vertices: node 0: a, node 1: b, node 2: c. Edges: none.abc
Character precedence from the first differing letters of adjacent words: abc, ab. A longer word before its own prefix is invalid.

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

Explanation

A longer word cannot precede its own exact prefix under any letter ordering.

Example 3

Character precedence from the first differing letters of adjacent words: z, x, z. A longer word before its own prefix is invalid.Character precedence from the first differing letters of adjacent words: z, x, z. A longer word before its own prefix is invalid. Vertices: node 0: x, node 1: z. Edges: node 1 (z) → node 0 (x); node 0 (x) → node 1 (z).xz
Character precedence from the first differing letters of adjacent words: z, x, z. A longer word before its own prefix is invalid.

Input
words = ["z","x","z"]
Output
""

Explanation

The comparisons demand both z before x and x before z, a contradiction.

Example 4

Character precedence from the first differing letters of adjacent words: a. A longer word before its own prefix is invalid.Character precedence from the first differing letters of adjacent words: a. A longer word before its own prefix is invalid. Vertices: node 0: a. Edges: none.a
Character precedence from the first differing letters of adjacent words: a. A longer word before its own prefix is invalid.

Input
words = ["a"]
Output
"a"

Explanation

Only a occurs, so the one-letter ordering a satisfies all comparisons.

Constraints

  • 1 <= number of words <= 100
  • Each word has 1..100 lowercase English letters

Function contractalienOrderArguments: json
Loading draft…
SolutionRuns on your device
Loading draft…