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 T4est 7est"
Output: "This is sentence T4est 7est"
💡 Note: Sort words by their position digits: This1→position 1, is2→position 2, sentence4→position 4, etc.
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: Reconstruct from ShuffledInput (Shuffled)is2sentence4This1↓ Extract positions and rearrange ↓Output (Sorted)Thisissentencepos 1pos 2pos 4Result: "This is sentence"
Understanding the Visualization
1
Input
Shuffled sentence with position digits: "is2 sentence4 This1"
2
Process
Extract position from each word and place in correct order
3
Output
Reconstructed original sentence: "This is sentence"
Key Takeaway
🎯 Key Insight: Each word encodes its correct position as the last character - extract and place directly!
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