How to use In-place Reversal and split() method In Javascript
In this approach, we convert the input string into an array of characters. We then iterate through each character in the array to find the start and end indices of each word. For each word, we check if its length is odd. If it is odd, we reverse the characters of the word in-place using a helper function. After processing all words, we convert the array of characters back into a string and return the modified string.
Example: The below example shows how to reverse only the odd length words using In-place Reversal and split() method.
function reverseOWords(str) {
// Convert the string into an array of characters
let ch = str.split("");
let start = 0;
// Iterate through each character in the array
for (let i = 0; i < ch.length; i++) {
if (ch[i] === " " || i === ch.length - 1) {
let end = (i === ch.length - 1) ? i : i - 1;
let wordLength = end - start + 1;
// Check if the length of the word is odd
if (wordLength % 2 !== 0) {
revWord(ch, start, end);
}
start = i + 1;
}
}
return ch.join("");
}
function revWord(ch, start, end) {
while (start < end) {
let temp = ch[start];
ch[start] = ch[end];
ch[end] = temp;
start++;
end--;
}
}
const input = "Hellow world how are you?";
console.log("Output:", reverseOWords(input));
Output
Output: Hellow dlrow woh era you?
Time Complexity: O(n),where n is the total number of characters in the input string.
Space complexity: O(n), where n is the total number of characters in the input string.
Reverse Only the Odd Length Words using JavaScript
Given a string containing words separated by spaces, our task is to reverse only the words with an odd length. The rest of the words remain unchanged.
Example:
Input: Hellow world how are you? Output: Hellow dlrow woh era you?
Below are the approaches to Reverse only the odd-length words:
Table of Content
- Using Split() Reverse() and Join() Methods
- Using In-place Reversal and split() method