00:00

Problem Statement

Input/Output Examples

Visual Explanation

Each step compares one pair from the outside in. A single mismatch would end the loop with false immediately; here every pair matches, so the method returns true after only two comparisons.

Approaches

All three approaches use the same fact: character i must equal character n - 1 - i. They differ in how much memory they need.

Java Solutions

Each tab is a complete program that runs on Java 17 or later. All three programs print the same output for the same inputs.

Complexity Analysis

Here n is the length of the string. Every approach compares at most n / 2 pairs. Two pointers uses constant extra space, while the reversed copy and the recursion stack both grow with n.

Interview Tips and Recommended Approach

  • Clarify the rules first. Ask whether case, spaces and punctuation matter; "Madam" is false under an exact comparison.
  • Know the sentence follow-up. To ignore case and punctuation, skip characters that fail Character.isLetterOrDigit() and compare with Character.toLowerCase().
  • Get the loop condition right. left < right handles both odd and even lengths, and the empty string returns true without entering the loop.
  • Do not reach for a stack, HashMap or sorting. A stack just rebuilds the reverse, counting answers a different question (can it be rearranged?), and sorting destroys the order.

Recommended Approach: Two Pointers

Why: it stops at the first mismatch, uses constant extra space and has no recursion depth limit. It is also the basis for many follow-up questions, such as palindromes that ignore punctuation.