![]() |
VOOZH | about |
Have you wondered which is the easiest way to reverse a string, Imagine you are giving a contest and an algorithm you have made requires reversing a string, you must be aware of the easiest way to reverse a string.
Reversing a string is the technique that reverses or changes the order of a given string so that the last character of the string becomes the first character , second last becomes second character of the string and so on.
Examples:
Input: "ABC"
Output: "CBA"Input: "geeksforgeeks"
Output: "skeegrofskeeg"
The easiest way to reverse a string is to use the inbuilt function of respective languages. There is a direct function in the “algorithm” header file for doing reverse that saves our time when programming.
// Reverses elements in [begin, end]
void reverse (BidirectionalIterator begin, BidirectionalIterator end);
reverse() is a predefined function in the header file algorithm. It is defined as a template in the above-mentioned header file. It reverses the order of the elements in the range [first, last) of any container. The time complexity is O(n).
Note: The range used is [first, last), which contains all the elements between first and last, including the element pointed by first but not the element pointed by last.
Syntax:
void reverse(BidirectionalIterator first, BidirectionalIterator last)
Explanation:
BidirectionalIterator is an iterator that can be used to access any
elements of a container in both forward and backward direction.
Below is the Implementation of the above approach:
skeegrofskeeg
Time Complexity: O(N), N is the size of the string.
Auxiliary Space: O(1)