How to use Two-Pointer Technique In Javascript
Using the two-pointer technique to reverse consonants involves placing pointers at the beginning and end of the string, swapping consonants when both pointers are at consonants, and moving pointers inward. This continues until the pointers cross, ensuring non-consonants remain unaffected.
Example: In this example The function reverseConsonants reverses consonants in a string using a two-pointer technique, leaving other characters unchanged. It correctly reverses consonants while preserving the string’s structure.
function reverseConsonants(str) {
const isConsonant = (char) => /[bcdfghjklmnpqrstvwxyz]/i.test(char);
let arr = str.split('');
let left = 0;
let right = arr.length - 1;
while (left < right) {
if (!isConsonant(arr[left])) {
left++;
} else if (!isConsonant(arr[right])) {
right--;
} else {
[arr[left], arr[right]] = [arr[right], arr[left]];
left++;
right--;
}
}
return arr.join('');
}
console.log(reverseConsonants("Hello, World!")); // "Hollo, Werld!"
Output
delro, WollH!
JavaScript Program to Reverse Consonants in a Given String Without Affecting the Other Elements
In this article, we have given a string and the task is to write a javascript program to reverse only the consonants of a string without affecting the other elements’ positions and printing the output in the console.
Examples:
Input: hello
Output: lelho
Explanation: h,l,l are consonants in the given string.
After modifying the string their occurrences are l,l,h and
vowels positions are not changed.
These are the following approaches by using these we can solve the given question:
Contact Us