Skip to content

Commit 773f2fd

Browse files
committed
Reverse words in a String
1 parent 67de492 commit 773f2fd

File tree

4 files changed

+202
-0
lines changed

4 files changed

+202
-0
lines changed
Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,133 @@
1+
# 151. Reverse Words in a String
2+
3+
**Difficulty:** *Easy*
4+
**Category:** *Strings, Stack, Two Pointers*
5+
**Leetcode Link:** [Problem Link](https://leetcode.com/problems/reverse-words-in-a-string/)
6+
7+
---
8+
9+
## 📝 Introduction
10+
11+
Given a string `s`, reverse the order of words in it. A word is defined as a sequence of non-space characters. The words in `s` are separated by one or more spaces. The output string should only contain a single space separating the words, and no leading or trailing spaces.
12+
13+
---
14+
15+
## 💡 Approach & Key Insights
16+
17+
The main idea is to reverse the order of the words, not the characters within them. We explore multiple approaches starting from brute force using a stack to a space-optimized method that constructs the result while traversing the string from the end.
18+
19+
---
20+
21+
## 🛠️ Breakdown of Approaches
22+
23+
### 1️⃣ Brute Force / Naive Approach
24+
25+
- **Explanation:**
26+
Push each word onto a stack while traversing the string. This reverses the order naturally. Then pop from the stack and build the output string. Stack ensures LIFO behavior to reverse the word order.
27+
28+
- **Time Complexity:** *O(N)* - We traverse the entire string once and then build the result string from the stack.
29+
- **Space Complexity:** *O(N)* - Additional space for the stack and the answer string.
30+
31+
- **Example/Dry Run:**
32+
33+
```plaintext
34+
Input: "TUF is great for interview preparation"
35+
36+
Step 1 → Push each word into a stack:
37+
Stack = ["TUF", "is", "great", "for", "interview", "preparation"]
38+
39+
Step 2 → Pop and build answer:
40+
"preparation interview for great is TUF"
41+
42+
Output: "preparation interview for great is TUF"
43+
```
44+
45+
---
46+
47+
### 2️⃣ Optimized Approach
48+
49+
- **Explanation:**
50+
Traverse the string from the end, constructing each word in reverse. Append each complete word to the result as we detect spaces. This eliminates the need for a stack. We carefully manage whether a space is needed before appending each word.
51+
52+
- **Time Complexity:** *O(N)* - Single traversal of the string.
53+
- **Space Complexity:** *O(1)* - We only use a few extra variables (not counting the output string).
54+
55+
- **Example/Dry Run:**
56+
57+
```plaintext
58+
Input: "TUF is great for interview preparation"
59+
60+
Step 1 → Start from end:
61+
"preparation" → add to result
62+
"interview" → prepend to result
63+
"for" → prepend
64+
"great" → prepend
65+
"is" → prepend
66+
"TUF" → prepend
67+
68+
Final Output: "preparation interview for great is TUF"
69+
```
70+
71+
---
72+
73+
### 3️⃣ Best / Final Optimized Approach (if applicable)
74+
75+
- **Explanation:**
76+
The two-pointer approach traverses from end to start, building words and appending them to the result string efficiently. It avoids stack overhead and minimizes space usage.
77+
78+
- **Time Complexity:** *O(N)*
79+
- **Space Complexity:** *O(1)* (excluding result string)
80+
81+
- **Example/Dry Run:**
82+
83+
```plaintext
84+
Input: " Hello World "
85+
86+
Trim extra spaces
87+
Traverse from the end
88+
Build each word and append
89+
Final Output: "World Hello"
90+
```
91+
92+
---
93+
94+
## 📊 Complexity Analysis
95+
96+
| Approach | Time Complexity | Space Complexity |
97+
| ------------- | --------------- | ---------------- |
98+
| Brute Force | O(N) | O(N) |
99+
| Optimized | O(N) | O(1) |
100+
| Best Approach | O(N) | O(1) |
101+
102+
---
103+
104+
## 📉 Optimization Ideas
105+
106+
- Modify the input string in-place if mutable (e.g., using character arrays in C++).
107+
- Skip multiple spaces early using regex or manual trimming.
108+
109+
---
110+
111+
## 📌 Example Walkthroughs & Dry Runs
112+
113+
```plaintext
114+
Example:
115+
Input: "TUF is great for interview preparation"
116+
Process:
117+
1. Extract words: ["TUF", "is", "great", "for", "interview", "preparation"]
118+
2. Reverse order: ["preparation", "interview", "for", "great", "is", "TUF"]
119+
3. Join with single spaces
120+
Output: "preparation interview for great is TUF"
121+
```
122+
123+
---
124+
125+
## 🔗 Additional Resources
126+
127+
128+
- [C++ String Functions](https://cplusplus.com/reference/string/string/)
129+
130+
---
131+
132+
Author: Abdul Wahab
133+
Date: 19/07/2025
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
class Solution {
2+
public:
3+
string reverseWords(string s) {
4+
int left = 0;
5+
int right = s.length()-1;
6+
7+
string temp="";
8+
string ans="";
9+
10+
//Iterate the string and keep on adding to form a word
11+
//If empty space is encountered then add the current word to the result
12+
while (left <= right) {
13+
char ch= s[left];
14+
if (ch != ' ') {
15+
temp += ch;
16+
} else if (ch == ' ') {
17+
if (ans!="") ans = temp + " " + ans;
18+
else ans = temp;
19+
temp = "";
20+
}
21+
left++;
22+
}
23+
24+
//If not empty string then add to the result(Last word is added)
25+
if (temp!="") {
26+
if (ans!="") ans = temp + " " + ans;
27+
else ans = temp;
28+
}
29+
30+
return ans;
31+
}
32+
};
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
class Solution:
2+
def reverseWords(self, s: str) -> str:
3+
left = 0
4+
right = len(s) - 1
5+
6+
temp = ""
7+
ans = ""
8+
9+
# Skip leading spaces
10+
while left <= right and s[left] == ' ':
11+
left += 1
12+
# Skip trailing spaces
13+
while right >= left and s[right] == ' ':
14+
right -= 1
15+
16+
# Iterate the string and collect words
17+
while left <= right:
18+
ch = s[left]
19+
if ch != ' ':
20+
temp += ch
21+
else:
22+
if temp != '':
23+
if ans != '':
24+
ans = temp + " " + ans
25+
else:
26+
ans = temp
27+
temp = ""
28+
left += 1
29+
30+
# Add the last word if any
31+
if temp != "":
32+
if ans != "":
33+
ans = temp + " " + ans
34+
else:
35+
ans = temp
36+
37+
return ans

0 commit comments

Comments
 (0)