Skip to content

Commit 1590930

Browse files
authored
Create README.md
1 parent c3a1a7e commit 1590930

File tree

1 file changed

+210
-0
lines changed
  • 25 - Greedy Algorithm Problems/05 - Reverse Words

1 file changed

+210
-0
lines changed
Lines changed: 210 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,210 @@
1+
<h1 align="center">Reverse - Words</h1>
2+
3+
## Problem Statement
4+
5+
**Problem URL :** [Reverse - Words](https://www.geeksforgeeks.org/problems/reverse-words-in-a-given-string5459/1?itm_source=geeksforgeeks&itm_medium=article&itm_campaign=practice_card)
6+
7+
![image](https://github.com/user-attachments/assets/393ae620-d127-45b5-81d6-75fc7e77fa7c)
8+
9+
### Problem Explanation
10+
The problem requires reversing the words in a given string. A word is defined as a sequence of non-space characters, and words are separated by spaces. You are tasked with reversing the order of words in the string, but keeping the characters within each word intact.
11+
12+
#### **Example 1:**
13+
14+
- **Input:** `"The quick brown fox"`
15+
- **Output:** `"fox brown quick The"`
16+
17+
**Explanation:** The order of the words is reversed, but the characters within each word remain unchanged.
18+
19+
#### **Example 2:**
20+
21+
- **Input:** `"Hello World"`
22+
- **Output:** `"World Hello"`
23+
24+
**Explanation:** The words "Hello" and "World" are reversed, and the characters inside the words stay the same.
25+
26+
#### **Example 3:**
27+
28+
- **Input:** `" I love programming "`
29+
- **Output:** `"programming love I"`
30+
31+
**Explanation:** In this case, even though there are extra spaces before the first word and after the last word, they should be ignored while reversing the words.
32+
33+
34+
### Approach:
35+
36+
To solve this problem, you do **not** need a greedy algorithm, as it doesn’t require making optimal choices at each step. Instead, you can solve it in a straightforward manner by splitting the string into words and then reversing the order of the words.
37+
38+
#### **Step-by-Step Approach:**
39+
1. **Split the String into Words:**
40+
- We can use an input string stream (`istringstream`) to extract words from the input string, splitting the string by spaces.
41+
42+
2. **Reverse the Order of Words:**
43+
- After splitting the string into words, we can reverse the list of words using the built-in `reverse()` function in C++.
44+
45+
3. **Reconstruct the String:**
46+
- After reversing the words, we will join them back together with a single space between each word and return the final string.
47+
48+
49+
## Problem Solution
50+
```cpp
51+
class Solution {
52+
public:
53+
// Function to reverse words in a given string
54+
string reverseWords(string &s) {
55+
// Create a vector to store individual words from the string
56+
vector<string> words;
57+
58+
// Temporary string to hold each word while reading from the string
59+
string word;
60+
61+
// Create an input string stream to split the string 's' into words
62+
istringstream iss(s);
63+
64+
// While there are words in the string stream, extract them and push to the 'words' vector
65+
while(iss >> word)
66+
words.push_back(word); // Extract each word and add it to the vector
67+
68+
// Reverse the vector of words
69+
reverse(words.begin(), words.end());
70+
71+
// Initialize an empty string to store the result
72+
string ans = "";
73+
74+
// Loop through the reversed vector of words
75+
for(int i = 0; i < words.size(); i++){
76+
// Add the current word to the result string
77+
ans += words[i];
78+
79+
// If this is not the last word, add a space between words
80+
if(i != words.size() - 1)
81+
ans += " ";
82+
}
83+
84+
// Return the final reversed string
85+
return ans;
86+
}
87+
};
88+
```
89+
90+
## Problem Solution Explanation
91+
92+
```cpp
93+
class Solution {
94+
public:
95+
// Function to reverse words in a given string
96+
string reverseWords(string &s) {
97+
```
98+
- This is the function signature. It defines the function `reverseWords` which takes a string reference `s` and returns a string.
99+
100+
```cpp
101+
// Create a vector to store individual words from the string
102+
vector<string> words;
103+
```
104+
- A `vector` called `words` is declared to store the words extracted from the string `s`.
105+
106+
```cpp
107+
// Temporary string to hold each word while reading from the string
108+
string word;
109+
```
110+
- A temporary string `word` is used to hold each word as we extract them from the string.
111+
112+
```cpp
113+
// Create an input string stream to split the string 's' into words
114+
istringstream iss(s);
115+
```
116+
- An `istringstream` `iss` is created from the string `s`. This allows us to extract words from the string.
117+
118+
```cpp
119+
// While there are words in the string stream, extract them and push to the 'words' vector
120+
while(iss >> word)
121+
words.push_back(word); // Extract each word and add it to the vector
122+
```
123+
- The `while(iss >> word)` loop reads each word from the stream `iss` one by one. Each word is added to the `words` vector.
124+
125+
```cpp
126+
// Reverse the vector of words
127+
reverse(words.begin(), words.end());
128+
```
129+
- After extracting all the words, we reverse the order of the words in the `words` vector using the `reverse()` function. This places the last word at the front and so on.
130+
131+
```cpp
132+
// Initialize an empty string to store the result
133+
string ans = "";
134+
```
135+
- An empty string `ans` is initialized to store the final result after concatenating the words in reverse order.
136+
137+
```cpp
138+
// Loop through the reversed vector of words
139+
for(int i = 0; i < words.size(); i++){
140+
// Add the current word to the result string
141+
ans += words[i];
142+
143+
// If this is not the last word, add a space between words
144+
if(i != words.size() - 1)
145+
ans += " ";
146+
}
147+
```
148+
- The `for` loop iterates over the `words` vector, appending each word to the result string `ans`.
149+
- If the current word is not the last word, a space is added after the word.
150+
151+
```cpp
152+
// Return the final reversed string
153+
return ans;
154+
}
155+
};
156+
```
157+
- Finally, the reversed string `ans` is returned, which contains the words in reversed order.
158+
159+
160+
### Example Walkthrough:
161+
162+
Let's consider an example with the input string `"The quick brown fox"`.
163+
164+
1. **Step 1 - Split the String into Words:**
165+
- The `istringstream` will extract words one by one:
166+
- "The"
167+
- "quick"
168+
- "brown"
169+
- "fox"
170+
171+
2. **Step 2 - Reverse the Words:**
172+
- After extracting the words, the `words` vector will contain: `["The", "quick", "brown", "fox"]`.
173+
- Reversing the vector will give: `["fox", "brown", "quick", "The"]`.
174+
175+
3. **Step 3 - Reconstruct the String:**
176+
- We loop through the reversed words and concatenate them into the result string `ans`:
177+
- Add "fox" → `ans = "fox"`
178+
- Add "brown" → `ans = "fox brown"`
179+
- Add "quick" → `ans = "fox brown quick"`
180+
- Add "The" → `ans = "fox brown quick The"`
181+
182+
4. **Final Output:**
183+
- The final output is `"fox brown quick The"`.
184+
185+
186+
### Time and Space Complexity:
187+
188+
#### **Time Complexity:**
189+
1. **Extracting Words:**
190+
- Extracting words using the `istringstream` takes O(n), where `n` is the length of the input string `s`.
191+
2. **Reversing the Vector:**
192+
- Reversing the vector of words takes O(k), where `k` is the number of words in the vector. In the worst case, `k` is O(n) (if each character is a separate word).
193+
3. **Reconstructing the String:**
194+
- Reconstructing the string by concatenating the words takes O(n) because we are iterating through each word and appending it to the result string.
195+
196+
Therefore, the overall time complexity is **O(n)**.
197+
198+
#### **Space Complexity:**
199+
1. **Storing Words:**
200+
- The space complexity is determined by the `words` vector, which stores each word separately. The total space required is proportional to the number of characters in the input string `s`, which is O(n).
201+
202+
Therefore, the overall space complexity is **O(n)**.
203+
204+
205+
### Summary:
206+
207+
- The code successfully reverses the words in the given string while maintaining the character order within each word.
208+
- The approach is simple and efficient, with both time and space complexity of **O(n)**.
209+
210+

0 commit comments

Comments
 (0)