#3869
Count Fancy Numbers in a Range
HardMathDynamic ProgrammingHash 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)
Precompute all good numbers and their sums to quickly determine if a number is fancy without checking each one individually.
⚙️
Algorithm
3 steps- 1Step 1: Precompute all good numbers (strictly increasing and decreasing) up to a certain limit.
- 2Step 2: Precompute good sums for numbers from 1 to 144.
- 3Step 3: For each number in the range [l, r], check against precomputed good numbers and sums.
solution.py16 lines
1def precompute_goods():
2 goods = set()
3 for i in range(1, 10):
4 goods.add(i)
5 for i in range(1, 10):
6 for j in range(i + 1, 10):
7 goods.add(int(str(i) + str(j)))
8 return goods
9
10def count_fancy(l, r):
11 goods = precompute_goods()
12 count = 0
13 for i in range(l, r + 1):
14 if i in goods or sum(int(d) for d in str(i)) in goods:
15 count += 1
16 return countℹ
Complexity note: Precomputation allows for constant-time checks against good numbers, making the overall complexity linear.
- 1Single-digit numbers are always good.
- 2The sum of digits can also be good, which adds complexity.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.