Codementor Events

logarithmic time reverse function

Published Oct 19, 2018

The basic framework for divide and conquer algorithm can be used for any operations like reverse, checking if array is sorted etc. The possible implementation of reversing a string/vector is given as follows which takes O(n) time where n is size of collection string/vector.

template<class BidirIt>
void reverse(BidirIt first, BidirIt last)
{
while ((first != last) && (first != --last)) {
std::iter_swap(first++, last);
}
}
Better algorithm for this can be given as follows:

include <iostream>

include <algorithm>

include <string>

template <typename T>
void reverse_rotate(T first, T last){
if((first == last) || std::next(first) == last) return;
T middle = first;
std::advance(middle, std::distance(first, last)/2);
reverse_rotate(first, middle);
reverse_rotate(middle, last);
std::rotate(first, middle, last);
}

int main(){
std::string s = "This is super cool";
reverse_rotate(s.begin(), s.end());
std::cout << s << '\n';
}

Discover and read more posts from Vinu Thomas
get started