02. Check Whether a String Is a Palindrome

Difficulty:EasyPattern:Two PointersTime:O(n)Space:O(1)

Determine whether a string reads the same forward and backward.

How It Works & Algorithmic Design

This uses the Symmetric Two-Pointer Check:

  1. Pointer Positions: Set left = 0 and right = s.length - 1.
  2. Symmetry Test: Compare s[left] and s[right]:
    • If s[left] !== s[right], the string is not symmetrical. Immediately return false.
    • Otherwise, advance left++ and retreat right-- toward the middle.
  3. Completion: If pointers cross (left >= right) without a character mismatch, return true.

Why This Approach Works Best

Rather than reversing the entire string (which takes extra space and time), this method checks characters in-place and stops early on the first mismatch. It processes at most $n/2$ comparisons, achieving $O(n)$ time and $O(1)$ extra space.

Example Walkthrough 1 (Palindrome)

Input

"racecar"

Odd-length palindrome string.

Comparisons

'r'=='r' -> 'a'=='a' -> 'c'=='c' -> Center reached ('e')

All symmetric character pairs match.

Output

true

String is a valid palindrome.

Example Walkthrough 2 (Non-Palindrome)

Input

"hello"

Non-palindrome string.

Comparisons

'h' != 'o' (Mismatch found instantly)

Terminates on the first comparison.

Output

false

String is not a palindrome.

Answer: Two-pointer palindrome check

function isPalindrome(s) {
  let left = 0, right = s.length - 1;
  while (left < right) {
    if (s[left] !== s[right]) return false;
    left++;
    right--;
  }
  return true;
}

Compare symmetric characters from both ends moving inward toward the center.

Key Takeaways
  • Checks symmetry using two converging pointers.

  • Early termination avoids unnecessary comparisons when a mismatch is found.

  • Operates in $O(n)$ time and $O(1)$ extra space.