Reverse Words in a String
Given a sentence, reverse the order of its words without affecting the order of letters within a given word.
Given a sentence, reverse the order of its words without affecting the order of letters within a given word.
Constraints
- Sentence contains English uppercase and lowercase letters, digits, and spaces.
- 1 ≤
sentence.length≤ 10⁴ - The order of the letters within a word is not to be reversed.
Note: The input string may contain leading or trailing spaces or multiple spaces between words. The returned string, however, should only have a single space separating each word. Do not include any extra spaces.
Examples
Example 1
Input String: "Hello Friend"
Reversed String: "Friend Hello"
Example 2
Input String: "Welcome to Educative"
Reversed String: "Educative to Welcome"
Example 3
Input String: "Hurray 3 2 1"
Reversed String: "1 2 3 Hurray"
Solution
Simple Two pointer approach convert this number into array and reverse this array .
function reverseWord(str) {
const arr = str.split(' ').filter(word => word.length > 0);
let left = 0;
let right = arr.length - 1;
while (left <= right) {
[arr[left], arr[right]] = [arr[right], arr[left]];
left++;
right--;
}
return arr.join(' ');
}
console.log(reverseWord('Hello Friend')); // "Friend Hello"
console.log(reverseWord(' Hello Friend ')); // "Friend Hello"
console.log(reverseWord(' a good example ')); // "example good a"
Time complexity: O(N) Space Complexity: O(1)