x

Check If a String is Palindrome in Java and Python

by Sumanik SinghUpdated April 11, 2018

Over the years, checking whether a string is a palindrome or not has become a classic coding interview question. This is because it involves concepts around string manipulation and comparison and even loops depending on the implementation. And, the question isn't a lengthy one so it can be completed within the time constraints of an interview. This article includes implementation for checking if a string is palindrome in java and python.

What Is a Palindrome?

According to synonym.com, the definition of palindrome is "a word or phrase that reads the same backward as forward." Basically, it means if you write the word or phrase in reverse, it will be exactly same as when it was forward. For example, dad and mom are palindromes and father and mother aren't. The word "palindrome" comes from two Greek root words, "palin" meaning again and "dromos" meaning way or direction. It was coined by the English playwright Ben Jonson in the 17th century.

Solution

  • The most common and easy way to solve the question is by reversing the string first and then comparing it with the original string. This approach will be O(n) in big-O notation because string reversal is O(n).
  • Another way would be to start comparing characters from beginning and end and continue until you reach the middle. This approach has a time complexity of O(n/2) but in big-O notation it will still be O(n). But the advantage with this approach is that you can return False as soon as you come across the first mismatch, whereas with the first approach, since reversing a string is the first step the time complexity will always be O(n).

Palindrome in Python Implementation

Following is the code for checking if a string is palindrome in python.

Palindrome in Java Implementation

Following is the code for checking if a string is palindrome in java.

Tip

  • Confirm with the interviewer if they want the code to be case sensitive or not. For example: If the code is case sensitive then Dad is not a palindrome because the first character is upper case "D" and the last character is lower case "d".

Video of the Day

Brought to you by Techwalla
Brought to you by Techwalla

More Articles