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 numbers 2 * n and 3 * 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

1
2
3
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

1
2
3
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 <= 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

  1. Concatenate n, 2*n, and 3*n as strings.
  2. Check if the length of the concatenated string is 9.
  3. Count the frequency of each digit in the string.
  4. Ensure all digits from ‘1’ to ‘9’ appear exactly once and ‘0’ does not appear.
  5. 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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution {
    public boolean isFascinating(int n) {
        String s = "" + n + (n * 2) + (n * 3);
        if (s.length() != 9) return false;
        int[] cnt = new int[10];
        for (char c : s.toCharArray()) cnt[c - '0']++;
        for (int i = 1; i <= 9; i++) if (cnt[i] != 1) return false;
        return cnt[0] == 0;
    }
}
1
2
3
4
5
6
class Solution:
    def is_fascinating(self, n: int) -> bool:
        s = f"{n}{n*2}{n*3}"
        if len(s) != 9 or '0' in s:
            return False
        return set(s) == set('123456789')

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.