FastPrepSort Sentence Words

Sort Sentence Words

Infosys logoInfosys● EasyNEW GRADONSITE INTERVIEW
Learn

Problem statement

Given a string sentence containing lowercase English words separated by one or more ASCII spaces, return its words sorted by increasing length.

When two words have the same length, order them lexicographically. Return the ordered words as an array so the result does not depend on reconstructed whitespace.

Function

sortWords(sentence: String) → String[]

Examples

Example 1

sentence = "banana fig apple kiwi"return = ["fig","kiwi","apple","banana"]

The word lengths are 3, 4, 5, and 6, so no tie-breaker is needed.

Example 2

sentence = "pear  plum fig apple"return = ["fig","pear","plum","apple"]

pear and plum both have length 4, so their lexicographic order decides the tie.

Constraints

  • 1 <= number of words <= 100000
  • The total number of non-space characters is at most 500000.
  • Every word contains only lowercase English letters.
  • Adjacent words are separated by one or more ASCII spaces.

More Infosys problems

See Infosys hiring insights
public String[] sortWords(String sentence) {
  // write your code here
}
sentence"banana fig apple kiwi"
expected["fig", "kiwi", "apple", "banana"]
Checking account…