#1735
Count Ways to Make Array With Product
HardArrayMathDynamic ProgrammingCombinatoricsNumber TheoryCombinatoricsPrime Factorization
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(log k + n) |
| Space | O(1) | O(log k) |
💡
Intuition
Time O(log k + n)Space O(log k)
The optimal approach utilizes prime factorization of k and combinatorial mathematics to efficiently calculate the number of ways to distribute the prime factors among the n positions. This avoids the need to generate all combinations.
⚙️
Algorithm
3 steps- 1Step 1: Prime factorize k to get the prime factors and their counts.
- 2Step 2: For each prime factor with count c, calculate the number of ways to distribute c identical items into n distinct boxes using the formula (c + n - 1) choose (n - 1).
- 3Step 3: Multiply the results for all prime factors and take modulo 10^9 + 7.
solution.py32 lines
1# Full working Python code
2from math import comb
3from collections import Counter
4
5MOD = 10**9 + 7
6
7def prime_factors(n):
8 i = 2
9 factors = Counter()
10 while i * i <= n:
11 while (n % i) == 0:
12 factors[i] += 1
13 n //= i
14 i += 1
15 if n > 1:
16 factors[n] += 1
17 return factors
18
19def countWaysOptimal(queries):
20 results = []
21 for n, k in queries:
22 if k == 1:
23 results.append(1)
24 continue
25 factors = prime_factors(k)
26 ways = 1
27 for count in factors.values():
28 ways *= comb(count + n - 1, n - 1)
29 ways %= MOD
30 results.append(ways)
31 return results
32ℹ
Complexity note: The time complexity is O(log k + n) because we are primarily focused on the prime factorization of k, which takes log k time, and then we perform combinatorial calculations for n positions.
- 1Understanding prime factorization is crucial for this problem.
- 2Combinatorial mathematics can significantly reduce the complexity of counting problems.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.