You are given a string s that may hold letters, digits, spaces and punctuation. Throw away everything that is not a letter or a digit, and treat upper-case and lower-case letters as the same.
Return true if what is left is spelled the same from left to right as from right to left, and false if it is not. If nothing is left, the answer is true.
Example 1
Input: s = "Top, spot!" Output: true Why: the letters are "topspot", the same in both directions
2 more examples and the constraints
Example 2
Input: s = "Nope, open" Output: false Why: "nopeopen" backwards is "nepoepon"
Example 3
Input: s = "?!" Output: true Why: no letters or digits remain, and an empty string is a palindrome
Constraints
- 1 ≤ length of s ≤ 200,000
- s holds only printable ASCII characters
- Digits count, so
0andPare two different characters
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Clean, then reverseO(n)
- Two pointers, in placeO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 200,000 characters | Verdict |
|---|---|---|---|
| Clean, then reverse | O(n) | Passes; uses a copy | |
| Two pointers, in place | O(n) | Best; no extra memory |
n = length of s. Both are linear; the bar also counts the extra passes and the copy.
Edge cases to test
- Nothing left after cleaning. "?!" or a single space has no letters or digits. The answer is true.
- Digits next to letters. "0P" is false:
0is a digit, not the letter O, and must not be dropped. - Mixed case. "Ab1 1bA" is true because
Aandacount as the same letter. - One character. Any single character reads the same both ways, so the loop never runs.
Common mistakes
- Dropping digits along with punctuation, so "0P" wrongly becomes "p" and passes.
- Comparing characters without lower-casing them, so "Aa" fails.
- Moving only one pointer after a match, or forgetting to stop when the pointers cross.
How to talk through it
- 1Clarify. Do digits count? Is case ignored? What should a string with no letters return?
- 2Give the simple version. Clean the string, compare it with its reverse, and note the O(n) extra memory.
- 3Remove the copy. Two pointers on the original string do the same comparison, skipping symbols as they go.
- 4Code the loop. One move per iteration: skip left, skip right, mismatch, or match and move both.
- 5Test out loud. Run "0P", "?!" and Example 1 before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?