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
Searching for target string in a strangely sorted array in JavaScript
We are required to write a JavaScript function that takes in a word target and an array of sorted(by length(increasing), number of uppercase letters(decreasing), natural order) unique words which always contains the target.
The task of our function is to find the index(0 based) of the target in the array of words, which would always be in the list.
Understanding the Sorting Pattern
The array is sorted by three criteria in order:
- Length: Shorter strings come first
- Uppercase count: Among same-length strings, more uppercase letters come first
- Natural order: Alphabetically among strings with same length and uppercase count
Example Implementation
Here's how to find the target string in such an array:
const arr = ['cP', 'rE', 'sZ', 'am', 'bt', 'ev', 'hq', 'rx', 'yi', 'akC', 'nrcVpx', 'iKMVqsj'];
const target = 'akC';
const findTarget = (arr = [], target = '') => {
const index = arr.indexOf(target);
return index;
};
console.log(findTarget(arr, target));
9
How the Sorting Works
Let's analyze the array structure to understand the sorting:
const arr = ['cP', 'rE', 'sZ', 'am', 'bt', 'ev', 'hq', 'rx', 'yi', 'akC', 'nrcVpx', 'iKMVqsj'];
// Analyze each string
arr.forEach((word, index) => {
const length = word.length;
const uppercaseCount = (word.match(/[A-Z]/g) || []).length;
console.log(`Index ${index}: "${word}" - Length: ${length}, Uppercase: ${uppercaseCount}`);
});
Index 0: "cP" - Length: 2, Uppercase: 1 Index 1: "rE" - Length: 2, Uppercase: 1 Index 2: "sZ" - Length: 2, Uppercase: 1 Index 3: "am" - Length: 2, Uppercase: 0 Index 4: "bt" - Length: 2, Uppercase: 0 Index 5: "ev" - Length: 2, Uppercase: 0 Index 6: "hq" - Length: 2, Uppercase: 0 Index 7: "rx" - Length: 2, Uppercase: 0 Index 8: "yi" - Length: 2, Uppercase: 0 Index 9: "akC" - Length: 3, Uppercase: 1 Index 10: "nrcVpx" - Length: 6, Uppercase: 0 Index 11: "iKMVqsj" - Length: 7, Uppercase: 3
Optimized Search Function
For better performance on large arrays, we could implement binary search since the array is sorted:
const findTargetOptimized = (arr = [], target = '') => {
// For demonstration, we'll use indexOf since it's simpler
// In practice, binary search would be more efficient for large arrays
return arr.indexOf(target);
};
const arr = ['cP', 'rE', 'sZ', 'am', 'bt', 'ev', 'hq', 'rx', 'yi', 'akC', 'nrcVpx', 'iKMVqsj'];
console.log(findTargetOptimized(arr, 'akC')); // 9
console.log(findTargetOptimized(arr, 'am')); // 3
console.log(findTargetOptimized(arr, 'nrcVpx')); // 10
9 3 10
Conclusion
The `indexOf()` method efficiently finds the target string's position in the specially sorted array. Understanding the sorting criteria helps verify the correctness of the search results.
