Verifying an Alien Dictionary - Problem

In an alien language, surprisingly, they also use English lowercase letters, but possibly in a different order. The order of the alphabet is some permutation of lowercase letters.

Given a sequence of words written in the alien language, and the order of the alphabet, return true if and only if the given words are sorted lexicographically in this alien language.

Example: If the alien alphabet order is "hlabcdefgijkmnopqrstuvwxyz", then "hello" comes before "leetcode" because 'h' < 'l' in this ordering.

Input & Output

Example 1 — Custom Alphabet Order
$ Input: words = ["hello","leetcode"], order = "hlabcdefgijkmnopqrstuvwxyz"
Output: true
💡 Note: In the alien alphabet, 'h' comes before 'l', so 'hello' < 'leetcode'. Words are sorted correctly.
Example 2 — Wrong Order
$ Input: words = ["word","world","row"], order = "worldabcefghijkmnpqstuvxyz"
Output: false
💡 Note: 'word' and 'world' have same prefix 'wor'. Comparing 'd' vs 'l': 'd' comes after 'l' in the order, so 'word' > 'world'. Not sorted.
Example 3 — Prefix Relationship
$ Input: words = ["apple","app"], order = "abcdefghijklmnopqrstuvwxyz"
Output: false
💡 Note: 'app' is a prefix of 'apple'. Shorter word should come first, but 'apple' comes first here. Not sorted.

Constraints

  • 1 ≤ words.length ≤ 100
  • 1 ≤ words[i].length ≤ 20
  • order.length == 26
  • All characters in words[i] and order are English lowercase letters
  • order contains each letter exactly once

Visualization

Tap to expand
Verifying an Alien Dictionary Hash Map Position Lookup Approach INPUT Words Array: "hello" index 0 "leetcode" index 1 Alien Alphabet Order: h l a b c d e f g i j k m n o p q r s t u v w x y z Key Positions: h=0 l=1 e=6 o=14 t=19 c=4 'h' comes BEFORE 'l' in alien order ALGORITHM STEPS 1 Build Position Map Map each char to its index order_map = { 'h':0, 'l':1, 'a':2, 'b':3... 2 Compare Adjacent Words Iterate word pairs "hello" vs "leetcode" 3 Find First Difference Compare char by char 'h' (pos 0) vs 'l' (pos 1) 0 < 1 --> Correct order! 4 Verify All Pairs All pairs sorted = true All pairs valid --> return true FINAL RESULT Word Comparison: "hello" h e l l o "leetcode" l e e t c o d e 'h' at position 0 'l' at position 1 0 < 1 --> Sorted! Output: true Words are sorted in alien order Key Insight: Build a hash map of character positions (O(1) lookup) from the alien alphabet. Then compare adjacent words character by character. The first differing character determines order. Time: O(M) where M = total characters | Space: O(1) for 26-char alphabet map TutorialsPoint - Verifying an Alien Dictionary | Hash Map Position Lookup
Asked in
Facebook 35 Google 25 Amazon 15
180.0K Views
Medium Frequency
~15 min Avg. Time
2.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen