Pankaj Tanwar
Published on

Sorting the Sentence.


Problem of the day - Sorting the Sentence

Tag - Easy

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.

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.

At first, the problem seemed very tricky. I love such problems. Here, it's not about the logic, it's about how well you write the code.

By looking at the problem statement, you will immediately get the logic and it will seem pretty easy to you to code it. But, when you start writing the code, you end up messing it up due to some tricky corner cases.

So, here is my approach -

  • As, max words possible are 9 so, initialize an array of the same length
  • Check if, next to next element is space or end of the word, (means, next element is the index value), just put the current word to index position in the list
  • Iterate over the list, and return the result.

Here is the code -

class Solution {
string sortSentence(string s) {
vector<string> list(9);
string word = "";
string res = "";
int index;
int words = 0;
for(int i=0;i<s.length();i++) {
word += s[i];
if(i+2 == s.length() || s[i+2] == ' ') {
index = s[i+1] - '1';
list[index] = word;
word = "";
i += 2;
for(int i=0;i<words;i++) {
string str = list[i];
res += str + (i == words-1 ? "" : " ");
return res;

I know, code might seem ugly, please do let me know if you have a better approach. I would love to talk.

Thanks for being part of my daily-code-workout journey. As always, if you have any thoughts about anything shared above, don't hesitate to reach out.

You might like previous editions of my coding diary