Algorithm LogbookAlgorithm Logbook

Palindrome Check

Two Pointers

๐Ÿ“‹ Problem Statement

Given a string, return True if it reads the same forward and backward, and False otherwise. For example, "racecar" is a palindrome, "hello" is not. A single character like "a" is always a palindrome.

๐Ÿ’ก Intuition

A palindrome is symmetric: s[i]=s[Nโˆ’1โˆ’i]s[i] = s[N-1-i] for all ii. This is the same two-pointer technique used for array reversal โ€” compare from both ends and move inward. Finding any mismatch lets us immediately return False (early exit).

๐Ÿ”ง Approach

  1. Initialize two pointers: left = 0, right = len(s) - 1.
  2. While left < right, compare s[left] with s[right].
  3. If they differ, return False immediately.
  4. If they match, move left forward and right backward.
  5. If the loop completes without mismatches, return True.

โšก Complexity Analysis

Time

O(N)O(N) where NN is the length of the string โ€” at most โŒŠN/2โŒ‹\lfloor N/2 \rfloor comparisons

Space

O(1)O(1) โ€” only two pointer variables, no extra data structures

โš ๏ธ Common Mistakes

  • Comparing with s == s[::-1] โ€” correct but uses O(N)O(N) extra space
  • Not handling case sensitivity: "Racecar" returns False unless normalized to lowercase first
  • Forgetting edge cases: empty string "" and single character "a" are both palindromes

๐ŸŽฏ Final Thoughts

This problem reinforces the two-pointer pattern from Day 4 (Array Reversal). Strings in Python are essentially character arrays, so the same pointer logic applies.