Check If a String is Palindrome in Java and Python

By Sumanik Singh

Updated April 11, 2018

A young man typing on his laptop at home
i g-stockstudio/iStock/Getty Images

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.

def is_palindrome(s): """Returns True if given argument s is a palindrome else False""" assert(isinstance(s,str)), "Argument s is not of type <str>" # Assert if the given argument is of type <str> return s[::-1]==s # Compare the reverse of string with itself if __name__=="__main__": print(is_palindrome("dad"))def is_palindrome(word): """Compares the characters one-by-one from beginning and end and returns False when the first mismatch occurs or else returns True""" i1,i2 = 0,len(word)-1 # Initialize the cursors while i2>i1: if word[i1]!=word[i2]: # If the characters don't match then no need to proceed further return False i1+=1 i2-=1 return True if __name__=="__main__": print(is_palindrome("dad"))

Palindrome in Java Implementation

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

public class Palindrome { public static Boolean isPalindrome(String str){ StringBuilder sb = new StringBuilder(str); // StringBuilder has reverse method return sb.reverse().toString().equals(str); // Compare the reverse of the string with itself } public static void main(String args[]) { Boolean b = isPalindrome("dad"); System.out.println(b); } }public class Palindrome { public static Boolean isPalindrome(String str){ int i1 = 0; int i2 = str.length() - 1; while(i2>i1){ if(str.charAt(i1)!=str.charAt(i2)){ return false; } i1++; i2--; } return true; } public static void main(String args[]) { Boolean b = isPalindrome("dad"); System.out.println(b); } }
×