Problem Statement

Given two integers n and k, consider an alphabet consisting of the first k lowercase English letters.

We need to find the number of palindromic strings whose length is less than or equal to n, subject to the following conditions:

  1. Every character must belong to the first k lowercase English letters.

  2. No character can appear more than twice.

  3. Return the answer modulo 10^9 + 7.

Example 1

Code
Input:
n = 3
k = 2

Output:
6

The valid strings are:

Code
a
b
aa
bb
aba
bab

Therefore, the answer is 6.

Example 2

Code
Input:
n = 4
k = 3

Output:
18

The valid strings are:

Code
a
b
c

aa
bb
cc

aba
aca
bab
bcb
cac
cbc

abba
acca
baab
bccb
caac
cbbc

Therefore, the answer is 18.

Important Observation

The most important part of this problem is understanding the structure of a palindrome.

A palindrome reads the same from left to right and right to left.

For example:

Code
aba
abba
abcba

Because every character can appear at most twice, a character used in a palindrome can generally appear:

This allows us to divide the problem into two cases:

  1. Even-length palindromes

  2. Odd-length palindromes

Case 1: Even-Length Palindromes

Suppose the length is:

Code
2 * m

For example:

Code
abba

The characters are:

Code
a b b a

Here, a appears twice and b appears twice.

Because no character can appear more than twice, all m characters in the first half must be different.

For example, with k = 3:

Code
a b

produces:

Code
abba

The first half determines the second half.

If we choose:

Code
a, b

the palindrome is:

Code
abba

If we choose:

Code
a, c

the palindrome is:

Code
acca

Therefore, for an even-length palindrome of length 2m, we need to select and arrange m distinct characters from k characters.

This is a permutation.

The number of possibilities is:

Code
P(k, m)

or:

Code
k * (k - 1) * (k - 2) * ... * (k - m + 1)

Example

For:

Code
k = 3
m = 2

we have:

Code
P(3, 2)
= 3 * 2
= 6

The six palindromes are:

Code
abba
acca
baab
bccb
caac
cbbc

Case 2: Odd-Length Palindromes

Now consider a palindrome of length:

Code
2 * m + 1

For example:

Code
aba

The structure is:

Code
a b a

The middle character can occur only once.

The remaining m characters form pairs.

For example:

Code
abcba

has the structure:

Code
a b c b a

Here:

The middle character can be selected in k ways.

After selecting the middle character, we need to select and arrange m different characters from the remaining k - 1 characters.

Therefore:

Code
Count = k * P(k - 1, m)

Example of Odd-Length Calculation

Suppose:

Code
n = 5
k = 3

For length 3:

Code
m = 1

Formula:

Code
k * P(k - 1, 1)

= 3 * 2

= 6

The palindromes are:

Code
aba
aca
bab
bcb
cac
cbc

For length 5:

Code
m = 2

Formula:

Code
3 * P(2, 2)

= 3 * 2 * 1

= 6

The palindromes are:

Code
abcba
acbca
bacab
bcacb
cabac
cbabc

Combining Both Cases

We need all palindromes whose length is at most n.

Therefore, we add:

Code
Length 1
Length 2
Length 3
Length 4
...
Length n

But instead of calculating every palindrome explicitly, we use the formulas.

For even length:

Code
2m

Count = P(k, m)

For odd length:

Code
2m + 1

Count = k * P(k - 1, m)

Java Solution

Java
class Solution {
    static final long MOD = 1000000007L;

    public int palindromicStrings(int n, int k) {
        long ans = 0;

        // Even length: 2 * len
        // Count = P(k, len)
        long perm = 1;

        for (int len = 1; len <= k && 2 * len <= n; len++) {
            perm = (perm * (k - len + 1)) % MOD;
            ans = (ans + perm) % MOD;
        }

        // Odd length: 2 * len + 1
        // Count = k * P(k - 1, len)
        perm = 1;

        for (int len = 0; len <= k - 1 && 2 * len + 1 <= n; len++) {

            if (len > 0) {
                perm = (perm * (k - len)) % MOD;
            }

            long count = (k * perm) % MOD;
            ans = (ans + count) % MOD;
        }

        return (int) ans;
    }
}

Detailed Code Explanation

1. Modulo Value

Java
static final long MOD = 1000000007L;

The number of possible strings can become very large.

The problem asks us to return the answer modulo:

Code
10^9 + 7

So we perform modulo after every multiplication and addition.

2. Store the Answer

Java
long ans = 0;

ans stores the total number of valid palindromic strings.

We use long because multiplication can temporarily produce values larger than the range of int.

3. Calculate Even-Length Palindromes

Java
long perm = 1;

for (int len = 1; len <= k && 2 * len <= n; len++) {
    perm = (perm * (k - len + 1)) % MOD;
    ans = (ans + perm) % MOD;
}

Here:

Code
2 * len

represents the palindrome length.

