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"


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


Check if two strings are equal or not after processing backspace

Check if two given strings are isomorphic to each other

Transform One String to Another with a Minimum Number of Operations

Swap all occurrences of two characters to get lexicographically smallest string

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

Check whether the given string is a palindrome

Print all subsequences of a string

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

Print all permutations of a given string

Longest Common Prefix in an Array of Strings