Sorting the Sentence
EasyUpdated: Sep 1, 2025
Practice on:
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.
Examples
Example 1
Input: s = "is2 sentence4 This1 a3"
Output: "This is a sentence"
Explanation: Sort the words in s to their original positions "This1 is2 a3 sentence4", then remove the numbers.
Example 2
Input: s = "Myself2 Me1 I4 and3"
Output: "Me Myself and I"
Explanation: Sort the words in s to their original positions "Me1 Myself2 and3 I4", then remove the numbers.
Constraints
2 <= s.length <= 200sconsists of lowercase and uppercase English letters, spaces, and digits from1to9.- The number of words in
sis between1and9. - The words in
sare separated by a single space. scontains no leading or trailing spaces.
Solution
Method 1 - Array Placement
Intuition
Since each word has a number (1-9) indicating its position, we can directly place each word in the correct position in an array and then join them.
Approach
- Split the input string into words
- Create an array of size equal to number of words
- For each word, extract the last character (position number) and place the word (without the number) at that position
- Join the words to form the final sentence
Code
C++
#include <string>
#include <vector>
#include <sstream>
using namespace std;
string sortSentence(string s) {
istringstream iss(s);
string word;
vector<string> words;
while (iss >> word) {
words.push_back(word);
}
vector<string> result(words.size());
for (const string& w : words) {
int pos = w.back() - '1'; // Convert to 0-indexed
result[pos] = w.substr(0, w.length() - 1); // Remove the number
}
string answer = "";
for (int i = 0; i < result.size(); i++) {
if (i > 0) answer += " ";
answer += result[i];
}
return answer;
}
Go
import (
"strconv"
"strings"
)
func sortSentence(s string) string {
words := strings.Split(s, " ")
result := make([]string, len(words))
for _, word := range words {
pos, _ := strconv.Atoi(string(word[len(word)-1]))
result[pos-1] = word[:len(word)-1] // Remove the number, convert to 0-indexed
}
return strings.Join(result, " ")
}
Java
class Solution {
public String sortSentence(String s) {
String[] words = s.split(" ");
String[] result = new String[words.length];
for (String word : words) {
int pos = word.charAt(word.length() - 1) - '1'; // Convert to 0-indexed
result[pos] = word.substring(0, word.length() - 1); // Remove the number
}
return String.join(" ", result);
}
}
Kotlin
class Solution {
fun sortSentence(s: String): String {
val words = s.split(" ")
val result = Array(words.size) { "" }
for (word in words) {
val pos = word.last().digitToInt() - 1 // Convert to 0-indexed
result[pos] = word.dropLast(1) // Remove the number
}
return result.joinToString(" ")
}
}
Python
def sortSentence(s: str) -> str:
words = s.split()
result = [''] * len(words)
for word in words:
pos = int(word[-1]) - 1 # Convert to 0-indexed
result[pos] = word[:-1] # Remove the number
return ' '.join(result)
Rust
pub fn sort_sentence(s: String) -> String {
let words: Vec<&str> = s.split_whitespace().collect();
let mut result = vec![String::new(); words.len()];
for word in words {
let pos = word.chars().last().unwrap().to_digit(10).unwrap() as usize - 1;
result[pos] = word[..word.len()-1].to_string();
}
result.join(" ")
}
TypeScript
function sortSentence(s: string): string {
const words = s.split(' ');
const result: string[] = new Array(words.length);
for (const word of words) {
const pos = parseInt(word[word.length - 1]) - 1; // Convert to 0-indexed
result[pos] = word.slice(0, -1); // Remove the number
}
return result.join(' ');
}
Complexity
- ⏰ Time complexity:
O(n)where n is the length of the input string (single pass through words) - 🧺 Space complexity:
O(n)for storing the words and result array