Problem Description
Given a string s (consisting of lowercase English letters), every character is first mapped to a digit according to a fixed old phone digits mapping (for example, the sample shows that a maps to 1, s maps to 7, d maps to 2, and f maps to 3). A substring (a contiguous non-empty piece of s) is called divisible if the sum of the mapped values of its characters is divisible by the length of the substring. The task is to count how many substrings of s are divisible.
Key Insights
- We can precompute a prefix sum array such that the sum of any substring from index i to j can be computed in O(1) time.
- The divisibility test for a substring with sum S and length L is simply: S % L == 0.
- Since s has at most 2000 characters, a double loop (O(n²)) to try every substring and test its divisibility is acceptable.
Space and Time Complexity
Time Complexity: O(n²) due to the nested loop over all substrings. Space Complexity: O(n) for storing the prefix sum array.
Solution
The solution works as follows:
- Set up a mapping from every lowercase letter to its corresponding digit as provided by the problem statement (for example, from the sample: a = 1, s = 7, d = 2, f = 3; the remaining mappings follow the same pattern).
- Build a prefix sum array where prefix[i+1] holds the sum of mapped digits for the substring s[0...i]. This lets us compute any substring’s sum as prefix[j+1] - prefix[i] in constant time.
- Use two nested loops to iterate over all substrings. For each substring, compute its sum and length, and check if the sum is divisible by the length.
- Count and return the number of substrings that satisfy the divisibility condition.