1784. Upside-Down Numbers
A sign shop prints numbers on plastic cards that customers may hang upside down. A card is called upside-down safe when turning it by 180 degrees shows the same number. Under a half turn the digits 0, 1 and 8 stay the same, 6 becomes 9 and 9 becomes 6; no other digit may appear, and the order of the digits is reversed by the turn.
Return every integer in the inclusive range [low, high] that is upside-down safe, sorted in ascending order. A number has no leading zero, except that the number 0 itself is allowed (it is safe). Return an empty array if there is none. Do not test every integer in the range: build each length from the outside in by choosing matching digit pairs, then keep the values that fall inside the range. There are at most 499 results. Intended complexity: proportional to the number of safe numbers up to the digit length of high, with O(log high) recursion depth.
Example 1
- Input:
- low = 0, high = 100
- Output:
- [0,1,8,11,69,88,96]
- Explanation:
The numbers that look the same upside down are 0, 1, 8, 11, 69, 88 and 96.
Example 2
- Input:
- low = 50, high = 100
- Output:
- [69,88,96]
- Explanation:
Between 50 and 100 only 69, 88 and 96 survive a half turn.
Example 3
- Input:
- low = 2, high = 7
- Output:
- []
- Explanation:
None of 2 to 7 reads the same after turning, so the result is empty.
Constraints
0 ≤ low ≤ high ≤ 107 (at most 499 results)
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(5^(d/2)) for d digits of high
- Space
- O(d)