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
Reversing consonants only from a string in JavaScript
We are required to write a JavaScript function that takes in a string of lowercase English alphabets as the only argument.
The function should construct a new string in which the order of consonants is reversed and the vowels hold their relative positions.
Problem Statement
For example, if the input to the function is:
const str = 'somestring';
Then the output should be:
const output = 'gomenrtiss';
In this example, consonants 's', 'm', 't', 'r', 'n', 'g' are reversed to 'g', 'n', 'r', 't', 'm', 's', while vowels 'o', 'e', 'i' stay in their original positions.
Algorithm Approach
We use a two-pointer technique to swap consonants from both ends of the string while keeping vowels in their original positions:
- Convert string to array for easy manipulation
- Use left and right pointers to find consonants
- Skip vowels and swap consonants
- Continue until pointers meet
Example
const str = 'somestring';
const reverseConsonants = (str = '') => {
const arr = str.split("");
let i = 0, j = arr.length - 1;
const consonants = 'bcdfghjklmnpqrstvwxyz';
while(i < j){
// Find consonant from left
while(i < j && consonants.indexOf(arr[i]) < 0) {
i++;
}
// Find consonant from right
while(i < j && consonants.indexOf(arr[j]) < 0) {
j--;
}
// Swap consonants
let tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
i++;
j--;
}
return arr.join('');
};
console.log(reverseConsonants(str));
gomenrtiss
How It Works
Let's trace through 'somestring':
- Original: s-o-m-e-s-t-r-i-n-g
- Consonants found: s, m, s, t, r, n, g
- Reversed consonants: g, n, r, t, s, m, s
- Final result: g-o-n-e-r-t-i-s-s (keeping vowels o, e, i in place)
Alternative Using Built-in Methods
const reverseConsonantsAlt = (str) => {
const vowels = 'aeiou';
const consonants = [];
// Extract consonants in reverse order
for(let i = str.length - 1; i >= 0; i--) {
if(!vowels.includes(str[i])) {
consonants.push(str[i]);
}
}
let consonantIndex = 0;
let result = '';
// Replace consonants with reversed ones
for(let char of str) {
if(vowels.includes(char)) {
result += char;
} else {
result += consonants[consonantIndex++];
}
}
return result;
};
console.log(reverseConsonantsAlt('hello'));
console.log(reverseConsonantsAlt('javascript'));
lellh ptircsavaj
Key Points
- Two-pointer technique efficiently swaps elements in-place
- Vowels (a, e, i, o, u) maintain their original positions
- Only consonants are reversed relative to each other
- Time complexity: O(n), Space complexity: O(n) for array conversion
Conclusion
Reversing consonants while preserving vowel positions can be efficiently solved using the two-pointer technique. This approach ensures optimal time complexity while maintaining the string's vowel structure.