For example:

Code
len = 1 → length 2
len = 2 → length 4
len = 3 → length 6

The variable perm maintains:

Code
P(k, len)

Iteration Example

Suppose:

Code
k = 4

Initially:

Code
perm = 1

For len = 1:

Code
perm = 1 * 4
      = 4

So:

Code
P(4,1) = 4

For len = 2:

Code
perm = 4 * 3
      = 12

So:

Code
P(4,2) = 12

For len = 3:

Code
perm = 12 * 2
      = 24

So:

Code
P(4,3) = 24

This avoids calculating factorials separately.

4. Calculate Odd-Length Palindromes

Java
perm = 1;

for (int len = 0; len <= k - 1 && 2 * len + 1 <= n; len++) {

Here:

Code
2 * len + 1

represents the odd palindrome length.

For example:

Code
len = 0 → length 1
len = 1 → length 3
len = 2 → length 5
len = 3 → length 7

5. Calculate P(k - 1, len)

Java
if (len > 0) {
    perm = (perm * (k - len)) % MOD;
}

For odd-length palindromes, one character is reserved for the middle.

Therefore, the remaining characters are selected from:

Code
k - 1

characters.

The required permutation is:

Code
P(k - 1, len)

The code calculates this incrementally.

For example, if:

Code
k = 4

then:

Code
P(3, 0) = 1
P(3, 1) = 3
P(3, 2) = 6
P(3, 3) = 6

6. Select the Middle Character

Java
long count = (k * perm) % MOD;

There are k choices for the middle character.

Therefore:

Code
Odd palindrome count
=
k * P(k - 1, len)

For example:

Code
k = 3
len = 1

Then:

Code
P(2,1) = 2

Therefore:

Code
count = 3 * 2
      = 6

7. Add to the Answer

Java
ans = (ans + count) % MOD;

We add the number of palindromes of the current length to the total answer.

Dry Run

Consider:

Code
n = 4
k = 3

The alphabet is:

Code
a, b, c

Length 1

Odd case:

Code
len = 0

count = 3 * P(2,0)
      = 3 * 1
      = 3

Strings:

Code
a
b
c

Total:

Code
3

Length 2

Even case:

Code
len = 1

count = P(3,1)
      = 3

Strings:

Code
aa
bb
cc

Total:

Code
3 + 3 = 6

Length 3

Odd case:

Code
len = 1

count = 3 * P(2,1)
      = 3 * 2
      = 6

Strings:

Code
aba
aca
bab
bcb
cac
cbc

Total:

Code
6 + 6 = 12

Length 4

Even case:

Code
len = 2

count = P(3,2)
      = 3 * 2
      = 6

Strings:

Code
abba
acca
baab
bccb
caac
cbbc

Total:

Code
12 + 6 = 18

Therefore:

Code
Answer = 18

Why We Do Not Need Dynamic Programming

Although the problem has a Dynamic Programming tag, the constraints and palindrome structure allow us to solve it directly using combinatorics.

The important fact is:

Once the first half of the palindrome is chosen, the second half is completely determined.

For example:

Code
First half: abc

The complete palindrome is:

Code
abccba

Therefore, we only need to count valid ways to construct the first half.

Because each character can occur at most twice, the characters in the first half must be distinct.

This converts the problem into a permutation-counting problem.

Why n <= 2 * k Matters

A palindrome of even length 2m needs m different characters.

Since there are only k available characters:

Code
m <= k

Similarly, an odd palindrome of length 2m + 1 needs m paired characters plus one middle character.

The constraint:

Code
n <= 2 * k

ensures that we never need more than k characters in the paired portion.

Complexity Analysis

The even-length loop runs at most k times.

The odd-length loop also runs at most k times.

Therefore:

Code
Time Complexity: O(k)

Only a few variables are used:

Code
ans
perm
count

Therefore:

Code
Auxiliary Space: O(1)

This is better than the expected:

Code
Time: O(k²)
Space: O(k²)

Final Formula

For every possible palindrome length:

Even length

For length:

Code
2m

the number of palindromes is:

Code
P(k, m)

Odd length

For length:

Code
2m + 1

the number of palindromes is:

Code
k × P(k - 1, m)

Therefore, the complete answer is:

Code
Σ P(k, m)       for every 2m <= n

+

Σ k × P(k-1, m) for every 2m+1 <= n

All calculations are performed modulo:

Code
1,000,000,007

Key Takeaway

The trick is not to generate the strings.

Instead:

  1. Divide the palindrome into even and odd lengths.

  2. For an even palindrome, choose and arrange distinct characters for the first half.

  3. For an odd palindrome, choose the middle character and then arrange distinct characters for the first half.

  4. Use permutations instead of generating strings.

  5. Calculate permutations incrementally to achieve O(k) time and O(1) extra space.

This turns what looks like a string-generation problem into a simple combinatorial counting problem.