Show problems as
Classic problem #125EasyTwo PointersString

Valid Palindrome

Real-world version: Mirror Phrase Check
Tracked in this browser only
Read Valid Palindrome on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

Learn the pattern firstTwo Pointers · Strings, animated step by step

A word-game server accepts a submission phrase typed by a player and decides whether it counts as a mirror phrase.

The server judges it with two relaxations, applied before the comparison:

  1. Only letters and digits are inspected. Every other character in phrase, including spaces, punctuation and symbols, is skipped over entirely.
  2. Letter case carries no meaning. An uppercase letter and its lowercase twin are treated as one and the same character.

After those relaxations, phrase is a mirror phrase when the kept characters spell the same thing read left to right as they do read right to left. Return true if it does and false if it does not.

A submission whose characters are all skipped keeps nothing at all, and nothing trivially matches itself, so those submissions are mirror phrases too.

Examples

Example 1

Input
phrase = "Step on no pets!"
Output
true

Dropping the spaces and the exclamation mark keeps steponnopets, which spells itself in reverse. Compared as typed it would fail, so the skipping rule is what decides this one.

Example 2

Input
phrase = "Deed"
Output
true

Nothing is skipped here. The capital D at the front lines up with the small d at the back, and folding case away makes them equal.

Example 3

Input
phrase = "Bell hop"
Output
false

The kept characters spell bellhop, whose reverse begins with p, so the very first comparison already disagrees.

Example 4

Input
phrase = "@@ ##"
Output
true

Not one letter or digit survives the first rule, leaving an empty run of characters, which the server accepts.

Constraints

  • 1 <= phrase.length <= 2 * 10^5
  • phrase is made up of printable ASCII characters

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def is_mirror_phrase(phrase: str) -> bool:
Java
public boolean isMirrorPhrase(String phrase)