Skip to main content
Back to problems
Codeforces
Medium
Strings
Greedy
Google
Palindrome Transformation

Find the minimum cost to turn a string into a palindrome by moving a cursor and changing characters near a chosen position.

Acceptance 0%
Problem Statement

You are given a lowercase string and a starting cursor position. In one move, you may move the cursor left or right by one position, and moving one step costs 1. You may also change a character at the current cursor position to any other lowercase letter, and changing a character costs the minimum number of circular alphabet steps between the original and new letter.

Your task is to make the whole string a palindrome with minimum total cost. You can choose the order in which positions are visited, but every necessary character change must be performed while the cursor is on that position or its mirrored counterpart, depending on your chosen strategy.

Return the minimum possible total cost.

Input Format

  • A string ss of length nn consisting of lowercase English letters.
  • An integer pp indicating the 1-indexed starting cursor position.

The exact source problem uses a single test case.

Output Format

  • Print one integer: the minimum total cost to transform ss into a palindrome.

Constraints

  • 1n1 \le n.
  • 1pn1 \le p \le n.
  • ss contains only lowercase English letters.
  • The string length is moderate enough for an O(n)O(n) or O(nlogn)O(n \log n) solution in the intended setting.
Examples
Sample cases returned by the problem API.

Example 1

Input

abca
1

Output

2

Explanation

The string is already almost a palindrome; changing one of the middle characters can make it a palindrome with cost 1, and the cursor movement can be arranged with minimal additional cost in this small example. (Illustrative example.)

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.