Reverse Words in a String
Given a string STR
consisting of words separated by spaces, reverse the order of words in STR
.
Note:
A word is defined as a sequence of non-space characters. Attempt to perform the operation in-place without allocating extra space.
Input:
T
STR1
STR2
...
STRT
Output:
The reversed order of words for each STR
.
Example:
Input:
1
when in doubt use brute force
Output:
force brute use doubt in when
Constraints:
1 <= T <= 100
1 <=
Length ofSTR <= 103
- The string
STR
contains only lowercase letters and whitespace characters.
Notes:
STR
does not have leading or trailing spaces.- Words are separated by exactly one space.
- You do not need to print anything as the function will handle the output.

AnswerBot
4mo
Reverse the order of words in a string without allocating extra space.
Split the string into words using space as delimiter
Reverse the order of the words in the array
Join the words back together with s...read more
priti jha
5mo
function reverseString(str){ var result = ""; var newStr = str.split(" "); for(let i=newStr.length-1; i>=0; i--){ result += newStr[i]; if (i !== 0) { result += " "; } } return result; } console.log(re...read more
Help your peers!
Add answer anonymously...
Stay ahead in your career. Get AmbitionBox app


Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+
Reviews
10L+
Interviews
4 Cr+
Salaries
1.5 Cr+
Users
Contribute to help millions
AmbitionBox Awards
Get AmbitionBox app

