Mirror Phrase Contest

Easytwo pointersAlso known as Valid Palindrome

A word-puzzle club runs a contest for phrases that read the same forwards and backwards. People send entries like "Top spot." and "12:21". The judges only look at letters and digits. Spaces, commas, colons and other marks do not count, and capital letters count the same as small ones.

So "Top spot." is judged as topspot, which mirrors perfectly. The club gets thousands of entries and wants a program to do the first round of judging.

Your task

Write isMirrorPhrase(entry). Return true if the letters and digits of entry, read left to right, are the same as read right to left, ignoring case. Return false otherwise.

Every character that is not a letter (a-z, A-Z) or a digit (0-9) is ignored. Digits count and must mirror like letters. An entry with no letters or digits at all counts as a mirror phrase.

isMirrorPhrase(entry: string) → bool

Examples

Example 1
Input
entry = "Top spot."
Output
true
Why

Keep only letters and digits, all lowercase: topspot. Read backwards it is still topspot, so the entry passes.

Example 2
Input
entry = "Step on pets"
Output
false
Why

The letters are steponpets. Backwards that is stepnopets. The ends match for a while (s and s, t and t, e and e, p and p), but then o meets n, so it fails.

Example 3
Input
entry = "0P"
Output
false
Why

Digits count. The characters are 0 and p, which are different. If you threw digits away you would be left with just p and wrongly answer true.

Constraints

  • 0 ≤ entry.length ≤ 2,000
  • entry contains printable ASCII characters only (letters, digits, spaces, punctuation).
Start with brute force

Build a cleaned copy with only the letters and digits in lowercase, make a reversed copy, and compare the two strings.

This is correct and runs in O(n), so it is fine at this size. Its cost is memory: it builds two extra strings as long as the input. Checking from both ends in the original string needs no copies at all, and it can stop at the first mismatch instead of cleaning the whole entry first.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code