- Choose the invariant that makes a window valid or useful.
- Advance the right boundary and add the new element.
- Move the left boundary only as needed while maintaining the invariant and updating the answer.
Code notes
- 56 lines of C++ from the credited upstream file valid-subarrays-with-matching-sum-digits-i.cpp.
- The implementation visibly relies on sequence storage.
- 8 loop blocks detected.
Complexity
Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class Solution {6public:7 int countValidSubarrays(vector<int>& nums, int x) {8 vector<int64_t> prefix(size(nums) + 1);9 for (int i = 0; i < size(nums); ++i) {10 prefix[i + 1] = prefix[i] + nums[i];11 }12 int result = 0;13 for (int64_t base = 1; x * base <= prefix.back(); base *= 10) {14 vector<int64_t> cnt(10);15 for (int i = 0, left = 0, right = 0; i < size(nums); ++i) {16 for (; prefix[right] <= prefix[i + 1] - x * base; ++right) {17 ++cnt[prefix[right] % 10];18 }19 for (; prefix[left] <= prefix[i + 1] - (x + 1) * base; ++left) {20 --cnt[prefix[left] % 10];21 }22 result += cnt[((prefix[i + 1] - x) % 10 + 10) % 10];23 }24 }25 return result;26 }27};28 29303132class Solution2 {33public:34 int countValidSubarrays(vector<int>& nums, int x) {35 const auto& check = [&](auto n) {36 if (n % 10 != x) {37 return false;38 }39 for (; n / 10; n /= 10);40 return n == x;41 };42 43 int result = 0;44 for (int i = 0; i < size(nums); ++i) {45 int64_t total = 0;46 for (int j = i; j < size(nums); ++j) {47 total += nums[j];48 if (check(total)) {49 ++result;50 }51 } 52 }53 return result;54 }55};56