Longest palindrome challenge

Another day and yet another tech challenge. I was recently confronted with this and although I couldn't tackle it during an interview session, once I finished the interview (lost the job of course), and was able to give it some thought, I realized this problem really isn't that difficult.

Context for the problem is this - I give you a string, and you need to find the longest palindrome in the string, or the longest word spelled the same forward as backward. So for example, if you were given "aghbrettegh", I'd expect to get 'ette' back.  As usual, there are multiple ways to approach solving this, so this is just one possible route. If you have a cleaner, better, or different one let me know.

There are two main challenges here - the first is to identify what a palindrome is. I tackled that part first, and wrote a boolean method which, as you might have guessed, returns true if the string is a palindrome, and false if it isn't. Looks like this in Ruby:

def is_palindrome? string
  string.split('').each_with_index do |s, idx|
    return false if s != string.slice(string.length-1 - idx, 1)
  end
  true
end

So basically we're just slicing the string 1 character at a time, from either end of the string, and comparing them. This worked pretty well, so we'll continue with the second part shortly.

Leave a Reply

Your email address will not be published. Required fields are marked *