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 III

Number: 557

Difficulty: Easy

Paid? No

Companies: Yandex, Amazon, Salesforce, Zappos


Problem Description

Given a string s, reverse the order of characters in each word while preserving the whitespace and the original order of the words.


Key Insights

  • The problem can be approached by splitting the string using the space character.
  • Each word should be individually reversed while the overall order of the words remains the same.
  • After processing each word, the words can be concatenated back with a single space.
  • This approach leverages simple string manipulation and iteration.

Space and Time Complexity

Time Complexity: O(n), where n is the length of the string.
Space Complexity: O(n), due to storing the split words and reversed words.


Solution

The solution involves:

  1. Splitting the input string s into a list of words using the space as a delimiter.
  2. Reversing each word in the list.
  3. Joining the reversed words with a space to form the final string. The main data structure used is an array (list) to store words. The algorithm is straightforward and involves iterating over each word and reversing it, which ensures a linear time complexity. The mental leap is recognizing that reversing the characters of each word can be done independently and then reassembled with preserved spaces.

Code Solutions

# Function to reverse words in a string
def reverseWords(s: str) -> str:
    # Split the string into words using space as delimiter
    words = s.split(" ")
    # For each word, reverse its characters
    reversed_words = [word[::-1] for word in words]
    # Join the reversed words with a space and return the result
    return " ".join(reversed_words)

# Example usage:
input_str = "Let's take LeetCode contest"
print(reverseWords(input_str))  # Output: "s'teL ekat edoCteeL tsetnoc"
← Back to All Questions