Given a string password consisting of lowercase English letters and an integer k, return the minimum number of character replacements required to transform password into a palindrome such that the resulting palindrome contains at most k distinct characters.
A replacement changes a single character at one position in the string to any other lowercase English letter. The length of password must remain the same. If it is impossible to satisfy both conditions, return -1.
A palindrome is a string that reads the same forwards and backwards.
Function Signature
def min_replacements(password: str, k: int) -> int:
Rules
-
The distinct-character limit applies to the final string. Any lowercase letter may appear in it, including letters that do not occur in
password
.
-
Under the constraints below a valid result always exists, because a string made of one repeated letter is a palindrome with one distinct character. The
-1
case therefore never occurs for valid input.
Constraints
-
1 <= len(password) <= 1000
-
1 <= k <= 26
-
password
consists of lowercase English letters.
Examples
Input: password = "abca", k = 2
Output: 1
The mirror pairs are (a, a) and (b, c). Using only the letters a and b, the first pair needs nothing and changing the c to b fixes the second, giving "abba".
Input: password = "abcde", k = 1
Output: 4
With one distinct character allowed, every position must hold the same letter. Each letter appears once, so whichever letter is kept, the other 4 positions have to change.
Input: password = "abcdba", k = 2
Output: 2
The pairs are (a, a), (b, b) and (c, d). Changing only one of c or d would leave three distinct letters, and giving up a or b instead costs 2 on that letter's pair plus 1 for (c, d). Changing both c and d to a gives "abaaba", which uses only a and b.