Bank app~15 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-125opposite-ends · two-pointers
A bank app prints a reference code on every statement. A code mixes letters, digits, hyphens, slashes and spaces, such as KB-7/A/7-bk. Most codes are short, but batch transfers carry references of up to 100,000 characters.
Years ago, a legacy system issued some codes as mirror codes. A mirror code reads the same from both ends once you ignore the separators, and upper and lower case count as the same letter. The migration team must flag every mirror code before statements move to the new ledger. The job checks millions of codes in place, so the team wants a check that makes no copy of a code.
Write is_mirror(code).
code is a reference code made of letters, digits, hyphens (-), slashes (/) and spaces. It is never empty.true if the letters and digits that remain read the same forwards and backwards, and false otherwise.true.Input: code = "KB-7/A/7-bk"
Output: true| left | right | Skipped on the left | Skipped on the right | code[left] | code[right] | Same, case ignored? |
|---|---|---|---|---|---|---|
| 0 | 10 | none | none | K | k | yes |
| 1 | 9 | none | none | B | b | yes |
| 3 | 7 | - at 2 |
- at 8 |
7 | 7 | yes |
| 5 | 5 | / at 4 |
/ at 6 |
A | A | yes: both pointers are on the middle letter |
After the last match, left is 6 and right is 4. The pointers have crossed, so every pair matched.
Input: code = "TX-92/19-XT"
Output: falseThe pairs T and T, X and X, then 9 and 9 match. The next pair is 2 and 1, so the code is not a mirror.
Input: code = "-- / --"
Output: trueThe code has no letters or digits, so it counts as a mirror. The left pointer skips separators until it meets the right pointer, and it stops there.
1 ≤ code.length ≤ 10^5code holds only the letters A to Z and a to z, the digits 0 to 9, hyphens, slashes and spaces.Any single pass over 10^5 characters is fast. Building a cleaned copy and comparing it with its reverse is already O(n), so time is not the hard part here.
The hard part is extra space: can you answer with two indexes and no copy? Be careful with the opposite trade, too. A check that makes no copy but counts in from the edges again for every pair is O(n^2): about 2.5 × 10^9 steps at this size.