AlgoViz

Check if String is Palindrome or Not

Easy

Ends match, then check the middle

Problem

Return whether a string reads the same forwards and backwards, using recursion.

In simple words

Compare the outer two letters, then recurse inward — if they ever differ, it's not a palindrome.

The idea

Compare the outermost characters; if they differ the answer is no, and if they match the question reduces to the substring between them. Failing fast on a mismatch means most non-palindromes are rejected immediately.

The trick

  • Base case: the pointers meet or cross, so it is a palindrome.
  • Return false the moment a pair differs — no need to keep going.

This one walks through the worked example rather than tracing the algorithm frame by frame — a full walkthrough is still to be drawn. The code and the idea below are the real solution.

0
0

Step 1 of 2. Here's the example — madam Values: 0.

1/2
Optimal
timeO(n)spaceO(n)
1f(l,r):2  if l>=r: return true3  if s[l]!=s[r]: return false4  return f(l+1,r-1)

Input

array
[0]

Output

answer

Check yourself

3 quick questions about this walkthrough. A wrong answer costs nothing.

Examples

Example 1

Input:
s = "madam"
Output:
true
Explanation:
Reads the same both ways.

Example 2

Input:
s = "hello"
Output:
false
Explanation:
Backwards it's 'olleh' — different.

Example 3

Input:
s = "a"
Output:
true
Explanation:
Single letters are palindromes.

Finished the walkthrough? Add it to your streak.