#2549
Count Distinct Numbers on Board
EasyArrayHash TableMathSimulationHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(1) |
| Space | O(n) | O(1) |
💡
Intuition
Time O(1)Space O(1)
In the optimal solution, we recognize that after a few iterations, all numbers from 2 to n will be added to the board, except for 1. This is due to the properties of the modulo operation.
⚙️
Algorithm
3 steps- 1Step 1: If n == 1, return 1 (only 1 is on the board).
- 2Step 2: If n == 2, return 2 (both 1 and 2 are on the board).
- 3Step 3: For n > 2, return n - 1 (all numbers from 2 to n are added).
solution.py4 lines
1def countDistinctNumbers(n):
2 if n == 1:
3 return 1
4 return n - 1ℹ
Complexity note: The time complexity is O(1) because we directly compute the result without any loops. The space complexity is also O(1) as we use a constant amount of space.
- 1After a few iterations, all numbers from 2 to n will be present on the board, except for 1.
- 2The modulo operation reveals a pattern that allows us to predict the final count without simulating each day.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.