less than 1 minute read

953. Verifying an Alien Dictionary (easy)

class Solution:

    def isAlienSorted(self, words: List[str], order: str) -> bool:
        temp = {}
        for i, c in enumerate(order):
            temp[c] = i

        def compare(word1, word2):
            n1, n2 = len(word1), len(word2)
            n = min(n1, n2)
            for i in range(n):
                a, b = word1[i], word2[i]
                if temp[a] > temp[b]:
                    return -1
                elif temp[a] < temp[b]:
                    return 1
            if n1 == n2:
                return 0
            return (-1 if n1 > n2 else 1)
        
        n = len(words)
        for i in range(n - 1):
            a, b = words[i], words[i + 1]
            if compare(a, b) < 0:
                return False
        return True