- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 61 lines of C++ from the credited upstream file count-valid-sequences.cpp.
- The implementation visibly relies on sequence storage.
- 2 loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45static const uint32_t MOD = 1e9 + 7;6 7uint32_t addmod(uint32_t a, uint32_t b) { 8 if (MOD - a <= b) {9 b -= MOD; 10 }11 return a + b;12}13 14uint32_t submod(uint32_t a, uint32_t b) {15 return addmod(a, (MOD - b) % MOD);16}17 1819uint32_t mulmod(uint32_t a, uint32_t b) { 20 uint32_t result = 0;21 if (a < b) {22 swap(a, b);23 }24 while (b > 0) { 25 if (b & 1) {26 result = addmod(result, a);27 }28 a = addmod(a, a);29 b >>= 1;30 } 31 return result; 32} 33 34vector<int> FACT = {1, 1};35vector<int> INV = {1, 1};36vector<int> INV_FACT = {1, 1};37const int MAX_N = 5e5;38const auto& init = [](int n) {39 while (size(INV) <= n) { 40 FACT.emplace_back(mulmod(FACT.back(), size(INV)));41 INV.emplace_back(mulmod(INV[MOD % size(INV)], MOD - MOD / size(INV))); 42 INV_FACT.emplace_back(mulmod(INV_FACT.back(), INV.back()));43 }44 return 0;45}(MAX_N);46 47class Solution {48public:49 int countValidSequences(int n, int k) {50 const auto& nCr = [](int n, int k) {51 return mulmod(mulmod(FACT[n], INV_FACT[n - k]), INV_FACT[k]);52 };53 54 const auto& nHr = [&](int n, int k) {55 return nCr(n + k - 1, k);56 };57 58 return submod(nHr(k, n - k), (n - k) % 2 == 0 ? nHr(k, (n - k) / 2) : 0);59 }60};61