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

Coding · Two pointers

A palindrome after deleting at most one letter

Easy · Target 12 minutes · Two pointers· Type asked at

You're given a string s of lower-case letters. Return true if it's a palindrome already or can be made into one by deleting at most one of its characters, and false if it can't.

Examples

InputOutputWhy
s = "abca"trueDelete the b or the c.
s = "aba"trueIt's a palindrome as it stands.
s = "abc"false
s = "cbbcc"trueDeleting one of the two c's at the end gives cbbc. Deleting the first c or a b does not work.

Constraints

  • 1 ≤ s.length ≤ 10⁵
  • s has lower-case English letters only

Hints

Hint 1

Trying every deletion and checking each result costs O(n²). Where's the first place a deletion could matter?

Hint 2

Walk two pointers in from the ends while the letters match. Those pairs are fine whatever you delete further in.

Hint 3

At the first mismatch one of s[lo] and s[hi] has to go. So you check whether s[lo+1..hi] or s[lo..hi−1] is a palindrome, and you don't get a second deletion.

Where people lose marks

  • Trying only one side at the mismatch. You'll pass most tests and then fail on something like cbbcc where it's the other letter that has to go.
  • Letting the inner check skip again. That allows two deletions and you'll say true for strings like abcdeca.
  • Building new substrings for each check. It's still O(n) but it copies, and in an interview I'd pass the two indices instead.
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.