Sorting the Sentence - Problem

Given a shuffled sentence where each word has been appended with its 1-indexed position, your task is to reconstruct the original sentence.

In a shuffled sentence, each word ends with a digit (1-9) that indicates its correct position in the original sentence. For example:

  • Original: "This is a sentence"
  • Shuffled: "sentence4 a3 is2 This1"

Your goal is to:

  1. Parse each word and extract its position number
  2. Sort the words according to their positions
  3. Remove the position numbers and reconstruct the sentence

Input: A shuffled sentence s with no more than 9 words
Output: The original sentence with words in correct order

Input & Output

example_1.py — Basic Example
$ Input: s = "is2 sentence4 This1 a3"
Output: "This is a sentence"
💡 Note: The words with positions: This1→1st, is2→2nd, a3→3rd, sentence4→4th. After removing digits and sorting by position: 'This is a sentence'
example_2.py — Single Word
$ Input: s = "Myself1"
Output: "Myself"
💡 Note: Only one word 'Myself' at position 1. After removing the digit: 'Myself'
example_3.py — Already Sorted
$ Input: s = "T1 h2 e3"
Output: "T h e"
💡 Note: Even if words are already in order, we still need to remove the position digits

Constraints

  • 2 ≤ s.length ≤ 200
  • s consists of lowercase and uppercase English letters, spaces, and digits from 1 to 9
  • The number of words in s is between 1 and 9
  • The words in s are separated by a single space
  • s does not have leading or trailing spaces
  • All the words have exactly one digit at the end representing their position

Visualization

Tap to expand
Library Book Organization AnalogyStep 1: Scattered books with position labelsHistory1Novel4Math3Science2Step 2: Prepare numbered shelf positionsPosition 1Position 2Position 3Position 4Step 3: Direct placement by reading position numbersHistoryScienceMathNovelStep 4: Final organized result (labels removed)HistoryScienceMathNovelResult: "History Science Math Novel"
Understanding the Visualization
1
Scattered Books
Books are scattered with position numbers: 'Novel4', 'History1', 'Math3', 'Science2'
2
Prepare Shelves
Set up 4 empty shelf positions: [_, _, _, _]
3
Direct Placement
Read each book's number and place it directly: History→pos1, Science→pos2, Math→pos3, Novel→pos4
4
Remove Labels
Remove the position sticky notes to get the clean, organized result
Key Takeaway
🎯 Key Insight: Since positions are numbered 1-9, we can use direct indexing (O(n)) instead of sorting algorithms (O(n log n)), making this more efficient than traditional sorting approaches.
Asked in
Amazon 15 Google 12 Microsoft 8 Meta 6
24.2K 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