Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Checking if an array is sorted lexicographically in reference to some scrambled alphabet sequence in JavaScript
We need to write a JavaScript function that checks if an array of words is sorted lexicographically according to a custom alphabet order. The function takes two arguments: an array of words and a string representing the custom alphabetical order.
The task is to verify whether the words are arranged correctly based on the given alphabet sequence. If they are properly sorted, return true; otherwise, return false.
Problem Understanding
Consider this example:
const arr = ['this', 'is', 'something', 'mad']; const order = 'hdetljnopqabcuvwxfgirsykmz';
In the custom order, 't' comes before 'i', 'i' comes before 's', and 's' comes before 'm'. So the array is correctly sorted according to this alphabet.
Solution Approach
We'll create a mapping of each character to its position in the custom alphabet, then compare adjacent words character by character:
const arr = ['this', 'is', 'something', 'mad'];
const order = 'hdetljnopqabcuvwxfgirsykmz';
const isPlacedCorrectly = (arr = [], order) => {
// Create a map for quick character position lookup
const charOrder = {};
for (let i = 0; i pos2) {
// word1 comes after word2, incorrect order
return false;
}
// If equal, continue to next character
}
// If all compared characters are equal, shorter word should come first
if (word1.length > word2.length) {
let allEqual = true;
for (let j = 0; j
true
Testing with Different Examples
// Test case 1: Correctly sorted
const test1 = ['hello', 'world'];
const order1 = 'hdetljnopqabcuvwxfgirsykmz';
console.log('Test 1:', isPlacedCorrectly(test1, order1));
// Test case 2: Incorrectly sorted
const test2 = ['world', 'hello'];
console.log('Test 2:', isPlacedCorrectly(test2, order1));
// Test case 3: Same prefix, different lengths
const test3 = ['app', 'apple'];
console.log('Test 3:', isPlacedCorrectly(test3, order1));
function isPlacedCorrectly(arr = [], order) {
const charOrder = {};
for (let i = 0; i pos2) {
return false; // incorrect order
}
}
// If all characters are equal, shorter word should come first
if (word1.length > word2.length) {
let allEqual = true;
for (let j = 0; j
Test 1: true
Test 2: false
Test 3: true
Key Points
- Create a character-to-position mapping for efficient lookups
- Compare adjacent words character by character
- Handle cases where words have common prefixes but different lengths
- Return
falseimmediately when incorrect ordering is found
Conclusion
This solution efficiently checks if words are sorted according to a custom alphabet by creating a position mapping and comparing adjacent words character by character. The time complexity is O(n*m) where n is the number of words and m is the average word length.
