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:
- Parse each word and extract its position number
- Sort the words according to their positions
- 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 -
sconsists of lowercase and uppercase English letters, spaces, and digits from 1 to 9 -
The number of words in
sis between 1 and 9 -
The words in
sare 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
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.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code