Leetcode #1735: Count Ways to Make Array With Product
In this guide, we solve Leetcode #1735 Count Ways to Make Array With Product in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Hard
- Premium: No
- Tags: Array, Math, Dynamic Programming, Combinatorics, Number Theory
Intuition
The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.
A carefully chosen DP state captures exactly what we need to build the final answer.
Approach
Define the DP state and recurrence, then compute states in the correct order.
Optionally compress space once the recurrence is clear.
Steps:
- Choose a DP state definition.
- Write the recurrence and base cases.
- Compute states in the correct order.
Example
Input: queries = [[2,6],[5,1],[73,660]]
Output: [4,1,50734910]
Explanation: Each query is independent.
[2,6]: There are 4 ways to fill an array of size 2 that multiply to 6: [1,6], [2,3], [3,2], [6,1].
[5,1]: There is 1 way to fill an array of size 5 that multiply to 1: [1,1,1,1,1].
[73,660]: There are 1050734917 ways to fill an array of size 73 that multiply to 660. 1050734917 modulo 109 + 7 = 50734910.
Python Solution
N = 10020
MOD = 10**9 + 7
f = [1] * N
g = [1] * N
p = defaultdict(list)
for i in range(1, N):
f[i] = f[i - 1] * i % MOD
g[i] = pow(f[i], MOD - 2, MOD)
x = i
j = 2
while j <= x // j:
if x % j == 0:
cnt = 0
while x % j == 0:
cnt += 1
x //= j
p[i].append(cnt)
j += 1
if x > 1:
p[i].append(1)
def comb(n, k):
return f[n] * g[k] * g[n - k] % MOD
class Solution:
def waysToFillArray(self, queries: List[List[int]]) -> List[int]:
ans = []
for n, k in queries:
t = 1
for x in p[k]:
t = t * comb(x + n - 1, n - 1) % MOD
ans.append(t)
return ans
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.