19. Reverse Words

The problem can be found at the following link: Question Link

Problem Description

Given a string str, reverse the string without reversing its individual words. Words are separated by dots.

Note: The last character is not a dot.

Examples:

Input: str = "i.like.this.program.very.much" Output: "much.very.program.this.like.i"

Explanation: After reversing the whole string (not individual words), the input string becomes "much.very.program.this.like.i".

Input: str = "pqr.mno" Output: "mno.pqr"

Explanation: After reversing the whole string, the input string becomes "mno.pqr".

My Approach

  1. Iterate Backwards:

    • Traverse the string from the last character to the first.

    • Every time a dot (.) is encountered, extract the word from the position after the dot to the current position and append it to the result string.

    • Continue this process until all words are appended in reverse order.

  2. Final Touch:

    • Add the last word, which doesn't have a preceding dot, after the loop ends.

Time and Auxiliary Space Complexity

  • Expected Time Complexity: O(|str|), where |str| is the length of the input string. This is because we are iterating over the string once to reverse the words.

  • Expected Auxiliary Space Complexity: O(|str|), as we are using a new result string to store the reversed words.

Code (C++)

Code (Java)

Code (Python)

Contribution and Support

For discussions, questions, or doubts related to this solution, please visit my LinkedIn:- Any Questions. Thank you for your input; together, we strive to create a space where learning is a collaborative endeavor.

⭐ Star this repository if you find it helpful or intriguing! ⭐


📍Visitor Count

Last updated