LeetCode 186: Reverse Words in a String II Solution

Master LeetCode problem 186 (Reverse Words in a String II), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

186. Reverse Words in a String II

Problem Explanation

Explanation:

Given a character array s, reverse the order of characters in each word within the array while still preserving whitespace and initial word order.

Algorithm:

  1. Reverse the entire character array s.
  2. Iterate through the reversed array and for each word, reverse the characters to get the original word order.
  3. Finally, reverse the entire array again to get the correct order of words with reversed characters.

Time Complexity: O(n), where n is the length of the character array s. Space Complexity: O(1)

:

Solution Code

class Solution {
    public void reverseWords(char[] s) {
        reverse(s, 0, s.length - 1);
        
        int start = 0;
        for (int end = 0; end < s.length; end++) {
            if (s[end] == ' ') {
                reverse(s, start, end - 1);
                start = end + 1;
            }
        }
        
        reverse(s, start, s.length - 1);
    }
    
    private void reverse(char[] s, int left, int right) {
        while (left < right) {
            char temp = s[left];
            s[left] = s[right];
            s[right] = temp;
            left++;
            right--;
        }
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 186 (Reverse Words in a String II)?

This page provides optimized solutions for LeetCode problem 186 (Reverse Words in a String II) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 186 (Reverse Words in a String II)?

The time complexity for LeetCode 186 (Reverse Words in a String II) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 186 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 186 in Java, C++, or Python.

Back to LeetCode Solutions