Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Two pointers

A palindrome, ignoring punctuation and case

Easy · Target 10 minutes · Two pointers

Given a string s, return true if it reads the same forwards and backwards once you keep only its letters and digits and ignore the difference between upper and lower case. Otherwise return false. The string contains printable ASCII characters only.

Examples

InputOutputWhy
s = "Was it a car or a cat I saw?"trueLetters only: wasitacaroracatisaw, the same reversed.
s = "race a car"falseraceacar reversed is racaecar.
s = " .,"trueNothing is left to compare, and an empty string is a palindrome.

Constraints

  • 0 ≤ s.length ≤ 2 × 10⁵
  • s consists of printable ASCII characters

Hints

Hint 1

Building a cleaned, lower-cased copy and comparing it with its reverse works, in O(n) extra memory. Can you compare in place?

Hint 2

Put one pointer at each end. If either points at a character that does not count, move it inward and look again.

Hint 3

When both point at letters or digits, compare them case-insensitively. A mismatch ends the search; a match moves both inward.

Where people lose marks

  • Skipping in an inner while loop without re-checking i < j, which can run a pointer past the other or off the end of a string of punctuation.
  • Comparing without lower-casing, so "No lemon" fails on N against n.
  • Treating digits as characters to skip. "0P" is not a palindrome: 0 and p differ.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.