Skip to main content

Valid Subarrays With Matching Sum Digits II - Solution & Explanation

HardPremiumFree on FleetCode3 min read
Practice this problem

Problem Statement

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 <= 105
  • 1 <= nums[i] <= 109
  • 1 <= x <= 9

Approach Overview

Problem Overview: You are given an array and must count subarrays where the digit sum of the subarray’s total matches a specific digit-based condition derived from the subarray boundaries. The challenge is that recomputing subarray sums and their digit sums repeatedly becomes expensive for large inputs.

Approach 1: Brute Force Enumeration (O(n²) time, O(1) space)

Generate every possible subarray using two nested loops. For each starting index i, extend the subarray to j while maintaining a running sum. After each extension, compute the digit sum of the current subarray total and check if it satisfies the matching condition. This approach is straightforward and useful for validating logic during development. However, computing up to n(n+1)/2 subarrays makes it impractical for large inputs.

Approach 2: Prefix Sum with On‑Demand Digit Sum (O(n²) time, O(n) space)

Precompute a prefix sum array so any subarray sum can be calculated in constant time using sum(i..j) = prefix[j+1] - prefix[i]. This removes the need to accumulate sums repeatedly. You still iterate over all pairs (i, j), but each subarray sum lookup becomes O(1). The digit sum check remains the main cost. While still quadratic overall, the code is cleaner and easier to reason about than incremental accumulation.

Approach 3: Prefix Transformation + Hash Map (O(n) time, O(n) space)

The key observation is that digit sums follow a predictable modular behavior (digital root). Instead of recomputing digit sums for every subarray, transform prefix sums into their digit-root representation. When two prefixes produce compatible digit signatures, the subarray between them satisfies the matching rule. Maintain a frequency map using a hash map keyed by this transformed value. As you iterate through the array once, compute the current prefix sum, convert it to its digit-root form, and count how many previous prefixes produce a valid match. Each lookup and update is O(1).

This converts a quadratic search into a linear scan because the digit constraint can be expressed using prefix relationships rather than recomputing properties for every subarray. The approach mirrors techniques used in problems involving remainder classes, digit invariants, or prefix transformations.

Recommended for interviews: Interviewers expect the prefix-based optimization. Starting with brute force demonstrates you understand the subarray definition, but the real signal comes from recognizing that digit-sum behavior can be normalized using modular arithmetic and tracked with a hash structure. The final solution combines prefix sums and hash maps to achieve O(n) time, which scales to large inputs.

Solutions for this problem are being prepared.

Try solving it yourself

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force Subarray EnumerationO(n²)O(1)Useful for small inputs or verifying correctness during early implementation
Prefix Sum with Direct Digit Sum CheckO(n²)O(n)Cleaner implementation when prefix sums are already required
Prefix Transformation + Hash MapO(n)O(n)Best for large arrays; converts digit constraint into prefix matching

Frequently Asked Questions

Is Valid Subarrays With Matching Sum Digits II easy or hard?
The problem is categorized as Hard because the digit-sum constraint is not obvious at first glance. Recognizing that digit sums can be normalized with modular arithmetic and combined with prefix-sum counting is the main difficulty.
Valid Subarrays With Matching Sum Digits II Python/Java solution
Most implementations maintain a running prefix sum and compute a digit-root or normalized digit-sum key at each step. A hash map tracks frequencies of previously seen keys. The same algorithm translates easily to Python dictionaries, Java HashMap, or C++ unordered_map with O(n) time complexity.
How to solve Valid Subarrays With Matching Sum Digits II in O(n)?
Compute a running prefix sum while converting it into a digit-root representation that preserves digit-sum behavior. Store frequencies of previously seen transformed values in a hash map. For each new prefix, look up how many prior prefixes form a valid pair and add that count to the result.
What is the best approach for Valid Subarrays With Matching Sum Digits II?
The most efficient solution uses prefix sums combined with a hash map that tracks digit-root transformations of prefix values. This allows subarrays satisfying the digit-sum condition to be detected through prefix relationships. The algorithm runs in O(n) time and O(n) space, making it suitable for large inputs.
Is Valid Subarrays With Matching Sum Digits II asked at Google/Amazon/Meta?
Problems built around prefix sums, digit properties, and hash-map counting patterns frequently appear in interviews at companies like Google, Amazon, and Meta. Variants involving modular arithmetic or digital-root tricks are common in advanced array questions.
What data structure is used in Valid Subarrays With Matching Sum Digits II?
The core data structures are a prefix sum array (or running prefix variable) and a hash map that stores counts of transformed prefix values. The hash map enables constant-time lookups to determine how many earlier prefixes produce a valid subarray.
What is the time complexity of Valid Subarrays With Matching Sum Digits II?
The optimal implementation runs in O(n) time using a prefix-sum scan and constant-time hash lookups. A brute-force approach that checks all subarrays requires O(n²) time because there are n(n+1)/2 possible subarrays.

Ready to solve this problem?

Practice Valid Subarrays With Matching Sum Digits II with our built-in code editor and test cases.

Practice on FleetCode