FastPrepReverse Word Order In Place

Reverse Word Order In Place

Microsoft logoMicrosoft● MediumFULLTIMEPHONE SCREEN
Learn

Problem statement

Given a mutable character array chars representing a sentence, reverse the order of its words while keeping the characters inside each word in their original order. Modify the supplied array in place using constant auxiliary workspace, then return the same array.

Every word contains ASCII letters. Adjacent words are separated by exactly one ASCII space, with no leading or trailing space. An empty array represents an empty sentence.

Function

reverseWordOrderInPlace(chars: char[]) → char[]

Examples

Example 1

chars = ["s","k","y"," ","i","s"," ","b","l","u","e"]return = ["b","l","u","e"," ","i","s"," ","s","k","y"]

Reverse three words without reversing their letters.

Example 2

chars = ["M","L"]return = ["M","L"]

A single word has no word-order change.

Example 3

chars = []return = []

The empty character array has no words.

Constraints

  • 0 <= chars.length <= 2000.
  • Each nonempty word contains only A-Z or a-z.
  • Words are separated by one space and there are no leading or trailing spaces.

More Microsoft problems

See Microsoft hiring insights
public char[] reverseWordOrderInPlace(char[] chars) {
    // Reverse the word order in place.
}
chars["s","k","y"," ","i","s"," ","b","l","u","e"]
expected["b","l","u","e"," ","i","s"," ","s","k","y"]
Checking account…