Valid Subarrays With Matching Sum Digits I Problem
Description
LeetCode Problem 3969.
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 <= 15001 <= nums[i] <= 10^91 <= x <= 9
Solution
Approach: Enumeration
With n at most 1500, we can afford to look at every subarray. Fix the left end l, then extend the right end r one element at a time while keeping a running sum s of nums[l..r].
For each sum, check both conditions: the last digit is s % 10, and the first digit is the first character of the decimal string of s. Both must equal x. The sum can reach about 1.5 * 1012, so it needs a 64-bit integer in Java, C++ and Go.
Complexity: O(n2) time and O(1) extra space, where n is the length of nums.
class Solution:
def countValidSubarrays(self, nums: List[int], x: int) -> int:
n = len(nums)
ans = 0
for l in range(n):
s = 0
for r in range(l, n):
s += nums[r]
if s % 10 == x and int(str(s)[0]) == x:
ans += 1
return ans