Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Alien Dictionary

Hard Acceptance 47.81% Points 40.00

You are given a sorted dictionary of an alien language containing several words (dict) and k starting alphabets of the standard dictionary. Your task is to determine the order of characters in the alien language based on the given words. If no valid ordering of characters is possible, return an empty string.

Note: Multiple valid orders may exist for a given test case. The output will be considered correct if the returned order satisfies the conditions, otherwise, the output will be "false."

Examples
Example 1

Example 1

Input: dict[] = ["caa", "aaa", "aab"], k = 3

Output: true

Explanation: The order of characters is 'c', 'a', 'b'. "caa" comes before "aaa", so 'c' is before 'a'. "aaa" comes before "aab", so 'a' is before 'b'.

Example 2

Example 2

Input: dict[] = ["z", "x", "z"], k = 2

Output: false

Explanation: No valid ordering is possible because "z" appears before and after "x," causing a contradiction.

Hints
Hint 1
Expected Time Complexity: O(n * |s| + k)
Hint 2
ExpectedAuxiliary Space: O(k)
Constraints
  • 1 <= dict.size() <= 10^4
  • 1 <= k <= 26
  • 1 <= Length of words <= 50
Companies
Amazon Microsoft Walmart Google Flipkart
Topics
String
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions