I'll provide solutions in multiple programming languages with different approaches, focusing on C and including some additional languages for comprehensive understanding.
C Solution
#include <stdio.h>
#include <string.h>
// Function to reverse characters in a specific range
void reverseChars(char* start, char* end) {
while (start < end) {
char temp = *start;
*start = *end;
*end = temp;
start++;
end--;
}
}
// Function to reverse words in a string
void reverseWords(char* str) {
int len = strlen(str);
// Step 1: Reverse the entire string
reverseChars(str, str + len - 1);
// Step 2: Reverse individual words
char* start = str;
char* end = str;
while (*end != '\0') {
// Find word boundaries
while (*end != '\0' && *end != ' ') {
end++;
}
// Reverse current word
reverseChars(start, end - 1);
// Move to next word
if (*end == ' ') {
start = ++end;
} else {
break;
}
}
}
int main() {
char str[] = "Hello World Programming";
printf("Original string: %s\n", str);
reverseWords(str);
printf("Reversed words: %s\n", str);
return 0;
}
Python Solution
def reverse_words(s):
# Split words, reverse the list, then join back
return ' '.join(s.split()[::-1])
# Alternative in-place solution
def reverse_words_inplace(s):
words = s.split()
words.reverse()
return ' '.join(words)
# Test
s = "Hello World Programming"
print(reverse_words(s))
C++ Solution
class Solution {
public:
string reverseWords(string s) {
// Remove extra spaces
stringstream ss(s);
string word, result;
// Collect words in reverse order
vector<string> words;
while (ss >> word) {
words.push_back(word);
}
// Reconstruct string in reverse
for (int i = words.size() - 1; i >= 0; i--) {
result += words[i];
if (i > 0) result += " ";
}
return result;
}
};
Java Solution
class Solution {
public String reverseWords(String s) {
// Trim leading/trailing spaces and split
String[] words = s.trim().split("\\s+");
// Reverse the array of words
Collections.reverse(Arrays.asList(words));
// Join words back together
return String.join(" ", words);
}
}
Detailed Approach for C Solution
-
Two-Step Reversal Process:
- First, reverse the entire string
- Then, reverse each individual word
-
Key Steps:
- Reverse entire string to bring words in reverse order
- Iterate through the string and reverse characters of each word
- Handle word boundaries carefully
-
Time Complexity: O(n)
- Single pass through the string
- Constant extra space
-
Space Complexity: O(1)
- In-place reversal
- No additional data structures used
Edge Cases and Considerations
- Multiple consecutive spaces
- Leading/trailing spaces
- Empty string
- Single word string
Complexity Analysis
- Time Complexity: O(n), where n is string length
- Space Complexity: O(1) for in-place reversal
- No additional memory allocation required
Potential Interview Follow-ups
- Handle multiple consecutive spaces
- Implement without using built-in split functions
- Optimize for very large strings
- Handle Unicode strings
Practical Tips
- Always validate input string
- Be careful with pointer arithmetic in C
- Consider memory management
- Test with various input scenarios
Sample Test Cases
Input: "Hello World"
Output: "World Hello"
Input: " programming is fun "
Output: "fun is programming"
Input: "a"
Output: "a"
Input: ""
Output: ""
Common Mistakes to Avoid
- Not handling edge cases
- Modifying original string without permission
- Inefficient space usage
- Not handling multiple spaces correctly
The C solution provides an in-place, memory-efficient approach to reversing words in a string. It demonstrates low-level string manipulation techniques while maintaining simplicity and efficiency.
Would you like me to elaborate on any specific aspect of word reversal or explain any part of the solution in more depth?