Reverse words in a given string

Posted by N.K. Chauhan 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"


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.


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


Print all permutations of a given string

Transform One String to Another with a Minimum Number of Operations

Longest Common Prefix in an Array of Strings

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

Print all subsequences of a string

Swap all occurrences of two characters to get lexicographically smallest string

Check whether the given string is a palindrome

Check if two strings are equal or not after processing backspace

Check if two given strings are isomorphic to each other

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