> For the complete documentation index, see [llms.txt](https://code-snippets.hbamithkumara.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://code-snippets.hbamithkumara.com/leetcode/problems/101-200/reverse-words-in-a-string-ii.md).

# 186. Reverse Words in a String II

### Description

&#x20;Given an input string , reverse the string word by word.&#x20;

**Note:**&#x20;

* A word is defined as a sequence of non-space characters.
* The input string does not contain leading or trailing spaces.
* The words are always separated by a single space.

**Follow up:** Could you do it in-place without allocating extra space?

### Constraints

### Approach

*Reverse the Whole String and Then Reverse Each Word*

<div align="left"><img src="/files/-MIZA1mZDrdXXk4tfBh4" alt=""></div>

### Links

* GeeksforGeeks
* [Leetcode](https://leetcode.com/problems/reverse-words-in-a-string-ii/)
* [ProgramCreek](https://www.programcreek.com/2014/05/leetcode-reverse-words-in-a-string-ii-java/)
* YouTube

### **Examples**

{% tabs %}
{% tab title="Example 1" %}
**Input:** \["t", "h", "e", " ", "s", "k", "y", " ", "i", "s", " ", "b", "l", "u", "e"]

**Output:** \["b", "l", "u", "e", " ", "i", "s", " ", "s", "k", "y", " ", "t", "h", "e"]
{% endtab %}
{% endtabs %}

### **Solutions**

{% tabs %}
{% tab title="Solution 1" %}

```java
/**
 * Time complexity : O(N), it's two passes along the string.
 * Space complexity : O(1), it's a constant space solution.
 */

class Solution {
    public void reverseWords(char[] s) {
        if(s == null || s.length == 0) return;
        
        // reverse the whole string
        reverse(s, 0, s.length-1);
        
        // reverse each word
        reverseEachWord(s);
    }
    
    private void reverse(char[] chars, int left, int right) {
        while(left < right) {
            char tmp = chars[left];
            chars[left++] = chars[right];
            chars[right--] = tmp;
        }
    }
    
    private void reverseEachWord(char[] chars) {
        int n = chars.length;
        int start = 0, end = 0;
        
        while(start < n) {
            // go to the end of the word
            while(end < n && chars[end] != ' ') {
                end++;
            }
            // reverse the word
            reverse(chars, start, end-1);
            // move to the next word
            end++;
            start = end;
        }
    }
}
```

{% endtab %}
{% endtabs %}

### **Follow up**

*
