EasyNo. 1859

Sorting the Sentence — LeetCode 1859 Python Solution

Pattern
Sorting
Topics
String, Sorting
Reading time
2 min

The problem

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.

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

PythonSolution
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

Time
O(n)
Space · auxiliary
O(n)where n is the length of the string s

Pattern: Sorting

Spend O(n log n) once to buy an ordering that makes the rest of the problem trivial. LeetCode 1859. Sorting the Sentence is filed here because LeetCode tags it Sorting, which is the vocabulary this hub collects.

The sorting guide has the Python template for the pattern and the 401 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0539Minimum Time DifferenceMedium
0899Orderly QueueHard
0937Reorder Data in Log FilesMedium
1451Rearrange Words in a SentenceMedium
2785Sort Vowels in a StringMedium
0056Merge IntervalsMedium

Frequently asked questions

How hard is LeetCode 1859. Sorting the Sentence?

LeetCode 1859. Sorting the Sentence is rated Easy on LeetCode.

What is the time complexity of LeetCode 1859. Sorting the Sentence?

The Python solution on this page runs in O(n).

What is the space complexity of LeetCode 1859. Sorting the Sentence?

The Python solution on this page uses O(n), where n is the length of the string s auxiliary space.

What topics does LeetCode 1859. Sorting the Sentence cover?

LeetCode 1859. Sorting the Sentence is tagged String and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.