Ride-hailing app~20 min2s · 256 MBtarget O(M + q) time, O(M) spacestrings · prefix-sums
A ride-hailing app prints a ticket number on every receipt, from 1 up to 1,000,000. A number is a mirror number when its digits read the same from left to right and from right to left. The number 121 is one, and 120 is not.
Support wants to hand out a small gift to mirror tickets. They ask many questions of the form: how many mirror tickets lie between two numbers?
Write mirror_tickets(queries).
[low, high] asks about all ticket numbers from low to high, both included. It always has low ≤ high.Input: queries = [[1, 20], [100, 130], [5, 5]]
Output: [10, 3, 1]The first query covers 1 to 20. The mirror numbers are 1 to 9 and 11, so the answer is 10. The second covers 100 to 130: 101, 111, 121.
| Query | Mirror numbers in the range | Answer |
|---|---|---|
| [1, 20] | 1, 2, 3, 4, 5, 6, 7, 8, 9, 11 | 10 |
| [100, 130] | 101, 111, 121 | 3 |
| [5, 5] | 5 | 1 |
Input: queries = [[10, 10]]
Output: [0]The number 10 reads 01 backwards, which is not the same text. There is no mirror number: the answer is 0.
Input: queries = [[1, 1000000]]
Output: [1998]The mirror numbers up to 1,000,000: the answer is 1998.
1 ≤ number of queries ≤ 10^51 ≤ low ≤ high ≤ 10^6A query can cover almost 10^6 numbers. Checking every number in every range costs up to 10^5 x 10^6 = 10^11 checks.
All queries draw on the same 10^6 numbers. Check each number once, which is 10^6 checks, then answer each query from a table of running counts.