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:
n with the numbers 2 * n and 3 * n.Return true if n is fascinating, or false otherwise.
Concatenating two numbers means joining them together. For example, the concatenation of 121 and 371 is 121371.
Example 1:
Input: n = 192 Output: true Explanation: We concatenate the numbers n = 192 and 2 * n = 384 and 3 * n = 576. The resulting number is 192384576. This number contains all the digits from 1 to 9 exactly once.
Example 2:
Input: n = 100 Output: false Explanation: We concatenate the numbers n = 100 and 2 * n = 200 and 3 * n = 300. The resulting number is 100200300. This number does not satisfy any of the conditions.
Constraints:
100 <= n <= 999This approach uses a set to verify the uniqueness of digits. After concatenating n, 2*n, and 3*n, we convert the result into a set of characters. The number is considered fascinating if the set contains exactly the digits '1' to '9', and if its length is 9.
We use sprintf to concatenate n, 2*n, and 3*n into a string. We then count the frequency of each digit using an array. If the digit '0' appears or any digit appears more than once, we return false. Otherwise, we verify if all digits from 1 to 9 appear exactly once.
C++
Java
Python
C#
JavaScript
Time Complexity: O(1) because the number of digits is constant.
Space Complexity: O(1) because only a fixed amount of extra space is needed.
This approach constructs the concatenated string from n, 2*n, and 3*n and directly checks if the resulting string matches the sorted version of '123456789'. Since the order must not affect the presence of digits between 1 to 9, sorting provides a straightforward comparison for validation.
In this C solution, the concatenated result of n, 2*n, and 3*n is stored in a character array. We use qsort to sort the characters and then check if the resultant sorted string is "123456789". This determines the number's fascinating status.
C++
Java
Python
C#
JavaScript
Time Complexity: O(1), due to constant and fixed string size.
Space Complexity: O(1), since we're using predefined character buffers.
| Approach | Complexity |
|---|---|
| Set-Based Unique Digit Verification | Time Complexity: O(1) because the number of digits is constant. |
| Direct Character Comparison | Time Complexity: O(1), due to constant and fixed string size. |
How to EASILY solve LeetCode problems • NeetCode • 427,736 views views
Watch 9 more video solutions →Practice Check if The Number is Fascinating with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor