FastPrepReverse Words in a String

Reverse Words in a String

Bloomberg LP logoBloomberg LP● MediumNEW GRADPHONE SCREEN
Learn

Problem statement

Given a string s containing words and spaces, return the words in reverse order.

A word is a maximal sequence of non-space characters. The returned string must contain exactly one space between adjacent words and no leading or trailing spaces.

Function

reverseWords(s: String) → String

Examples

Example 1

s = "the sky is blue"return = "blue is sky the"

The four words appear in the opposite order, separated by one space.

Example 2

s = "  hello world  "return = "world hello"

Leading and trailing spaces are discarded before the two words are reversed.

Example 3

s = "a good   example"return = "example good a"

Multiple spaces between input words become a single space in the result.

Constraints

  • 1 <= s.length <= 100000.
  • s contains English letters, digits, punctuation, and space characters.
  • s contains at least one word.

More Bloomberg LP problems

See Bloomberg LP hiring insights
public String reverseWords(String s) {
    // Write your code here.
}
s"the sky is blue"
expected"blue is sky the"
Checking account…