0953. Verifying an Alien Dictionary

Easy | String + Hash Table | 28 ms (96.12%), 14.2 MB (91.25%)

Source: LeetCode - Verifying an Alien Dictionary GitHub: Solution / Performance

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.

Lexicographical order in English 1. Correct order for [apple, book] 2. Correct order for [backtrack, backwords] 3. Wrong order for [apple, app]. Should be [app, apple]

First, we build the order using the hash table or array according to the input order. Then, we iterate through each word in the words to check it with the adjacent word.

Check Conditions

  1. Current index + 1 (current length) is larger than next word's length, return False For the first iteration (index = 0), this check does not work since each word has 1 as MIN length. After passing the first iteration with second check, this check will be effective.

  2. Current word and the adjacent word have different char in the same index

    • Check their order, if violate, return False.

    • Otherwise, break to the next iteration (since they are in the correct order).

class Solution:
    def isAlienSorted(self, words: List[str], order: str) -> bool:
        
        # ==================================================
        #  String                                          =
        # ==================================================
        # time  : O(M), M is the total number of chars in words
        # space : O(1)
        
        table = dict()
        for i in range(len(order)): table[order[i]] =  i
            
        for i in range(len(words) - 1):
            for j in range(len(words[i])):
                # (current string's length > adjacent string's length)
                if j+1 > len(words[i+1]): return False
                
                if words[i][j] != words[i+1][j]:
                    if table[words[i][j]] > table[words[i+1][j]]: return False
                    break
                    
        return True

Last updated