Reverse Words in a String

Given a string s, reverse the order of its words. A word is a maximal run of non-space characters. The result must contain the words in reverse order separated by exactly one space: leading and trailing spaces are removed, and runs of several spaces between words collapse to a single space.

30:00

Reverse Words in a String
medium
Free written solution
Topics
Companies

Given a string s, reverse the order of its words. A word is a maximal run of non-space characters. The result must contain the words in reverse order separated by exactly one space: leading and trailing spaces are removed, and runs of several spaces between words collapse to a single space.

Example 1:
Input: {"s":"the sky is blue"}
Output: blue is sky the
Constraints:
  • 1≤s.length≤1041 \leq s.length \leq 10^4

  • s contains English letters (upper-case and lower-case), digits, and spaces

  • There is at least one word in s

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"s":"the sky is blue"}

Read s from the right end, so the last word is found first. Start i at index 14; words collects them in the order they are met.

s, read right to left

t

0

h

1

e

2

·

3

s

4

k

5

y

6

·

7

i

8

s

9

·

10

b

11

l

12

u

13

e

14

i

▲

· = space

■ spaces being skipped

■ word being read

colored = taken

words 0

spaces dropped 0

words (in the order they were found)

Empty so far.

Variables
VariableValue
i14
n15
DepthFunction Call
Stack empty
0/13