Problem · Dynamic Programming

Number of Balanced Strings

Learn this problem
MediumMoveworksFULLTIMEINTERNOA

Problem 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) → int

Examples

Example 1

n = 3d = 3return = 1134

Dynamic 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 = 124

There are 124 ordered pairs of lowercase letters whose alphabet-position difference is at most 2.

Constraints

  • 1 <= n <= 10^6
  • 0 <= d <= 25

More Moveworks problems

drafts saved locally
public int numberOfBalancedStrings(int n, int d) {
  // write your code here
}
n3
d3
expected1134
checking account