← Back to libraryQuestion 55 of 273
⌨️Java CodingBeginner

Check if a String is a Palindrome

📌 Definition:

Determine whether a string reads the same forwards and backwards (e.g. "madam", "racecar").

📖 Detailed Explanation:

Compare characters from both ends moving inward with two pointers — O(n) time, O(1) extra space. A common follow-up is to ignore case and non-alphanumeric characters ("A man, a plan, a canal: Panama").

💻 Solutions:
public static boolean isPalindrome(String s) {
    int i = 0, j = s.length() - 1;
    while (i < j) {
        if (s.charAt(i++) != s.charAt(j--)) return false;
    }
    return true;
}
function isPalindrome(s) {
  let i = 0, j = s.length - 1;
  while (i < j) {
    if (s[i++] !== s[j--]) return false;
  }
  return true;
}
def is_palindrome(s):
    return s == s[::-1]
🔑 Key Points:
  • Two pointers from both ends — O(1) extra space
  • Normalize case/whitespace for the "sentence" variant
  • Empty and single-char strings are palindromes
  • Reverse-and-compare works but allocates a copy
🌍 Real-World Example:

Palindrome logic appears in validating symmetric tokens, but its real value is demonstrating clean two-pointer traversal and edge-case thinking.

🎯 Scenario-Based Interview Question:

Your check passes for "madam" but fails "Race car". Why, and how do you fix it?