A parcel-sorting conveyor stamps every barcode with a string of lowercase letters, one character per station along the belt. For quality control, the system tracks a running weight as the barcode passes: each letter contributes a value equal to its position in the alphabet ('a' = 1, 'b' = 2, ..., 'z' = 26), and the running weight after station i (for i = 1..n, where n is the barcode's length) is the sum of the letter values of the first i characters — that is, the weight of the length-i prefix of the barcode.
For inspection purposes every prefix is reduced to a residue class by taking its running weight modulo a fixed inspection modulus m. Two prefixes (of possibly different lengths) are called linked if they fall into the same residue class.
Count the number of unordered pairs of prefixes, out of all n prefixes of the barcode, that are linked.
Line 1: a string s of lowercase English letters (the barcode). Line 2: a single integer m (the inspection modulus).
A single integer: the number of unordered pairs of prefixes of s that share the same residue modulo m.
1 <= length of s <= 100000 1 <= m <= 100000 Every character of s is a lowercase English letter ('a'-'z').
Example 1
Input
ab 3
Expected
0
Explanation
Letter values: a=1, b=2. Running weights after each prefix are 1 ("a") and 3 ("ab"). Modulo 3 these are residues 1 and 0 — different, so there are 0 linked pairs.
Example 2
Input
aab 2
Expected
1
Explanation
Letter values: a=1, a=1, b=2. Running weights are 1, 2, 4 for prefixes "a", "aa", "aab". Modulo 2 the residues are 1, 0, 0 — the prefixes "aa" and "aab" share residue 0, giving exactly 1 linked pair.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →