Strings•Easy
Palindrome Check
Palindrome Check

A Palindrome is a word, phrase, number, or other sequence of characters that reads the same backward as forward (ignoring spaces, punctuation, and capitalization). Classic examples include "racecar", "madam", and "radar".
Implementation Mechanics: The Two Pointers Technique
Checking for a palindrome is highly optimized using the Two Pointers pattern, which scans from both ends inward:
- Pointers Placement: Place a
leftpointer at index0(start of string) and arightpointer at indexN - 1(end of string). - Comparison: Compare the characters at
arr[left]andarr[right].- If they do not match, the string is not a palindrome. Stop and return
false. - If they match, increment
left(left++) and decrementright(right--).
- If they do not match, the string is not a palindrome. Stop and return
- Loop: Repeat step 2 as long as
left < right. - Success: If the pointers meet or cross without any mismatch, return
true.
Complexity Analysis
- Time Complexity:
- Best Case:
O(1)(if the very first and last characters do not match, e.g.,"apple") - Average/Worst Case:
O(N)(whereNis the length of the string, since we make at mostN / 2comparisons)
- Best Case:
- Space Complexity:
O(1)(constant auxiliary space as the verification is done entirely in-place)