Reverse words in a given string

Posted by on Mar 31, 2024

Given a String S or length N, reverse the string without reversing its individual words. Words are separated by single whitespace.

Input: "this is an amazing program", Output: "program amazing an is this"

Input: "The purpose of our lives is to be happy", Output: "happy be to is lives our of purpose The"


Solutions

Method 1: In O(n) time

We can easily solve this problem in O(n) time and O(n) extra space.

The idea is to first reverse the entire string and then reverse only the individual words.

Complexity

The time complexity of this solution is O(N) and space complexity is O(N).

Related


Power Set: Print all non-empty subsequences of a string

Print all permutations of a given string

Check if two given strings are isomorphic to each other

Print all subsequences of a string

Transform One String to Another with a Minimum Number of Operations

Find all substrings of a string in "O (n^2)" time

Swap all occurrences of two characters to get lexicographically smallest string

Check whether the given string is a palindrome

Longest Common Prefix in an Array of Strings

Check if two strings are equal or not after processing backspace