Back to challenges
Hard 0 solved 0% acceptance

Count Numbers With Distinct Neighbors

Count range values whose adjacent decimal digits are never equal.

What you'll learn

  • Count numbers up to a limit digit by digit
  • Track the previous digit and tight bounds
  • Answer a range as f(b) - f(a - 1)

Problem

Count integers from left through right, including both endpoints, that have no equal neighboring digits. Use their usual decimal writing with no leading zeroes. Zero and all other single-digit numbers qualify.

Implement counting_numbers(left, right).

Input

left: The first allowed value.

right: The last allowed value.

Output

Return how many values satisfy the rule.

Constraints

0 ≤ left ≤ right ≤ 10¹⁸. The range may be too large to inspect each integer individually.

Examples

Example 1
Input:
left = 10
right = 15

Expected output:
expected = 5
Input:
long long left = 10;
long long right = 15;

Expected output:
long long expected = 5;
Input:
long left = 10;
long right = 15;

Expected output:
long expected = 5;

Explanation

Only 11 has equal neighboring digits. The other five numbers qualify.

Example 2
Input:
left = 0
right = 9

Expected output:
expected = 10
Input:
long long left = 0;
long long right = 9;

Expected output:
long long expected = 10;
Input:
long left = 0;
long right = 9;

Expected output:
long expected = 10;

Explanation

All ten values have just one digit and therefore no equal neighbors.

How to approach it

Try on your own first, then open one hint at a time.

Hint 1

Count valid numbers up to each endpoint, then subtract to get the range answer.

Hint 2

Digit DP fits because validity depends on adjacent digits and whether you have started the number.

Hint 3

Leading zeros need special handling so that shorter numbers are counted correctly.

Expected complexity

O(k * 10 * states) time, O(k * states) extra space

References

This challenge is adapted for CodeUtility. Follow the statement and constraints above.

Learn from others

Community solutions

No published solutions yet. Solve this challenge to share the first one.