Back to Two Pointers and Sliding Window
Valid Palindrome
Clean the string, then use two pointers converging from both ends. Compare characters one pair at a time — any mismatch immediately rules out a palindrome.
Visualization
Speed
0
Characters Checked
Checking...
Result
Cleaned string: "amanaplanacanalpanama"
0
a
L=R1
m
–2
a
–3
n
–4
a
–5
p
–6
l
–7
a
–8
n
–9
a
–10
c
–11
a
–12
n
–13
a
–14
l
–15
p
–16
a
–17
n
–18
a
–19
m
–20
a
–Left pointer (L)Right pointer (R)Matched pairMismatch
Ready — press Play or step through.
Complexity
O(n)
Best Case
O(n)
Worst Case
O(n)
Average
O(1)
Space
Space is O(1) extra if we use two pointers on the original string without creating a cleaned copy. The O(n) cleaning pass is unavoidable but the pointer traversal itself is O(1) space.
How It Works
- 1Strip non-alphanumeric characters and convert to lowercase
- 2Place left pointer at index 0, right pointer at the last index
- 3Compare s[left] and s[right]. If equal, move both inward. If not, return False
- 4When left >= right all pairs have matched — return True
Active Recall Quiz
Question 1 of 3
Why do we skip non-alphanumeric characters when checking for a palindrome?