Count the Number of Ideal Arrays - Problem

You are given two integers n and maxValue, which are used to describe an ideal array.

A 0-indexed integer array arr of length n is considered ideal if the following conditions hold:

  • Every arr[i] is a value from 1 to maxValue, for 0 <= i < n.
  • Every arr[i] is divisible by arr[i - 1], for 0 < i < n.

Return the number of distinct ideal arrays of length n. Since the answer may be very large, return it modulo 10^9 + 7.

Input & Output

Example 1 — Basic Case
$ Input: n = 2, maxValue = 3
Output: 5
💡 Note: The 5 ideal arrays are: [1,1], [1,2], [1,3], [2,2], [3,3]. Each array satisfies: all elements ≤ 3, and each element divides the next.
Example 2 — Longer Array
$ Input: n = 3, maxValue = 2
Output: 4
💡 Note: The 4 ideal arrays are: [1,1,1], [1,1,2], [1,2,2], [2,2,2]. All arrays have length 3 with elements ≤ 2.
Example 3 — Single Element
$ Input: n = 1, maxValue = 4
Output: 4
💡 Note: With length 1, any single value is ideal: [1], [2], [3], [4]. No divisibility constraint applies.

Constraints

  • 2 ≤ n ≤ 104
  • 1 ≤ maxValue ≤ 104

Visualization

Tap to expand
Count the Number of Ideal Arrays INPUT Array Structure (n=2) arr[0] arr[1] arr[1] % arr[0] == 0 maxValue = 3 1 2 3 Parameters: n = 2 maxValue = 3 Values: 1, 2, 3 MOD = 10^9 + 7 ALGORITHM STEPS 1 Find Divisor Chains Start from each value 1..maxValue 2 Enumerate Valid Pairs arr[1] must divide by arr[0] Valid Arrays: [1,1] - 1%1=0 OK [1,2] - 2%1=0 OK [1,3] - 3%1=0 OK [2,2] - 2%2=0 OK [3,3] - 3%3=0 OK 3 Count Combinations Use DP with prime factors 4 Sum All Counts 1+3+1 = 5 total arrays FINAL RESULT All 5 Ideal Arrays: [1, 1] [1, 2] [1, 3] [2, 2] [3, 3] Output: 5 OK - Verified 5 mod (10^9+7) = 5 Key Insight: For optimal solution, use prime factorization + combinatorics. Each ideal array corresponds to distributing prime factors across n positions. Count strictly increasing subsequences ending at each value, then use Stars and Bars to count arrangements. Time: O(maxValue * log(maxValue) + n) TutorialsPoint - Count the Number of Ideal Arrays | Optimal Solution
Asked in
Google 15 Meta 8 Amazon 5
25.0K Views
Medium Frequency
~45 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen