↓Skip to main content
  1. LeetCode/

LeetCode 151: Reverse Words in a String

·1 min· ·
LeetCode Medium Two-Pointers String
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2022-11-12

  • Submissions: Accepted ×3 → Runtime Error → Wrong Answer ×5 → Accepted

Approach
#

str.split() with no argument splits on runs of whitespace of any length and drops leading and trailing spaces, giving exactly the word list. Reverse it and join with single spaces. With an O(1)-space requirement on a character array, reverse everything and then each word (Two Pointers Template 1).

My Attempts
#

It passed in 2022. A 2026 rewrite used split(" "), which produces empty strings for consecutive spaces: "b b" returned "b b" (still two spaces) and "b " returned " b"; one version also forgot the separating space, turning "a b" into "ba".

Solution
#

class Solution:
    def reverseWords(self, s: str) -> str:
        return " ".join(reversed(s.split()))

Complexity
#

Time O(n), space O(n).

Mistakes to Avoid
#

  • split(" ") produces empty strings for consecutive spaces; split() does not.

Interview Explanation
#

Calling split() with no argument yields the words with all extra spaces handled, and I join them reversed with single spaces. Time O(n).

Related

LeetCode 647: Palindromic Substrings
·1 min
LeetCode Medium Two-Pointers String Dynamic-Programming
LeetCode 647 note: expand around centers, counting one palindromic substring for each successful expansion
LeetCode 5: Longest Palindromic Substring
·2 mins
LeetCode Medium Two-Pointers String Dynamic-Programming Manacher
LeetCode 5 note: expand around centers, using each position as an odd and an even center; with interval DP, iterate i from large to small
LeetCode 189: Rotate Array
·2 mins
LeetCode Medium Array Math Two-Pointers
LeetCode 189 note: take k %= n, then reverse three times: the whole array, the first k, and the last n - k, with O(1) extra space
LeetCode 93: Restore IP Addresses
·2 mins
LeetCode Medium String Backtracking
LeetCode 93 note: cut into exactly 4 pieces, each 1 to 3 digits long, valued 0 to 255, with no leading zero except 0 itself
LeetCode 131: Palindrome Partitioning
·2 mins
LeetCode Medium String Dynamic-Programming Backtracking
LeetCode 131 note: each level cuts a palindrome from the front of the remaining string, trying every length from 1 to the whole remainder
LeetCode 143: Reorder List
·2 mins
LeetCode Medium Linked-List Two-Pointers Stack Recursion
LeetCode 143 note: find the middle, reverse the second half, and merge the two alternately, cutting the first half’s tail