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 DictionaryInput Words: ["hello", "leetcode"]Alien Order: "hlabcdefgijkmnopqrstuvwxyz"hellovsleetcodeCompare using alien alphabet positions:h = 0l = 2Position 0 < Position 2 → Correctly sorted ✓All adjacent pairs must be in correct orderOutput: true
Understanding the Visualization
1
Input
Words array and custom alphabet order
2
Process
Compare adjacent words using alien alphabet positions
3
Output
Return true if words are sorted, false otherwise
Key Takeaway
🎯 Key Insight: Build a position mapping for the alien alphabet to enable fast character comparisons
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