Magicsheet logo

Sorting the Sentence

Easy
12.5%
Updated 8/1/2025

Sorting the Sentence

What is this problem about?

"Sorting the Sentence" is a "Easy" difficulty string manipulation problem. A sentence has been shuffled such that each word has a number (1 to 9) appended to it, representing its original position. Your goal is to reconstruct the original sentence by removing the numbers and placing the words in the correct order.

For example, the string "is2 sentence4 This1 a3" should be transformed back into "This is a sentence". This problem tests basic string splitting, extraction, and sorting.

Why is this asked in interviews?

Companies like Microsoft and Bloomberg ask this to check a candidate's fluency with string and list operations. It evaluates whether you can parse strings effectively, handle index conversions (e.g., converting a 1-based string index into a 0-based array index), and join strings with spaces. It’s a classic warm-up question that assesses attention to detail and clean code practices.

Algorithmic pattern used

The pattern used is String Parsing and Bucket Placement.

  1. Split: Divide the input string into a list of words based on spaces.
  2. Parse: For each word, extract the number at the end and the word itself.
  3. Place: Use an array (or a dictionary) to store the words at the correct indices (position - 1).
  4. Join: Combine the words in the array with spaces between them.

Example explanation

Input: "Myself2 Me1 I3"

  1. Split: ["Myself2", "Me1", "I3"]
  2. Process "Myself2": Word="Myself", Pos=2. Place at index 1.
  3. Process "Me1": Word="Me", Pos=1. Place at index 0.
  4. Process "I3": Word="I", Pos=3. Place at index 2.
  5. Array: ["Me", "Myself", "I"]
  6. Join: "Me Myself I" Result: "Me Myself I".

Common mistakes candidates make

One common mistake is incorrectly extracting the number (e.g., assuming it's always at index -1, which is true for 1-9, but might be different if numbers were larger). Another error is using the position as the direct index (e.g., placing "Me1" at index 1 instead of 0), which results in a leading space or an out-of-bounds error. Finally, using a full sort on the words based on the number is slightly less efficient than a simple O(N)O(N) placement into a fixed-size array.

Interview preparation tip

When tackling the "Sorting the Sentence coding problem," remember that you don't necessarily need a sorting algorithm. Since the positions are 1 to NN, you can use a list as a "bucket" to place everything in O(N)O(N) time. This is faster and more direct. Also, make sure to use a string builder or a join function to avoid the O(N2)O(N^2) complexity of repeated string concatenation in certain languages.

Similar Questions