Problem Description
A sentence is a list of words separated by a single space, where each word has an appended digit representing its original position. Given such a shuffled sentence, the goal is to rearrange the words in their correct order and then remove the digits, returning the restored sentence.
Key Insights
- Each word ends with a digit indicating its position.
- The sentence can be split into individual words.
- Sorting the list of words using the digit (last character) as the key reorders them to their original positions.
- Once sorted, removing the trailing digit from each word yields the final sentence.
Space and Time Complexity
Time Complexity: O(n log(n)) due to sorting the words, though n is at most 9. Space Complexity: O(n) to store the split words.
Solution
The approach is straightforward:
- Split the sentence into words by spaces.
- Sort the words by converting the last character (which is a digit) to an integer and using it as the key.
- Remove the last character (digit) from each word after sorting.
- Join the modified words with spaces to form the original sentence.
Key data structures used: array (or list) to store the words, and built-in sort functions available in most languages.