AAlgoLoopSpaced repetition for LeetCode
EASYStringLeetCode ↗

Verifying an Alien Dictionary

The key idea

Build a rank for each letter from order, then check every adjacent pair of words is sorted. Compare two words character by character at the first position where they differ; if one word is a prefix of the other, the shorter one must come first.

Problem

In an alien language that still uses the 26 English lowercase letters, the letters follow a different order. You are given a list of words words written in this alien language, and a string order that lists all 26 letters in the alien alphabet's order.

Return true if and only if the given words are sorted in increasing lexicographic order according to this new alien order. Otherwise return false.

Lexicographic order works the same way as in English, except the meaning of each letter's rank comes from order instead of the usual a to z. When comparing two words, look at the first position where they differ: the word with the lower-ranked letter at that position is smaller. If one word is a prefix of the other, the shorter word is smaller.

Constraints

Examples

Input: words = ["hello","leetcode"], order = "hlabcdefgijkmnopqrstuvwxyz" Output: true
Input: words = ["word","world","row"], order = "worldabcefghijkmnpqstuvxyz" Output: false
Input: words = ["apple","app"], order = "abcdefghijklmnopqrstuvwxyz" Output: false

Complexity

Time: O(n * m) Space: O(1)

See the full solution

410310
Step-by-step visualization
Start free →

More String problems