Reversing the order of words in a string is a common problem that can be encountered in coding interviews.
Problem Statement
Given a string, reverse the order of words. Each word is separated by spaces, and you need to ensure that the reversed words are also separated by a single space.
Example
Input: "Hello World from Rowdy Coders"
Output: "Coders Rowdy from World Hello"
Approach 1: Using Built-in Methods
The simplest way to reverse the words in a string is by leveraging JavaScript’s built-in methods. Here are the steps:
- Split the string into an array of words.
- Reverse the array.
- Join the array back into a string.
function reverseWords(str) {
return str.split(' ').reverse().join(' ');
}
// Test the function
const input = "Hello World from Rowdy Coders";
const output = reverseWords(input);
console.log(output); // Output: "Coders Rowdy from World Hello"
Explanation
split(' ')
converts the string into an array of words.reverse()
reverses the array.join(' ')
combines the reversed array into a single string with spaces between words.
Approach 2: Using a Loop
If you want to avoid using built-in methods like reverse()
, you can reverse the words using a loop. This approach gives you more control over the process.
function reverseWords(str) {
const words = str.split(' ');
let reversedWords = '';
for (let i = words.length - 1; i >= 0; i--) {
reversedWords += words[i] + (i > 0 ? ' ' : '');
}
return reversedWords;
}
// Test the function
const input = "Hello World from Rowdy Coders";
const output = reverseWords(input);
console.log(output); // Output: "Coders Rowdy from World Hello"
Explanation
split(' ')
converts the string into an array of words.- A loop iterates over the array in reverse order, building the reversed string one word at a time.
- The loop ensures that a space is added between words except after the last word.
Approach 3: Using a Stack
A stack is a suitable data structure for reversing the order of elements. You can push words onto the stack and then pop them off to reverse their order.
function reverseWords(str) {
const words = str.split(' ');
const stack = [];
for (const word of words) {
stack.push(word);
}
let reversedWords = '';
while (stack.length > 0) {
reversedWords += stack.pop() + (stack.length > 0 ? ' ' : '');
}
return reversedWords;
}
// Test the function
const input = "Hello World from Rowdy Coders";
const output = reverseWords(input);
console.log(output); // Output: "Coders Rowdy from World Hello"
Explanation
split(' ')
converts the string into an array of words.- Each word is pushed onto the stack.
- Words are popped off the stack and concatenated into the reversed string.