Reverse Words in a String - JavaScript Solution with O(n) Time Complexity


Given an input string s, reverse the order of the words.

A word is defined as a sequence of non-space characters. The words in s will be separated by one space for simplicity.

Return a string of the words in reverse order concatenated by a single space.

Example:

Input:  input = "sky is blue"

Output:  "blue is sky"

Understanding the Problem

The core challenge of this problem is to reverse the order of words in a given string. This is a common problem in text processing and has applications in various fields such as natural language processing and data formatting. A potential pitfall is to mistakenly reverse the characters within the words instead of reversing the order of the words themselves.

Approach

To solve this problem, we can follow these steps:

  1. Split the input string into an array of words.
  2. Reverse the array of words.
  3. Join the reversed array back into a single string with spaces separating the words.

Let's discuss a naive solution and then move on to an optimized solution.

Naive Solution

The naive solution involves manually iterating through the string to identify words and then constructing the reversed string. This approach is not optimal due to its complexity and potential for errors.

Optimized Solution

The optimized solution leverages built-in JavaScript methods to achieve the desired result efficiently:

  1. Use the split() method to convert the string into an array of words.
  2. Use the reverse() method to reverse the array.
  3. Use the join() method to concatenate the words back into a single string.

Algorithm

Here is a step-by-step breakdown of the optimized algorithm:

  1. Split the input string s by spaces to get an array of words.
  2. Reverse the array of words.
  3. Join the reversed array into a single string with spaces separating the words.

Code Implementation

// Function to reverse the words in a string
function reverseWords(s) {
    // Step 1: Split the string into an array of words
    const wordsArray = s.split(' ');
    
    // Step 2: Reverse the array of words
    const reversedArray = wordsArray.reverse();
    
    // Step 3: Join the reversed array into a single string
    const reversedString = reversedArray.join(' ');
    
    // Return the reversed string
    return reversedString;
}

// Example usage
const input = "sky is blue";
const output = reverseWords(input);
console.log(output); // Output: "blue is sky"

Complexity Analysis

The time complexity of this solution is O(n), where n is the length of the input string. This is because the split(), reverse(), and join() methods each operate in linear time. The space complexity is also O(n) due to the storage required for the array of words.

Edge Cases

Consider the following edge cases:

  • Empty string: The function should return an empty string.
  • String with one word: The function should return the same word.
  • String with multiple spaces between words: The function should handle multiple spaces correctly.

Examples:

console.log(reverseWords("")); // Output: ""
console.log(reverseWords("hello")); // Output: "hello"
console.log(reverseWords("  hello   world  ")); // Output: "world hello"

Testing

To test the solution comprehensively, consider using a variety of test cases:

  • Simple cases with a few words.
  • Edge cases such as empty strings and strings with one word.
  • Complex cases with multiple spaces and special characters.

Example test cases:

console.log(reverseWords("sky is blue")); // Output: "blue is sky"
console.log(reverseWords("hello world")); // Output: "world hello"
console.log(reverseWords("a b c d e")); // Output: "e d c b a"

Thinking and Problem-Solving Tips

When approaching such problems, consider the following tips:

  • Break down the problem into smaller, manageable steps.
  • Leverage built-in methods and libraries to simplify your solution.
  • Think about edge cases and how your solution handles them.
  • Practice similar problems to improve your problem-solving skills.

Conclusion

In this blog post, we discussed how to reverse the words in a string using JavaScript. We covered the problem definition, approach, algorithm, code implementation, complexity analysis, edge cases, and testing. Understanding and solving such problems is crucial for improving your coding skills and preparing for technical interviews. Keep practicing and exploring further to enhance your problem-solving abilities.

Additional Resources

For further reading and practice, consider the following resources: