Problem · Dynamic Programming
Number of Balanced Strings
Learn this problemProblem statement
Count the balanced strings of length n over the lowercase English alphabet.
A string is balanced when the absolute difference between the alphabet positions of every pair of adjacent characters is at most d.
Return the count modulo 1,000,000,007.
Function
numberOfBalancedStrings(n: int, d: int) → intExamples
Example 1
n = 3d = 3return = 1134Dynamic counting over the final letter gives 1,134 balanced lowercase strings of length 3 when adjacent letters may differ by at most 3.
Example 2
n = 2d = 2return = 124There are 124 ordered pairs of lowercase letters whose alphabet-position difference is at most 2.
Constraints
1 <= n <= 10^60 <= d <= 25