Visualize

Pattern visualizer

Valid Palindrome

A palindrome mirrors around its center: the first char must equal the last, the second the second-last, and so on inward. Two pointers start at the two ends and walk toward the middle comparing one mirrored pair per step, so the check is O(n) time and O(1) space with no reversed copy. Animated on: Decide whether a string reads the same forwards and backwards..

Two pointers converging from both ends

time O(n)space O(1)step 1 / 11
r
[0]
a
[1]
c
[2]
e
[3]
c
[4]
a
[5]
r
[6]
line 1

The word 'racecar' as characters (indices 0..6). We must decide if it reads the same left-to-right and right-to-left.

Pseudocode
1FUNCTION isPalindrome(s): // s = 'racecar'
2 l = 0; r = length of s - 1
3 WHILE l < r:
4 IF s[l] != s[r]: RETURN false
5 l = l + 1
6 r = r - 1
7 RETURN true

← / → step · space play · Home restart

Where to practice Strings