Categories
interview

Verifying an Alien Dictionary (Js)

/**
 * @param {string[]} words
 * @param {string} order
 * @return {boolean}
 */
const isAlienSorted = function(words, order) {
  
const isInOrder = {};
  for (let i = 0; i < order.length; i++) {
    isInOrder[order.charAt(i)] = i;
  }

  search: for (let i = 0; i < words.length - 1; i++) {
    const wordBefore = words[i];
    const wordAfter = words[i + 1];
    const minWordLen = Math.min(wordBefore.length, wordAfter.length);
    for (let k = 0; k < minWordLen; k++) {
      if (wordBefore.charAt(k) !== wordAfter.charAt(k)) {
        if (isInOrder[wordBefore.charAt(k)] > isInOrder[wordAfter.charAt(k)]) {
          return false;
          }
        continue search;
      }
    }
   if (wordBefore.length > wordAfter.length) {
     return false;
     }
  }
  return true
};

console.log(isAlienSorted(['ace', 'ad'], 'abcdefghijklmnopqrstuv')); // true

Demo