Sorting the Sentence - Problem

A sentence is a list of words that are separated by a single space with no leading or trailing spaces. Each word consists of lowercase and uppercase English letters.

A sentence can be shuffled by appending the 1-indexed word position to each word then rearranging the words in the sentence.

For example, the sentence "This is a sentence" can be shuffled as "sentence4 a3 is2 This1" or "is2 sentence4 This1 a3".

Given a shuffled sentence s containing no more than 9 words, reconstruct and return the original sentence.

Input & Output

Example 1 — Basic Case
$ Input: s = "is2 sentence4 This1 Test5 est6"
Output: "This is sentence sentence Test est"
💡 Note: Sort words by their position digits: This1→position 1, is2→position 2, sentence4→position 4, Test5→position 5, est6→position 6.
Example 2 — Different Order
$ Input: s = "Myself2 Me1 I4 and3"
Output: "Me Myself and I"
💡 Note: Rearrange by positions: Me1, Myself2, and3, I4 becomes "Me Myself and I"
Example 3 — Single Word
$ Input: s = "T4est1"
Output: "T4est"
💡 Note: Single word with position 1, just remove the digit to get "T4est"

Constraints

  • s contains only lowercase and uppercase English letters, spaces and digits from 1 to 9
  • All the words in s are separated by a single space
  • s contains between 1 and 9 words, inclusive
  • Each word in s consists of lowercase and uppercase English letters
  • All the words have a unique position digit

Visualization

Tap to expand
Sorting the Sentence INPUT Shuffled Sentence: is2 sentence4 This1 T4est 7est Extract Positions: is 2 sentence 4 This 1 T4est ? 7est ? Position = last digit of each word Input String s: "is2 sentence4 This1 T4est 7est" ALGORITHM STEPS 1 Split by Space Create words array 2 Extract Position Get last char as index 3 Remove Position Strip last digit 4 Place in Array Put word at pos-1 Result Array (1-indexed): This [1] is [2] sentence [4] T4est [?] 7est [?] Join with spaces Concatenate in order Time: O(n) | Space: O(n) FINAL RESULT Reconstructed Sentence: This pos 1 is pos 2 sentence pos 4 T4est pos ? 7est pos ? Order Flow: 1 ---> 2 ---> 3 ---> 4 ---> 5 Output: "This is sentence T4est 7est" OK - Done! Key Insight: The last character of each word is the 1-indexed position. Extract it, remove it from the word, then place the word at position-1 in a result array. Finally, join all words with spaces. Words with digits in the middle (like T4est) keep those digits - only the LAST digit is the position. TutorialsPoint - Sorting the Sentence | Optimal Solution
Asked in
Amazon 15 Microsoft 12
33.9K Views
Medium Frequency
~8 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen