A student just learnt the reverse() function in c++ STL. He writes the following algorithm to check if a given string S is a palindrome

bool isPalindrome(string& s)
string rev = s
reverse(rev.begin(), rev.end())
return s == rev

Is the algorithm correct? What is the space and time complexity?

No syntactical error but algorithm just does not work on all possible range of inputs.

Algorithm is correct and uses O(N) time and O(1) space.

Syntactical error, correction in statement 2 : rev = reverse(rev.begin(), rev.end())

Algorithm is correct and uses O(N) time and O(N) extra space.

Hey @Kash-Moulik-3715574511847721
Yes this is correct.Time complexity will be O(n) and space complexity will also be O(n).Here n is the number of characters in the string. (Since you are making copy of the reversed string in a string variable)

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.