Problem Statement
Use a stack to reverse the order of words in a sentence. We can utilize the stack's Last In, First Out (LIFO) property to reverse the word order.
Example Usage
Additional Examples:
- Input:
"stack implementation"
- Output:
"implementation stack"
- Input:
"javascript is fun"
- Output:
"fun is javascript"
JavaScript Stack - Using Custom Stack Class
We’ll use the following custom Stack class to reverse the order of words. This class includes methods like push, pop, peek, isEmpty, size, and clear.
Dry Run
For the input "hello world":
- Split the sentence into words:
["hello", "world"]
- Push each word onto the stack:
- Push
"hello" → Stack: ["hello"]
- Push
"world" → Stack: ["hello", "world"]
- Pop each word from the stack to reverse the order:
- Pop
"world" → reversedSentence = "world "
- Pop
"hello" → reversedSentence = "world hello "
- Trim the trailing space to get
"world hello".
Complexity Analysis
Custom Defined Stack Methods
- Time Complexity: Each
push and pop operation is O(1), making the solution O(n) for n words in the sentence.
- Space Complexity: O(n) for storing words in the stack.
Conclusion
Using a stack to reverse the order of words in a sentence is a clean and efficient solution that leverages the stack's LIFO property. This approach is useful in scenarios where word order needs to be reversed while preserving the order within each word.