Skip to main content
Back to problems
Leetcode
Medium
Arrays
Math
Combinatorics
Dynamic Programming
Count The Number Of Arrays With K Matching Adjacent Elements

Count how many arrays of length nn over values in [1,m][1, m] have exactly kk adjacent equal pairs.

Acceptance 50%
Problem Statement

You are given three integers nn, mm, and kk.

Count the number of arrays of length nn such that:

  • Each element is an integer from $1totom$ inclusive.
  • Exactly kk indices ii satisfy 1i<n1 \le i < n and ai=ai+1a_i = a_{i+1}.

Return the number of such arrays modulo 109+710^9 + 7.

This is a counting problem: you do not need to construct the arrays, only count how many satisfy the condition.

Input Format

A single test instance is given as three integers:

  • nn — length of the array
  • mm — number of possible values
  • kk — required number of adjacent equal pairs

Output Format

Return one integer: the number of arrays of length nn with exactly kk matching adjacent pairs, modulo 109+710^9 + 7.

Constraints

  • 1n,m1051 \le n, m \le 10^5
  • 0k<n0 \le k < n
  • Answers are taken modulo 109+710^9 + 7

Note: the exact official limits may vary by platform, but the problem is typically solved under modular arithmetic with combinatorial DP.

Examples
Sample cases returned by the problem API.

Example 1

Input

n = 3, m = 2, k = 1

Output

4

Explanation

Arrays of length 3 over {1, 2} with exactly one equal adjacent pair are:

  • [1, 1, 2]
  • [1, 2, 2]
  • [2, 2, 1]
  • [2, 1, 1]

So the answer is 4.

Example 2

Input

n = 2, m = 3, k = 0

Output

6

Explanation

We need arrays of length 2 with no equal adjacent pair. The first element can be any of 3 values, and the second must be different, giving 3×2=63 \times 2 = 6 arrays.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.