Java ProgramsRecursionCheck Palindrome Using Recursion

Check Palindrome Using Recursion in Java

beginner·  Recursion  ·  Recursion

Problem

A recursive palindrome check compares the outermost pair of characters and, if they match, hands off a narrower window to the next call — shrinking one pair at a time until nothing is left to compare.

Given a string and a pair of index bounds, determine recursively whether it reads the same forwards and backwards.

Input
racecar
Output
racecar is palindrome: true

Java Program

Java
public class PalindromeCheckRecursion { static boolean isPalindrome(String str, int left, int right) { if (left >= right) return true; // window has shrunk to nothing left to compare if (str.charAt(left) != str.charAt(right)) return false; // one mismatch rules it out return isPalindrome(str, left + 1, right - 1); } public static void main(String[] args) { String str = "racecar"; boolean result = isPalindrome(str, 0, str.length() - 1); System.out.println(str + " is palindrome: " + result); } }

Output

racecar is palindrome: true

Core Logic

Comparing the two ends of the current window and recursing on the window with both ends moved inward reduces the whole check to a chain of single-pair comparisons.

How It Works
  1. 1isPalindrome(str, left, right) tracks the current comparison window with two index bounds.
  2. 2If str.charAt(left) != str.charAt(right), the call returns false immediately — one mismatch is enough to rule out a palindrome.
  3. 3Otherwise it recurses with isPalindrome(str, left + 1, right - 1), narrowing the window by one character from each side.
  4. 4The base case if (left >= right) return true; fires once the window has shrunk to nothing or a single middle character, meaning every pair matched.
For "racecar", the calls compare (r,r), then (a,a), then (c,c), then reach left == right at the middle 'e' and return true all the way back up.
💡

Key Point: Each call only ever needs to know the current window's bounds — it doesn't need to remember which pairs already matched, since a mismatch anywhere would already have returned false before this call was ever reached.

Complexity
Time Complexity: O(n)Space Complexity: O(n)

Why: The window shrinks by one pair per call, so roughly n/2 calls run, each adding a frame to the call stack before any of them return.

Key Concepts

recursionshrinking windowbase case

Related Programs