- Decide the key that represents the information needed later.
- Update its count or stored state while scanning the input.
- Use constant-time expected lookups to detect matches or assemble the result.
Code notes
- 69 lines of C++ from the credited upstream file 1735.cpp.
- The implementation visibly relies on sequence storage, hash lookup.
- 7 loop blocks detected.
Complexity
Expected hash operations are constant time, but the surrounding scan and the number of stored keys determine total work and memory.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 vector<int> waysToFillArray(vector<vector<int>>& queries) {4 constexpr int kMax = 10000;5 constexpr int kMaxFreq = 13; 6 const vector<int> minPrimeFactors = sieveEratosthenes(kMax + 1);7 const auto [fact, invFact] = getFactAndInvFact(kMax + kMaxFreq - 1);8 vector<int> ans;9 10 for (const vector<int>& query : queries) {11 const int n = query[0];12 const int k = query[1];13 int res = 1;14 for (const auto& [_, freq] : getPrimeFactorsCount(k, minPrimeFactors))15 res = static_cast<long>(res) * nCk(n - 1 + freq, freq, fact, invFact) %16 kMod;17 ans.push_back(res);18 }19 20 return ans;21 }22 23 private:24 static constexpr int kMod = 1'000'000'007;25 26 27 vector<int> sieveEratosthenes(int n) {28 vector<int> minPrimeFactors(n + 1);29 iota(minPrimeFactors.begin() + 2, minPrimeFactors.end(), 2);30 for (int i = 2; i * i < n; ++i)31 if (minPrimeFactors[i] == i) 32 for (int j = i * i; j < n; j += i)33 minPrimeFactors[j] = min(minPrimeFactors[j], i);34 return minPrimeFactors;35 }36 37 unordered_map<int, int> getPrimeFactorsCount(38 int num, const vector<int>& minPrimeFactors) {39 unordered_map<int, int> count;40 while (num > 1) {41 const int divisor = minPrimeFactors[num];42 while (num % divisor == 0) {43 num /= divisor;44 ++count[divisor];45 }46 }47 return count;48 }49 50 pair<vector<long>, vector<long>> getFactAndInvFact(int n) {51 vector<long> fact(n + 1);52 vector<long> invFact(n + 1);53 vector<long> inv(n + 1);54 fact[0] = invFact[0] = 1;55 inv[0] = inv[1] = 1;56 for (int i = 1; i <= n; ++i) {57 if (i >= 2)58 inv[i] = kMod - kMod / i * inv[kMod % i] % kMod;59 fact[i] = fact[i - 1] * i % kMod;60 invFact[i] = invFact[i - 1] * inv[i] % kMod;61 }62 return {fact, invFact};63 }64 65 int nCk(int n, int k, const vector<long>& fact, const vector<long>& invFact) {66 return fact[n] * invFact[k] % kMod * invFact[n - k] % kMod;67 }68};69