Valid Subarrays With Matching Sum Digits II Problem
Description
LeetCode Problem 3972.
You are given an integer array nums and an integer digit x.
A subarray nums[l..r] is considered valid if the sum of its elements satisfies both of the following conditions:
- The first digit of the sum is equal to
x. - The last digit of the sum is equal to
x.
Return the number of valid subarrays.
Example 1:
Input: nums = [1,100,1], x = 1
Output: 4
Explanation:
The valid subarrays are:
- nums[0..0]: sum = 1
- nums[0..1]: sum = 1 + 100 = 101
- nums[1..2]: sum = 100 + 1 = 101
- nums[2..2]: sum = 1
Thus, the answer is 4.
Example 2:
Input: nums = [1], x = 2
Output: 0
Explanation:
The only subarray is nums[0..0] with a sum of 1, which does not satisfy the conditions.
Thus, the answer is 0.
Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 10^91 <= x <= 9
Solution
Approach: Prefix Sums, Binary Search and Digit Counts
With n up to 105 we cannot look at every subarray. Let pre[i] be the sum of the first i elements. The sum of nums[l..r-1] is pre[r] - pre[l], and because every number is positive, pre is strictly increasing.
Fix the right end r and count the valid left ends l. The two conditions can be handled separately:
- Last digit.
pre[r] - pre[l]ends withxexactly whenpre[l] % 10equals(pre[r] - x) % 10. Precomputecnt[m][i], the number of indices belowiwhose prefix sum ends with digitm. - First digit. The sum starts with
xexactly when it lies in[x * 10^k, (x + 1) * 10^k - 1]for somek. These intervals do not overlap, and since the sum is at most about 1014, there are at most 15 of them. For each interval, the needed valuespre[l]form a range of values, and sincepreis sorted, the matching indices form a contiguous block[lo, hi)that two binary searches find.
For each k, the number of valid left ends in the block is cnt[m][hi] - cnt[m][lo]. Add this up over all k and all r.
Complexity: O(n * D * log n) time, where D (about 15) is the number of digits of the largest sum, and O(10n) space for the digit counts.
from bisect import bisect_left, bisect_right
from itertools import accumulate
class Solution:
def countValidSubarrays(self, nums: List[int], x: int) -> int:
n = len(nums)
pre = [0] + list(accumulate(nums)) # strictly increasing, since nums[i] >= 1
# cnt[m][i]: how many of pre[0..i-1] end with digit m
cnt = [[0] + list(accumulate(1 if p % 10 == m else 0 for p in pre)) for m in range(10)]
ans = 0
for r in range(1, n + 1):
s = pre[r]
c = cnt[(s - x) % 10] # pre[l] must end with this digit for the sum to end with x
# every sum ending at r is at least nums[r - 1], so shorter lengths cannot occur
p = 10 ** max(0, len(str(nums[r - 1])) - 2)
while x * p <= s:
# sum in [x*p, (x+1)*p - 1]: first digit x, and the sum has the same length as x*p
lo = bisect_left(pre, s - ((x + 1) * p - 1), 0, r)
hi = bisect_right(pre, s - x * p, 0, r)
if hi > lo:
ans += c[hi] - c[lo]
p *= 10
return ans