Problem · String
Sort Sentence Words
Learn this problemProblem 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
- Swap Two Numbers Without a Third VariableONSITE INTERVIEW · Seen Aug 2026
- Count Valid A-B-C Sequences Under a Modulo-Four RuleOA · Seen Aug 2026
- Maximum Product of a Strictly Increasing Contiguous SubarrayOA · Seen Aug 2026
- Minimum Cost to Assign Candidates to Two CitiesOA · Seen Aug 2026
- Merge Two Sorted Arrays In PlaceONSITE INTERVIEW · Seen Jul 2026
- Minimum Coins for a TargetONSITE INTERVIEW · Seen Jul 2026
- Minimum Path Sum With Grid SwitchesONSITE INTERVIEW · Seen May 2026
- Maximum Subarray Sum After SwapsOA · Seen Feb 2026