#2729
Check if The Number is Fascinating
EasyHash TableMathHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution builds on the brute force approach but uses a set to track the digits. This avoids the need for sorting and allows for a more efficient check for uniqueness and completeness.
⚙️
Algorithm
3 steps- 1Step 1: Calculate 2 * n and 3 * n.
- 2Step 2: Concatenate n, 2 * n, and 3 * n into a single string.
- 3Step 3: Use a set to track digits and ensure all digits from 1 to 9 are present without duplicates.
solution.py3 lines
1def is_fascinating(n):
2 concatenated = str(n) + str(2 * n) + str(3 * n)
3 return len(set(concatenated)) == 9 and '0' not in concatenatedℹ
Complexity note: The time complexity is O(n) because we traverse the concatenated string once. The space complexity is O(n) due to the storage of unique digits in a set.
- 1The problem requires checking for unique digits, which can be efficiently managed using a set.
- 2Understanding the constraints (3-digit numbers) allows for simpler checks without worrying about larger inputs.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.