Alien Dictionary Sort

Hard
topological-sort graph dfs alien-language
Problem Description

Given a list of words sorted according to an alien language, determine the order of characters in that alien alphabet. The words are given in lexicographically sorted order according to the alien language rules.

Input Format
First line contains n (number of words). Next n lines contain words in the alien language (lowercase letters only).
Output Format
A string representing the order of characters in the alien alphabet, or "INVALID" if no valid order exists.
Constraints
• 1 ≤ n ≤ 100
• 1 ≤ word length ≤ 100
• Words contain only lowercase English letters
• Words are given in sorted order according to alien language
• Return lexicographically smallest valid order if multiple exist
Sample Input/Output
Input:
4
wrt
wrf
er
ett
Output:
wertf
Explanation

From "wrt" and "wrf": t comes before f. From "wrt" and "er": w comes before e. From "er" and "ett": r comes before t. Building the order: w → e → r → t → f.

Solution Hints
170
Points
4000ms
Time Limit
256MB
Memory Limit
Code Editor
Register to Submit
Register to Access Code Editor

Create a free account to solve coding problems and track your progress.

Register Now
Feedback