Sorting the Sentence (LeetCode 1859): Solution and Explanation
A sentence of up to 9 words was shuffled after each word had its 1-based position appended to it. Given the shuffled string, return the original sentence with the digits removed.
Intuition
It looks like a sorting problem, but every word already carries its final index. There is nothing to compare: the last character of a word says exactly where it goes.
So the job is placement, not sorting. Make one empty slot per word, put each word into the slot its digit names, and read the slots from left to right.
Approach: Place by position digit
- Split
son spaces to get the shuffled words. - Create an array
slotswith one entry per word. - For each word, read its last character as the position
dand store the word without that character inslots[d - 1]. - Join
slotswith single spaces and return it.
Step-by-step example
s = "is2 sentence4 This1 a3"
- Splitting gives four words, so make four empty slots.
- "is2" ends in 2, so slot 2 gets "is".
- "sentence4" ends in 4, so slot 4 gets "sentence".
- "This1" goes to slot 1 and "a3" goes to slot 3.
- The slots read "This", "is", "a", "sentence". Joined: "This is a sentence".
Code: Python, Java, C++
1class Solution:
2 def sortSentence(self, s: str) -> str:
3 words = s.split()
4 slots = [''] * len(words)
5 for w in words:
6 slots[int(w[-1]) - 1] = w[:-1]
7 return ' '.join(slots)1class Solution {
2 public String sortSentence(String s) {
3 String[] words = s.split(" ");
4 String[] slots = new String[words.length];
5 for (String w : words) {
6 int pos = w.charAt(w.length() - 1) - '1';
7 slots[pos] = w.substring(0, w.length() - 1);
8 }
9 return String.join(" ", slots);
10 }
11}1class Solution {
2public:
3 string sortSentence(string s) {
4 istringstream ss(s);
5 vector<string> slots(9);
6 string w;
7 int count = 0;
8 while (ss >> w) {
9 slots[w.back() - '1'] = w.substr(0, w.size() - 1);
10 count++;
11 }
12 string res;
13 for (int i = 0; i < count; i++) {
14 if (i > 0) res += ' ';
15 res += slots[i];
16 }
17 return res;
18 }
19};Time and space complexity
O(n)
Splitting, placing and joining each touch every character of the sentence a constant number of times.
O(n)
The split words and the slots together hold the whole sentence.
Other approaches
Sort by the last character (time O(n + k log k), space O(n))
Sort the words with the last character as the key, then strip it from each. It is short to write but does O(k log k) comparisons for k words where direct placement needs none.
Common mistakes
- Forgetting that positions are 1-based. The word ending in 1 belongs at index 0.
- Leaving the digit on the word, or stripping every digit when only the last character is the position.
- Adding a trailing space when building the result by hand instead of joining.
Frequently asked questions
Why is a single digit always enough for the position?
The sentence has at most 9 words, so every position is between 1 and 9 and fits in one character.
Do I need to sort at all?
No. The digit is the final index, so each word can be written straight into its slot in one pass.
Does letter case matter?
No. Words keep their case exactly as given; only the digit is removed.