Count Ways to Make Array With Product - Problem

You are given a 2D integer array queries. For each queries[i], where queries[i] = [ni, ki], find the number of different ways you can place positive integers into an array of size ni such that the product of the integers is ki.

As the number of ways may be too large, the answer to the ith query is the number of ways modulo 109 + 7.

Return an integer array answer where answer.length == queries.length, and answer[i] is the answer to the ith query.

Input & Output

Example 1 — Basic Query
$ Input: queries = [[2,6],[3,1]]
Output: [4,1]
💡 Note: For [2,6]: arrays [1,6], [2,3], [3,2], [6,1] all have product 6, so 4 ways. For [3,1]: only [1,1,1] has product 1, so 1 way.
Example 2 — Single Element
$ Input: queries = [[1,10]]
Output: [1]
💡 Note: Array of size 1 with product 10: only [10] works, so 1 way.
Example 3 — Larger Array
$ Input: queries = [[4,2]]
Output: [4]
💡 Note: Arrays of size 4 with product 2: [2,1,1,1], [1,2,1,1], [1,1,2,1], [1,1,1,2], so 4 ways.

Constraints

  • 1 ≤ queries.length ≤ 104
  • 1 ≤ ni ≤ 104
  • 1 ≤ ki ≤ 104

Visualization

Tap to expand
Count Ways to Make Array With Product INPUT queries array: queries[0] = [2, 6] n=2 slots, product=6 ? ? queries[1] = [3, 1] n=3 slots, product=1 ? ? ? Goal: Fill arrays with positive integers whose product equals k Prime Factorization: 6 = 2 × 3 1 = (no factors) ALGORITHM STEPS 1 Prime Factorize k Find prime powers of k 2 Stars and Bars Distribute powers to n slots 3 Combinations C(n+e-1, e) for each prime 4 Multiply Results Product of all combinations Example: n=2, k=6 6 = 2^1 × 3^1 For 2^1: C(2+1-1,1) = C(2,1) = 2 For 3^1: C(2+1-1,1) = C(2,1) = 2 Total = 2 × 2 = 4 Ways: [1,6] [6,1] [2,3] [3,2] For k=1: Only [1,1,1] = 1 way FINAL RESULT Output Array: [4, 1] Query 1: [2, 6] answer[0] = 4 [1,6] [6,1] [2,3] [3,2] OK Query 2: [3, 1] answer[1] = 1 [1, 1, 1] only OK Results mod 10^9 + 7 Key Insight: This is a combinatorics problem using Stars and Bars theorem. For each prime factor p^e in k, we need to distribute e copies among n slots. The number of ways is C(n+e-1, e). Multiply results for all prime factors. Precompute factorials for efficient modular combinations. TutorialsPoint - Count Ways to Make Array With Product | Optimal Solution
Asked in
Google 25 Microsoft 18 Amazon 15
15.6K Views
Medium Frequency
~35 min Avg. Time
420 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