714006. Count Special Numbers

Medium

Count Special Numbers

Slug: count-special-numbers--170647 Difficulty: Medium Id: 714006 Topic Tags: Arrays, Mathematical, sieve, Data Structures, Algorithms Company Tags: Intuit

Summary

The problem "Count Special Numbers" involves counting the number of special numbers in a given range. A special number is defined as a number that has at least one digit greater than its leftmost digit and at least one digit less than its rightmost digit. For example, 123 is not a special number because all digits are increasing from left to right. On the other hand, 345 is a special number because there exists a digit (3) which is less than the adjacent digit.

Detailed Explanation

To solve this problem, we will use a sieve-based approach. The idea is to create an array is_special of size 10^6 + 1, where is_special[i] represents whether i is a special number or not. We iterate through each number from 0 to n - 1 and check if it's a special number by comparing its leftmost and rightmost digits.

Here's the step-by-step breakdown:

  1. Initialize an array is_special of size 10^6 + 1.
  2. Iterate through each number from 0 to n - 1. For each number, extract its leftmost (left) and rightmost (right) digits.
  3. Check if the difference between right and left is at least 1. If not, mark the current number as non-special in is_special.
  4. Count the number of special numbers by iterating through is_special.

Time complexity: O(n) Space complexity: O(10^6)

Optimized Solutions

Java

View on GeeksforGeeks
public int countSpecialNumbers(int n) {
    boolean[] is_special = new boolean[1000000 + 1];
    for (int i = 0; i <= n; i++) {
        int left = i / 100;
        int right = i % 10;
        if (right - left >= 1) {
            is_special[i] = true;
        }
    }
    int count = 0;
    for (int i = 0; i <= n; i++) {
        if (is_special[i]) {
            count++;
        }
    }
    return count;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.