• Listen to a special audio message from Bill Roper to the Hive Workshop community (Bill is a former Vice President of Blizzard Entertainment, Producer, Designer, Musician, Voice Actor) 🔗Click here to hear his message!
  • Read Evilhog's interview with Gregory Alper, the original composer of the music for WarCraft: Orcs & Humans 🔗Click here to read the full interview.

Fastest way to determine if string is a palindrome?

Status
Not open for further replies.
Level 15
Joined
Aug 7, 2013
Messages
1,338
Hi,

What is the best method, time complexity wise, to detect if a string is a palindrome, e.g.

Code:
function isPalindrome takes string whichString returns boolean
  …
endfunction

The algorithm I got is to simply check off each character with the string in place, e.g. compare the 0th and nth character, then the 1th and n - 1 th character, etc. If any do not match, then reject and return false. Otherwise return true.

This algorithm is also found on stack overflow.com: http://stackoverflow.com/questions/8444710/easiest-way-to-check-if-a-string-is-palindrome

This is O(n) because its linear with respect to the size of the palindrome.

Is there anyway to do this check faster than linear time? If not, can someone show a (mathematical) proof that the Palindrome Acceptance Problem cannot be done faster than O(n)?
 
Level 29
Joined
Jul 29, 2007
Messages
5,174
The short answer is no.
How could it not be O(n) when you have n characters that you must process individually?

The longer answer, google will lead you to some article about proof that a "multitape Turing machine" can do a check at O(1), but this has nothing to do with our computers (or does it?).
 
Status
Not open for further replies.
Top