[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;

25 thoughts on “[Programming Problem] Verifying an Alien Dictionary

  1. I’m not sure why but this site is loading very slow for me.
    Is anyone else having this issue or is it a problem on my end?
    I’ll check back later and see if the problem still exists.

  2. I’ve been surfing on-line more than 3 hours today, but I never discovered any
    interesting article like yours. It is lovely
    worth sufficient for me. Personally, if all website
    owners and bloggers made excellent content as you did, the internet will probably be a lot more useful than ever before.

Leave a Reply

Your email address will not be published.