There are a few different solutions to the classic Palindrome Question. One of them involves reversing the string and comparing the original string to it another involves comparing first and last letters of the string and then recursively doing the same for the inner string.
For the first approach, is invoking string[::-1] an O(n) operating or an O(n^2) one? I believe that appending a char to a string is an O(n) operation (while appending to a list is O(1)), so does setting reversedString = string[::-1]
treat string
as a string or as an array?
For the recursive approach, if my solution is:
if len(string) <= 1:
return True
return (string[0] == string[-1]) and check_palindrome(string[1:-1])
does this take O(n) space or O(n^2) space? I know O(n) space is taken up by the recursive calls, but I'm thinking that on each stack the string is stored, so would that make it O(n*n) = O(n^2) space?
Thanks!