Problem
You are given an integer n
that consists of exactly 3
digits.
We call the number n
fascinating if, after the following modification, the resulting number contains all the digits from 1
to 9
exactly once and does not contain any 0
’s:
- Concatenate
n
with the numbers2 * n
and3 * n
.
Return true
ifn
is fascinating, orfalse
otherwise.
Concatenating two numbers means joining them together. For example, the concatenation of 121
and 371
is 121371
.
Examples
Example 1
|
|
Example 2
|
|
Constraints
100 <= n <= 999
Solution
Method 1 – Frequency Count and Set Comparison
Intuition
Concatenate n
, 2*n
, and 3*n
to form a 9-digit number. If this number contains all digits from 1 to 9 exactly once (no zeros), then n
is fascinating. This is a direct frequency/counting problem.
Reasoning
By concatenating the numbers and counting the frequency of each digit, we can check if all digits from 1 to 9 appear exactly once and 0 does not appear. If so, the number is fascinating.
Approach
- Concatenate
n
,2*n
, and3*n
as strings. - Check if the length of the concatenated string is 9.
- Count the frequency of each digit in the string.
- Ensure all digits from ‘1’ to ‘9’ appear exactly once and ‘0’ does not appear.
- Return true if all conditions are met, otherwise false.
Edge cases:
- If the concatenated string contains ‘0’ or is not 9 digits, return false.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(1)
, as the number of digits and operations are constant. - 🧺 Space complexity:
O(1)
, as only a fixed number of variables are used.