Count the Number of Ideal Arrays - Problem
Count the Number of Ideal Arrays
You are given two integers
An ideal array is a 0-indexed integer array
โข Every element
โข Each element is divisible by the previous element:
In other words, the array must be non-decreasing and each element must be a multiple of the previous element.
Example: If
Return the count modulo
You are given two integers
n and maxValue, and your task is to find the number of ideal arrays of length n.An ideal array is a 0-indexed integer array
arr of length n that satisfies these conditions:โข Every element
arr[i] is between 1 and maxValue (inclusive)โข Each element is divisible by the previous element:
arr[i] % arr[i-1] == 0 for all i > 0In other words, the array must be non-decreasing and each element must be a multiple of the previous element.
Example: If
n=3, maxValue=5, then [1,2,4] is ideal because 2%1==0 and 4%2==0.Return the count modulo
109 + 7 since the answer can be very large. Input & Output
example_1.py โ Basic Case
$
Input:
n = 2, maxValue = 5
โบ
Output:
10
๐ก Note:
The ideal arrays are: [1,1], [1,2], [1,3], [1,4], [1,5], [2,2], [2,4], [3,3], [4,4], [5,5]. Each array satisfies the divisibility condition.
example_2.py โ Length 3
$
Input:
n = 3, maxValue = 4
โบ
Output:
11
๐ก Note:
Valid arrays include [1,1,1], [1,1,2], [1,1,3], [1,1,4], [1,2,2], [1,2,4], [2,2,2], [2,2,4], [2,4,4], [3,3,3], [4,4,4].
example_3.py โ Edge Case
$
Input:
n = 1, maxValue = 3
โบ
Output:
3
๐ก Note:
With length 1, any single value from 1 to maxValue is valid: [1], [2], [3].
Visualization
Tap to expand
Understanding the Visualization
1
Start with Base
Place any block from 1 to maxValue as the foundation
2
Add Valid Multiples
On each level, only place blocks that are multiples of the one below
3
Count Possibilities
Use DP to count all possible towers of height n
4
Sum Results
Add up counts for all possible ending values
Key Takeaway
๐ฏ Key Insight: An ideal array is essentially a sequence where each element is a multiple of the previous one. We can solve this efficiently using dynamic programming by counting the number of ways to build arrays of each length ending with each possible value.
Time & Space Complexity
Time Complexity
O(maxValue * log(maxValue) + n * P)
Where P is the number of primes up to maxValue. Sieve takes O(maxValue * log(log(maxValue))), DP takes O(n * number of distinct prime factor patterns)
โก Linearithmic
Space Complexity
O(maxValue + n * P)
Store prime factorization for each number plus DP table
โก Linearithmic Space
Constraints
- 2 โค n โค 104
- 1 โค maxValue โค 104
- Return the result modulo 109 + 7
- Each arr[i] must be divisible by arr[i-1]
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code