[Programming Problem] Verifying an Alien Dictionary

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 lexicographicaly in this alien language.

[Problem Link]

  • Create a custom comparator which will compare two words based on the order. The custom comparator basically loops through character by character to check order. Do account for cases where one word is smaller than the other or both words are same length.
  • Compare adjacent words in the array using the comparator. If any of them out of place, return false;
 * @param {string[]} words
 * @param {string} order
 * @return {boolean}
var isAlienSorted = function(words, order) {
    const orderMap = {};
    for (var i = 0; i < order.length; i++) orderMap[order[i]] = i;
    for (var i = 0 ; i < words.length-1 ; i++ ) {
        if (compare(words[i], words[i+1], orderMap) === 1) return false;
    return true;    
var compare = function(a, b, orderMap) {
    for ( var i = 0 ; i < Math.min(a.length, b.length) ; i++ ) {
        if (orderMap[a[i]] < orderMap[b[i]]) return -1;
        else if (orderMap[a[i]] > orderMap[b[i]]) return 1;
    if (a.length === b.length) return 0;
    return a.length < b.length ? -1 : 1;

3,404 thoughts on “[Programming Problem] Verifying an Alien Dictionary