DSA · Strings · #152
Reverse Words in a String
Module 62 · difficulty 3/5·⏱ 30:00starts on first keystroke
Given an input string `s`, reverse the order of the **words**. A *word* is a maximal sequence of non-space characters. The words in `s` are separated by one or more spaces. Return a string with the words in reverse order, joined by a single space. The result must NOT contain leading or trailing spaces, and must collapse any multiple spaces between words into one. Implement `reverseWords(s)` which returns the resulting string.
Examples
s = "the sky is blue"→"blue is sky the"— Words are reversed in order.s = " hello world "→"world hello"— Leading and trailing spaces are removed.s = "a good example"→"example good a"— Multiple inner spaces collapse to one.
Constraints
- · 1 <= s.length <= 10^4
- · s consists of English letters (upper/lower-case), digits, and spaces ' '.
- · There is at least one word in s.
- · Words are separated by one or more space characters.
Session phases
A · Clarify
B · Approach
C · Complexity
D · Edges
E · Code
F · Tradeoff
G · Score
Phase A — Clarify
Ask questions about input bounds, types, and edge constraints.
Ask the coach clarifying questions about the problem.
When you've covered this phase, advance to the next.