Leetcode #1859: Sorting the Sentence
In this guide, we solve Leetcode #1859 Sorting the Sentence in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Easy
- Premium: No
- Tags: String, Sorting
Intuition
Sorting reveals structure that is hard to see in the original order.
Once sorted, a linear scan is usually enough to compute the answer.
Approach
Sort the data and sweep through it while maintaining a small state.
This keeps the logic straightforward and reliable.
Steps:
- Sort the data.
- Scan in order while maintaining state.
- Update the best answer.
Example
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.
Python Solution
class Solution:
def sortSentence(self, s: str) -> str:
ws = s.split()
ans = [None] * len(ws)
for w in ws:
ans[int(w[-1]) - 1] = w[:-1]
return " ".join(ans)
Complexity
The time complexity is , and the space complexity is , where is the length of the string . The space complexity is , where is the length of the string .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.