We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Reverse Words in a String

Number: 151

Difficulty: Medium

Paid? No

Companies: Amazon, Google, Meta, Microsoft, Apple, Bloomberg, Nvidia, tcs, Infosys, Accenture, Oracle, TikTok, Adobe, Qualcomm, Walmart Labs, Arista Networks, Wayfair, Morgan Stanley, HPE, Snap, Yelp


Problem Description

Given an input string s, reverse the order of the words. A word is defined as a sequence of non-space characters. Words in the string are separated by at least one space. The output should have words in reverse order, concatenated by a single space each, with no leading or trailing spaces or extra spaces between words.


Key Insights

  • Use built-in functions to trim and split the string by spaces.
  • Reverse the list of words.
  • Join the reversed list using a single space.
  • Handle edge cases such as multiple spaces between words and leading/trailing spaces.
  • In languages with mutable strings, consider an in-place algorithm for O(1) extra space as a follow-up.

Space and Time Complexity

Time Complexity: O(n), where n is the length of the input string. Space Complexity: O(n), to store the split words (unless an in-place algorithm is implemented).


Solution

The main idea is to clean up the string by removing extra spaces and then split the string into words. After obtaining a list of words, we simply reverse the list and join the words with a single space between them. This approach leverages string trimming, splitting, reversing, and joining, which are available in many programming languages. A potential gotcha is ensuring that no extra spaces are left in the output, which is handled by trimming and using the join function appropriately.


Code Solutions

# Python solution
def reverseWords(s: str) -> str:
    # Split the string by spaces; this automatically handles multiple spaces and trimming
    words = s.split()
    # Reverse the list of words
    words.reverse()
    # Join the reversed words with a single space and return the result
    return " ".join(words)

# Example usage
if __name__ == "__main__":
    s = "  hello world  "
    print(reverseWords(s))  # Expected output: "world hello"
← Back to All Questions