Check if The Number is Fascinating — Easy Problem & Solution

A three-digit number n is fascinating if, after concatenating n, 2 n and 3 n into one string, the result contains each digit from 1 to 9 exactly once and…

  • Difficulty: Easy
  • Topics: Strings, Math, Hash Table
  • Asked at: TCS, Wipro, Cognizant
  • Time limit: 2 s
  • Memory limit: 256 MB
  • Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby

Problem statement

A three-digit number n is fascinating if, after concatenating n, 2 * n and 3 * n into one string, the result contains each digit from 1 to 9 exactly once and contains no 0.

Return true if n is fascinating.

Example 1

Input: n = 192
Output: true
Explanation: 192, 384 and 576 concatenate to 192384576, which uses 1 through 9 once each.

Example 2

Input: n = 100
Output: false
Explanation: 100200300 is full of zeros.

Example 3

Input: n = 583
Output: false
Explanation: 583, 1166 and 1749 concatenate to eleven digits, so the count is already wrong.

Constraints

  • 100 <= n <= 999

How to solve Check if The Number is Fascinating

The property is stated directly in terms of the digit string, so build it and tally. The length check is a cheap early exit that also guards against 3 * n growing to four digits.

Approach

  1. Concatenate the decimal forms of n, 2 * n and 3 * n.
  2. If the result is not nine characters long, return false.
  3. Tally the digits; reject if any 0 appears or if any digit 1..9 does not appear exactly once.

Why it works

Nine characters holding the nine non-zero digits once each is exactly the definition, and checking the length first means the tally never has to reason about repeated digits in an over-long string.

Complexity

  • Time — O(1)
  • Space — O(1)

Pitfalls

  • Skipping the length check lets a four-digit 3 * n slip through with a coincidentally valid tally prefix.
  • Checking only for duplicates misses a missing digit, and vice versa — both conditions are needed.

Reference solution

Python

def isFascinating(n: int) -> bool:
    joined = str(n) + str(2 * n) + str(3 * n)
    if len(joined) != 9:
        return False
    return sorted(joined) == list("123456789")

JavaScript

var isFascinating = function(n) {
    var joined = String(n) + String(2 * n) + String(3 * n);
    if (joined.length !== 9) return false;
    var seen = [];
    for (var t = 0; t < 10; t++) seen.push(0);
    for (var i = 0; i < joined.length; i++) seen[joined.charCodeAt(i) - 48]++;
    if (seen[0] !== 0) return false;
    for (var d = 1; d <= 9; d++) {
        if (seen[d] !== 1) return false;
    }
    return true;
};

Also on the editorial tab: C, C#, C++, Go, Java, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.

All 282 strings problems · the whole catalogue