Chat app~20 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-7number-theory
A chat app keeps a mirror key for every message id, for a reverse lookup table. The mirror of an id has its decimal digits in the opposite order, and keeps the sign. The mirror of 120 is 21, and the mirror of -45 is -54.
The lookup table stores keys as signed 32-bit integers. When a mirror does not fit, the app stores 0 for that message. Your team lead asks you to compute the mirror key of every id in a list.
Write mirror_ids(ids).
ids is a list of message ids. Each one is a signed 32-bit integer, from -2147483648 to 2147483647.-2147483648 or above 2147483647, its key is 0.Input: ids = [123, -456, 120, 0]
Output: [321, -654, 21, 0]For each id, take its size and remember its sign. Pop the last digit of the size and push it onto the end of the mirror, until no digits are left.
| Id | Digit by digit | Mirror | Fits 32 bits? | Key |
|---|---|---|---|---|
123 |
3, then 2, then 1 | 321 | yes | 321 |
-456 |
6, then 5, then 4, sign back | -654 | yes | -654 |
120 |
0, then 2, then 1 | 21 | yes | 21 |
0 |
no digits | 0 | yes | 0 |
Input: ids = [1534236469]
Output: [0]The mirror is 9646324351. It is larger than 2147483647, so the key is 0.
Input: ids = [1463847412, 2147483647, -2147483648]
Output: [2147483641, 0, 0]The mirror of the first id is 2147483641, which is 6 below the largest allowed value, so it fits. The mirror of 2147483647 is 7463847412, and the mirror of -2147483648 is -8463847412. Both are out of range.
1 ≤ length of ids ≤ 200000-2147483648 ≤ id ≤ 2147483647Each id has at most 10 digits, so one mirror costs about 10 steps, and 200,000 ids cost about 2,000,000 steps. That is fine.
The cost comes from how you build the answer. Inserting each key at the front of the result list moves every key already there, and that is about 200,000 × 200,000 ÷ 2 moves. Append each key, and keep the order of the ids.