A positive integer is a perfect wake number when its decimal digits satisfy three conditions: it contains no 0, no digit repeats, and the two digits next to a digit are never higher than that digit. The interview first asked for a function that decides whether one number is a perfect wake number (for example, 123 is not), then asked how many perfect wake numbers lie between 1 and 9999. Write one function that covers both: count the perfect wake numbers in the inclusive range [low, high], where high is at most 9999. When low == high, the result is 1 if that number is a perfect wake number and 0 otherwise.
The report states the third condition loosely. Applied to the first and last digits as well, it would rule out every number with two or more digits, because of two adjacent different digits one is always higher than the other. This version therefore assumes it applies only to digits that have a neighbor on both sides, as the Rules state. Under that reading no four-digit number is a perfect wake number: its second and third digits each have a neighbor on both sides and sit next to each other, so each would have to be greater than the other. Every perfect wake number in the range has one, two or three digits.
Function Signature
def count_perfect_wake_numbers(low: int, high: int) -> int:
Rules
-
Write
n
in decimal without leading zeros.
n
is a perfect wake number when all three conditions hold:
-
No digit of
n
is
0
.
-
No digit appears more than once in
n
.
-
Every digit that has a neighbor on both sides is greater than both of those neighbors. Because the digits are distinct, "not higher than" is the same as "lower than". The first and last digits have only one neighbor each and are not checked by this condition.
-
Every one-digit number from
1
to
9
is a perfect wake number, and so is every two-digit number whose two digits are different and nonzero.
-
No four-digit number is a perfect wake number, for the reason given above.
-
Return the number of perfect wake numbers
n
with
low <= n <= high
.
Constraints
-
1 <= low <= high <= 9999
-
The result is an integer from
0
to
high - low + 1
.
Examples
Example 1
Input: low = 123, high = 123
Output: 0
123 has no zero and no repeated digit, but its middle digit 2 has the neighbor 3, which is higher, so 123 is not a perfect wake number. This is the example given in the interview.
Example 2
Input: low = 100, high = 200
Output: 28
200 and every number from 100 to 109 contain a 0. The numbers that qualify all have the form 1, then a middle digit greater than both outer digits, then a last digit other than 0 and 1: 132, 142, 143, and so on up to 198. There are 28 of them.
Example 3
Input: low = 1, high = 9999
Output: 249
This is the count asked for in the interview's follow-up. It is made up of the nine one-digit numbers, the 72 two-digit numbers with two different nonzero digits, and 168 three-digit numbers. No four-digit number contributes.