🔹 Introduction
String problems are very common in Java interviews.
One of the easiest yet frequently asked questions is:
👉 Check whether a given string is a palindrome.
Let’s understand how to solve it step by step.
🔹 Problem Statement
A string is called a palindrome if it reads the same forward and backward.
Example:
Input: madam
Output: Palindrome
Input: hello
Output: Not a Palindrome
🔹 Approach 1: Using Two Pointers (Best Method)
- Start one pointer from the beginning
- Start another pointer from the end
- Compare characters
- If all match → Palindrome
🔹 Java Code (Two Pointer Approach)
public class PalindromeCheck {
public static void main(String[] args) {
String str = "madam";
int left = 0;
int right = str.length() - 1;
boolean isPalindrome = true;
while (left < right) {
if (str.charAt(left) != str.charAt(right)) {
isPalindrome = false;
break;
}
left++;
right--;
}
if (isPalindrome) {
System.out.println("Palindrome");
} else {
System.out.println("Not a Palindrome");
}
}
}
🔹 Approach 2: Using StringBuilder (Simple Method)
Reverse the string and compare.
🔹 Java Code (StringBuilder)
public class PalindromeCheck {
public static void main(String[] args) {
String str = "madam";
String reversed = new StringBuilder(str).reverse().toString();
if (str.equals(reversed)) {
System.out.println("Palindrome");
} else {
System.out.println("Not a Palindrome");
}
}
}
🔹 Time Complexity
- O(n) → Efficient solution
🔹 Key Takeaways
✔ Two-pointer approach is optimal
✔ StringBuilder makes it simple
✔ Very frequently asked in interviews
🔹 Conclusion
Palindrome is one of the most basic and important string problems.
Make sure you understand both approaches for interviews.
🔗 Also Read
👉 First Non-Repeating Character in Java
👉 Check Palindrome String in Java
Comments
Post a Comment