Reverse Words in a String — LeetCode 151 Python Solution
- Problem
- #151
- Pattern
- Two Pointers
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given an input string s, reverse the order of the words. A word is defined as a sequence of non-space characters.
Example
- Input
- s = "the sky is blue"
- Output
- "blue is sky the"
Python solution
class Solution:
def reverseWords(self, s: str) -> str:
words = []
i, n = 0, len(s)
while i < n:
while i < n and s[i] == " ":
i += 1
if i < n:
j = i
while j < n and s[j] != " ":
j += 1
words.append(s[i:j])
i = j
return " ".join(words[::-1])Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Two Pointers
Use the order already in the input to discard half the search space at every step. LeetCode 151. Reverse Words in a String is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.
The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.
Related problems
On study lists
This problem is on LeetCode 75 and Top Interview 150.
Frequently asked questions
- How hard is LeetCode 151. Reverse Words in a String?
- LeetCode 151. Reverse Words in a String is rated Medium on LeetCode.
- What is the time complexity of LeetCode 151. Reverse Words in a String?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 151. Reverse Words in a String?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 151. Reverse Words in a String cover?
- LeetCode 151. Reverse Words in a String is tagged Two Pointers and String on LeetCode.