714006. Count Special Numbers
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:
- Initialize an array
is_specialof size10^6 + 1. - Iterate through each number from
0ton - 1. For each number, extract its leftmost (left) and rightmost (right) digits. - Check if the difference between
rightandleftis at least1. If not, mark the current number as non-special inis_special. - Count the number of special numbers by iterating through
is_special.
Time complexity: O(n) Space complexity: O(10^6)
Optimized Solutions
Java
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;
}