Tutorialspoint
Problem
Solution
Submissions

Alien Dictionary

Certification: Advanced Level Accuracy: 0% Submissions: 0 Points: 15

Write a C++ program to solve the Alien Dictionary problem. In an alien language, words are sorted lexicographically based on the alien alphabet. Given a sorted dictionary of alien words, derive the order of letters in the alien alphabet. Return a string representing the order of the alien alphabet. If there is no valid order, return an empty string.

Example 1
  • Input: words = ["wrt", "wrf", "er", "ett", "rftt"]
  • Output: "wertf"
  • Explanation:
    • From "wrt" and "wrf", we know 't' comes before 'f'
    • From "wrf" and "er", we know 'w' comes before 'e'
    • From "er" and "ett", we know 'r' comes before 't'
    • From "ett" and "rftt", we know 'e' comes before 'r'
    • Combining all relationships: "wertf"
Example 2
  • Input: words = ["z", "x", "z"]
  • Output: ""
  • Explanation:
    • Since "z" appears both before and after "x", there's a contradiction.
    • No valid alphabet order exists.
Constraints
  • 1 ≤ words.length ≤ 100
  • 1 ≤ words[i].length ≤ 100
  • words[i] consists of only lowercase English letters
  • Time Complexity: O(C) where C is the total length of all words
  • Space Complexity: O(1) or O(U^2) where U is the number of unique characters
QueueSetTech MahindraShopify
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Extract character order relationships from adjacent words
  • Create a directed graph where edges represent order relationships
  • Check for cycles in the graph (which would indicate an invalid order)
  • Perform a topological sort on the graph
  • The topological sort result is the order of the alien alphabet

Steps to solve by this approach:

 Step 1: Create a set of all unique characters in the words.
 Step 2: Build a directed graph where edges represent the ordering relationships between characters.
 Step 3: For each pair of adjacent words, find the first differing character and add an edge.
 Step 4: Check for invalid orderings (e.g., if a longer word is a prefix of a shorter word).
 Step 5: Perform a topological sort using Kahn's algorithm with a queue of nodes with 0 in-degree.
 Step 6: Build the result string by appending characters in topological order.
 Step 7: Validate the result by checking if all characters are included (indicating no cycles).

Submitted Code :