Skip to main content

Verifying an Alien Dictionary

Easy
Data Structures and Algorithms
Editorial
Topics:
String
Hash Table
Array

Implement Solution.isAlienSorted(words, order) to determine whether the list words is sorted according to an alien alphabet. The string order gives the complete character ranking: a character appearing earlier in order is considered smaller than one appearing later.

Compare words lexicographically using this ranking. For two words, the first position where their characters differ determines their order. If one word is a prefix of the other, the shorter word must come first. Equal words are allowed.

Return true if every consecutive pair in words follows these rules; otherwise, return false.

Example 1:

Input: words = ["mango","map","mat"], order = "abcdefghijklmnopqrstuvwxyz"
Output: true
Explanation: The words are in ordinary alphabetical order: "mango" comes before "map", and "map" comes before "mat" at their first differing character.

Example 2:

Input: words = ["zone","zoo"], order = "zyxwvutsrqponmlkjihgfedcba"
Output: false
Explanation: After the shared prefix z, the reversed alphabet ranks o before n, so zoo should come before zone.

Example 3:

Input: words = ["cabin","cabinet"], order = "abcdefghijklmnopqrstuvwxyz"
Output: true
Explanation: cabin is a prefix of cabinet, and the shorter word correctly appears first.

Constraints:

  • 1 <= words.length <= 100
  • 1 <= words[i].length <= 20
  • words[i] contains only lowercase English letters
  • order.length = 26
  • order is a permutation of the 26 lowercase English letters

Need help or want more practice?

Practise in an interviewGet AI Coach help