← Arrays & Strings

Drill #5 — Check palindrome string

Easy Two Pointers Arrays & Strings

In plain English: Check whether a word or phrase reads the same forwards and backwards.

A palindrome is symmetric, so comparing from both ends toward the center catches any mismatch in O(n/2) comparisons.

Prompt

Given string s, return True if it's a palindrome.

Try to write it from scratch before scrolling down.

Solution

def is_palindrome(s):
    l, r = 0, len(s) - 1
    while l < r:
        if s[l] != s[r]:  # mismatch = not palindrome
            return False
        l += 1; r -= 1
    return True

# Test: is_palindrome("racecar") == True
O(n) time · O(1) space

Related Micro Drills

← Drill #4 Drill #6 →