|
| 1 | +/** |
| 2 | + * @param {string[]} words Words to check for order. |
| 3 | + * @param {string} order Order of characters in alien alphabet. |
| 4 | + * @return {boolean} Are given words in alphabetical order given Alien alphabet |
| 5 | + * @summary Verifying Alien Dictionary {@link https://leetcode.com/problems/verifying-an-alien-dictionary/} |
| 6 | + * @description Given a list of words and custom alphabet, return true if list of word is sorted alphabetically. |
| 7 | + * Space O(1) - not asiggning any new memory. |
| 8 | + * Time O(n) - number of words. |
| 9 | + */ |
| 10 | +const isAlienSorted = (words, order) => { |
| 11 | + const OFFSET = 'a'.charCodeAt(0); |
| 12 | + const orderLength = order.length; |
| 13 | + const wordsLength = words.length; |
| 14 | + const humanToAlien = Array('z'.charCodeAt(0) - OFFSET); |
| 15 | + |
| 16 | + for (let i = 0; i < orderLength; i++) { |
| 17 | + humanToAlien[order[i].charCodeAt(0) - OFFSET] = i; |
| 18 | + } |
| 19 | + |
| 20 | + for (let i = 0; i < wordsLength - 1; i++) { |
| 21 | + const w1 = words[i]; |
| 22 | + const w2 = words[i + 1]; |
| 23 | + const iterationLength = w1.length < w2.length ? w1.length : w2.length; |
| 24 | + |
| 25 | + let sameChars = true; |
| 26 | + for (let j = 0; j < iterationLength; j++) { |
| 27 | + const char1 = w1[j]; |
| 28 | + const char2 = w2[j]; |
| 29 | + |
| 30 | + if (char1 !== char2) { |
| 31 | + sameChars = false; |
| 32 | + |
| 33 | + if (humanToAlien[char1.charCodeAt(0) - OFFSET] > humanToAlien[char2.charCodeAt(0) - OFFSET]) return false; |
| 34 | + break; |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + if (sameChars && w1.length > w2.length) return false; |
| 39 | + } |
| 40 | + |
| 41 | + return true; |
| 42 | +}; |
0 commit comments