cppAcademy
FROM LEARNING TO COMPETING

Beginner.
Your first challenges.

Bulgarian Informatics Group E · 2007–2026

270 independently explained problems: 54 Municipal, 54 Regional, 105 National Olympiad tasks and 57 Autumn Tournament tasks. Start with the easier tasks and work upwards. Difficulty labels are learning estimates, not official ratings; Group E also includes challenging national-level problems. Years follow Arena’s competition-season labels. Source clarifications are noted on affected tasks.
GROUP E2009 · MediumDigits & number theory

Numbers with Distinct Digits

National Olympiad — National round (2009 season)

Submission name: unique.cpp

Problem summary

A number is unique when none of its decimal digits repeat. Count unique numbers in the inclusive interval [m, n]. Zero is a one-digit number.

Input

Two integers m and n.

Output

The number of unique numbers in the interval.

Constraints

0 ≤ m < n ≤ 10,000,000.

Worked example

An independently prepared example for this explanation.

Input

97 104

Output

5

Solution analysis

  1. Check each integer in the interval. Extract its last digit with remainder by 10 and remove that digit with division by 10.
  2. Use a ten-element boolean array to record digits already encountered. A repeated digit rejects the number immediately. A do-while loop processes zero as the single digit 0.
  3. From 97 through 104, the accepted values are 97, 98, 102, 103, and 104. Values 99, 100, and 101 contain repetitions.

Why it works

During a check, seen[d] is true exactly when digit d has already been extracted. A check fails exactly when a repeated digit appears; otherwise every digit is distinct. The outer loop examines every integer of the inclusive interval once, so its count is correct.

Complexity: O((n − m + 1)D) time, where D ≤ 8 is the number of decimal digits; O(1) extra space.

Watch out. Include both endpoints. Leading zeros are not part of a number; zero itself must still be considered.

Commented C++17 solution

An independently written complete program with standard headers.

#include <iostream>
using namespace std;
int main() {
    int lower, upper;
    cin >> lower >> upper;
    int answer = 0;
    for (int number = lower; number <= upper; number++) {
        bool seen[10] = {};
        bool unique = true;
        int remaining = number;
        // A do-while loop also checks the one-digit number zero.
        do {
            int digit = remaining % 10;
            if (seen[digit]) {
                unique = false;
                break;
            }
            seen[digit] = true;
            remaining /= 10;
        } while (remaining > 0);
        if (unique) {
            answer++;
        }
    }
    cout << answer << '\n';
}

Source: Arena Olimpiici ↗