LeetCode solutions

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

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 30ms, memory 17.4MB, accepted 2025-12-29.

python
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)

Source