1970. Sorting the Sentence
My accepted Python solution to LeetCode problem 1970, Sorting the Sentence, running in 30ms.
- Difficulty: Easy
- Python
- Runtime 30ms
- Memory 17.4MB
- Updated
Read the problem on LeetCode View on GitHub
The problem statement is LeetCode’s and stays on their site. What follows is my accepted solution.
Python
Accepted on LeetCode — runtime 30ms, memory 17.4MB, accepted 2025-12-29.
class Solution:
def sortSentence(self, s: str) -> str:
# Split, sort by the number at end, remove numbers
# Time: O(n log n), Space: O(n)
words = s.split()
# Sort by the last character (which is the position number)
words.sort(key=lambda w: w[-1])
# Remove the position number from each word
return ' '.join(w[:-1] for w in words)