Minimum cost to convert the given String into Palindrome
Last Updated :
23 Jul, 2025
Given a string S of length N and 2 integers X and Y, the task is to find the minimum cost of converting the string to a palindrome by performing the following operations any number of times in any order:
- Move the leftmost character to the rightmost end of the string at cost X. i.e S1S2...SN gets converted into S2S3...SNS1.
- Replace any character of the string with any lowercase letter at cost Y.
Examples:
Input: N = 5, S = "rrefa", X = 1, Y = 2
Output: 3
Explanation: First pay Y = 2 amount and replace S5 (i.e. 'a') with 'e'. Now the string becomes "rrefe". Now pay X = 1 amount to rotate the string once. Now the string becomes "refer" which is a palindrome. The total cost to achieve the same is 2 + 1 = 3.
Input: N = 8, S = "bcdfcgaa", X = 1000000000, Y = 1000000000
Output: 4000000000
Approach: This can be solved by the following idea:
It does not matter whether we replace a character before or after we move it. So, we will perform all the operation 1s before operation 2s for the sake of simplicity. We will fix how many times we will perform operation 1. Note that after N rotations the string becomes equal to the initial string. So, N-1 rotations are sufficient to arrive at the answer. Then, for each of the first N/2 characters we will check whether it matches with (N - i + 1)th character
(say its palindromic pair). If not, we have to pay cost Y to change any one of them.
The following steps can be used to solve the problem :
- Initialize a variable (say answer) to store the final answer.
- Iterate from i = 0 to N - 1, i.e. fix the number of rotations of the string (operation 1).
- Initialize a variable (say count) by 0 to store the number of operations 2 to be performed.
- Iterate from j = 0 to N - 1 (in the nested loop) to check how many characters of the string are not equal to their palindromic pair.
- If any character is not equal to its palindromic pair, increment the count.
- Calculate the cost of converting the string into palindrome for the current 'i'.
- The minimum of all costs for each iteration would be the final answer.
Following is the code based on the above approach:
C++
// C++ code for the above approach
#include <bits/stdc++.h>
using namespace std;
#define int long long
// Function to find minimum cost to convert
// the given string into palindrome by
// performing the given operations
int minCost(string S, int N, int X, int Y)
{
// Initializing a variable to store
// the final answer
int answer = 1e16;
// Iterating from i=0 to N-1, i.e.
// fixing the rotations of the
// string (operation 1)
for (int i = 0; i < N; i++) {
// Variable to store the number
// of operations 2 to be performed
int count = 0;
// Iterating from j=0 to N-1 to
// check how many characters of
// the string are not equal to
// their palindromic pair
for (int j = 0; j < N; j++) {
// If any character of the
// string is not equal to its
// palindromic pair,
// increment count
if (S[(j + i) % N] != S[(N - 1 - j + i) % N]) {
count++;
}
}
// Cost to convert the string S to
// palindrome when 'i' rotations
// are performed
int cost = X * i + Y * (count / 2);
// Minimum of all these costs would
// be the final answer
answer = min(answer, cost);
}
// Returning answer
return answer;
}
// Driver code
int32_t main()
{
int N = 5, X = 1, Y = 2;
string S = "rrefa";
// Function call
int answer = minCost(S, N, X, Y);
cout << answer;
return 0;
}
Java
import java.util.*;
public class Main {
static long minCost(String S, int N, long X, long Y) {
// Initializing a variable to store
// the final answer
long answer = Long.MAX_VALUE;
// Iterating from i=0 to N-1, i.e.
// fixing the rotations of the
// string (operation 1)
for (int i = 0; i < N; i++) {
// Variable to store the number
// of operations 2 to be performed
int count = 0;
// Iterating from j=0 to N-1 to
// check how many characters of
// the string are not equal to
// their palindromic pair
for (int j = 0; j < N; j++) {
// If any character of the
// string is not equal to its
// palindromic pair,
// increment count
if (S.charAt((j + i) % N) != S.charAt((N - 1 - j + i) % N)) {
count++;
}
}
// Cost to convert the string S to
// palindrome when 'i' rotations
// are performed
long cost = X * i + Y * (count / 2);
// Minimum of all these costs would
// be the final answer
answer = Math.min(answer, cost);
}
// Returning answer
return answer;
}
// Driver code
public static void main(String[] args) {
int N = 5;
long X = 1, Y = 2;
String S = "rrefa";
// Function call
long answer = minCost(S, N, X, Y);
System.out.println(answer);
}
}
Python3
# Python code implementation:
def minCost(S, N, X, Y):
# Initializing a variable to store
# the final answer
answer = float('inf')
# Iterating from i=0 to N-1, i.e.
# fixing the rotations of the
# string (operation 1)
for i in range(N):
# Variable to store the number
# of operations 2 to be performed
count = 0
# Iterating from j=0 to N-1 to
# check how many characters of
# the string are not equal to
# their palindromic pair
for j in range(N):
# If any character of the
# string is not equal to its
# palindromic pair,
# increment count
if S[(j + i) % N] != S[(N - 1 - j + i) % N]:
count += 1
# Cost to convert the string S to
# palindrome when 'i' rotations
# are performed
cost = X * i + Y * (count // 2)
# Minimum of all these costs would
# be the final answer
answer = min(answer, cost)
# Returning answer
return answer
# Driver code
N = 5
X = 1
Y = 2
S = "rrefa"
# Function call
answer = minCost(S, N, X, Y)
print(answer)
# This code is contributed by sankar.
C#
// C# code implemetation
using System;
public class GFG {
static long minCost(string S, int N, long X, long Y)
{
// Initializing a variable to store the final answer
long answer = long.MaxValue;
// Iterating from i=0 to N-1, i.e. fixing the
// rotations of the string (operation 1)
for (int i = 0; i < N; i++) {
// Variable to store the number of operations 2
// to be performed
int count = 0;
// Iterating from j=0 to N-1 to check how many
// characters of the string are not equal to
// their palindromic pair
for (int j = 0; j < N; j++) {
// If any character of the string is not
// equal to its palindromic pair, increment
// count
if (S[(j + i) % N]
!= S[(N - 1 - j + i) % N]) {
count++;
}
}
// Cost to convert the string S to palindrome
// when 'i' rotations are performed
long cost = X * i + Y * (count / 2);
// Minimum of all these costs would be the final
// answer
answer = Math.Min(answer, cost);
}
// Returning answer
return answer;
}
static public void Main()
{
// Code
int N = 5;
long X = 1, Y = 2;
string S = "rrefa";
// Function call
long answer = minCost(S, N, X, Y);
Console.WriteLine(answer);
}
}
// This code is contributed by karthik
JavaScript
// Javascript code for the above approach
function minCost(S, N, X, Y) {
// Initializing a variable to store
// the final answer
let answer = 1e16;
// Iterating from i=0 to N-1, i.e.
// fixing the rotations of the
// string (operation 1)
for (let i = 0; i < N; i++) {
// Variable to store the number
// of operations 2 to be performed
let count = 0;
// Iterating from j=0 to N-1 to
// check how many characters of
// the string are not equal to
// their palindromic pair
for (let j = 0; j < N; j++) {
// If any character of the
// string is not equal to its
// palindromic pair,
// increment count
if (S[(j + i) % N] !== S[(N - 1 - j + i) % N]) {
count++;
}
}
// Cost to convert the string S to
// palindrome when 'i' rotations
// are performed
let cost = X * i + Y * Math.floor(count / 2);
// Minimum of all these costs would
// be the final answer
answer = Math.min(answer, cost);
}
// Returning answer
return answer;
}
// Driver code
let N = 5,
X = 1,
Y = 2;
let S = "rrefa";
// Function call
let answer = minCost(S, N, X, Y);
console.log(answer);
// This code is contributed by Prajwal Kandekar
Time Complexity: O(N*N)
Auxiliary Space: O(1)
New Approach:- Here Another approach to solve this problem is to use dynamic programming. We can define a state dp[i][j] as the minimum cost required to make the substring from i to j a palindrome. We can then use this state to compute the minimum cost required to make the entire string a palindrome.
We can start by initializing all the diagonal elements of the dp matrix to 0, as the minimum cost required to make a single character a palindrome is 0. We can then iterate over all possible substrings of length 2 to N, and compute the minimum cost required to make each substring a palindrome. We can do this by checking if the first and last characters of the substring match, and then adding the cost of either inserting a character or deleting a character based on which operation gives the minimum cost.
The final answer would be the value of dp[0][N-1], which represents the minimum cost required to make the entire string a palindrome.
Algorithm:-
- Define a function minCost that takes four arguments: S, a string of length N that we want to make a palindrome, N, an integer that represents the length of the string S, X, an integer that represents the cost of deleting a character, and Y, an integer that represents the cost of replacing a character.
- Initialize a 2D array dp of size N x N with all elements set to zero. This array will store the minimum cost required to make a substring from i to j a palindrome.
- Set the diagonal elements of the dp matrix to zero. This is because the minimum cost required to make a single character a palindrome is always zero.
- Iterate over all possible substrings of length 2 to N, and compute the minimum cost required to make each substring a palindrome.
- To compute the cost of making a substring a palindrome, we first check if the first and last character of the substring are equal. If they are equal, we do not need to perform any operation, and the cost is equal to the cost of making the remaining substring a palindrome. If they are not equal, we need to perform one of three operations: delete the last character and make the substring i to j-1 a palindrome (cost X), delete the first character and make the substring i+1 to j a palindrome (cost X), or replace the last character with the first character and make the substring i+1 to j-1 a palindrome (cost Y).
- Once we have computed the minimum cost required to make each substring a palindrome, we return the minimum cost required to make the entire string a palindrome, which is stored in the dp[0][N-1] element of the dp matrix.
- In the driver code, we define the values of N, X, Y, and S, and then call the minCost function with these values. We store the result in the answer variable and then print it.
|
Following is the code based on the above approach:-
C++
#include <algorithm>
#include <cstring>
#include <iostream>
using namespace std;
int minCost(string S, int N, int X, int Y)
{
// Initializing a 2D array to store the
// minimum cost required to make a
// substring from i to j a palindrome
int dp[N][N];
// Filling the diagonal elements of the
// dp matrix with 0, as the minimum cost
// required to make a single character
// a palindrome is 0
for (int i = 0; i < N; i++) {
dp[i][i] = 0;
}
// Iterating over all possible substrings
// of length 2 to N, and computing the
// minimum cost required to make each
// substring a palindrome
for (int L = 2; L <= N; L++) {
for (int i = 0; i < N - L + 1; i++) {
int j = i + L - 1;
if (S[i] == S[j]) {
dp[i][j] = dp[i + 1][j - 1];
}
else {
dp[i][j] = min(
min(dp[i][j - 1] + X, dp[i + 1][j] + X),
dp[i + 1][j - 1] + Y);
}
}
}
// Returning the minimum cost required
// to make the entire string a palindrome
return dp[0][N - 1];
}
// Driver Code
int main()
{
int N = 5;
int X = 1;
int Y = 2;
string S = "rrefa";
// Function call
int answer = minCost(S, N, X, Y);
cout << answer << endl;
return 0;
}
Java
public class Main {
public static int minCost(String S, int N, int X, int Y)
{
// Initializing a 2D array to store the
// minimum cost required to make a
// substring from i to j a palindrome
int[][] dp = new int[N][N];
// Filling the diagonal elements of the
// dp matrix with 0, as the minimum cost
// required to make a single character
// a palindrome is 0
for (int i = 0; i < N; i++) {
dp[i][i] = 0;
}
// Iterating over all possible substrings
// of length 2 to N, and computing the
// minimum cost required to make each
// substring a palindrome
for (int L = 2; L <= N; L++) {
for (int i = 0; i < N - L + 1; i++) {
int j = i + L - 1;
if (S.charAt(i) == S.charAt(j)) {
dp[i][j] = dp[i + 1][j - 1];
}
else {
dp[i][j] = Math.min(
Math.min(dp[i][j - 1] + X,
dp[i + 1][j] + X),
dp[i + 1][j - 1] + Y);
}
}
}
// Returning the minimum cost required
// to make the entire string a palindrome
return dp[0][N - 1];
}
// Driver Code
public static void main(String[] args)
{
int N = 5;
int X = 1;
int Y = 2;
String S = "rrefa";
// Function call
int answer = minCost(S, N, X, Y);
System.out.println(answer);
}
}
Python
def minCost(S, N, X, Y):
# Initializing a 2D array to store the
# minimum cost required to make a
# substring from i to j a palindrome
dp = [[0 for i in range(N)] for j in range(N)]
# Filling the diagonal elements of the
# dp matrix with 0, as the minimum cost
# required to make a single character
# a palindrome is 0
for i in range(N):
dp[i][i] = 0
# Iterating over all possible substrings
# of length 2 to N, and computing the
# minimum cost required to make each
# substring a palindrome
for L in range(2, N+1):
for i in range(N-L+1):
j = i + L - 1
if S[i] == S[j]:
dp[i][j] = dp[i+1][j-1]
else:
dp[i][j] = min(dp[i][j-1]+X, dp[i+1][j]+X, dp[i+1][j-1]+Y)
# Returning the minimum cost required
# to make the entire string a palindrome
return dp[0][N-1]
# Driver code
N = 5
X = 1
Y = 2
S = "rrefa"
# Function call
answer = minCost(S, N, X, Y)
print(answer)
C#
using System;
class Program
{
static int MinCost(string S, int N, int X, int Y)
{
// Initializing a 2D array to store the
// minimum cost required to make a
// substring from i to j a palindrome
int[,] dp = new int[N, N];
// Filling the diagonal elements of the
// dp matrix with 0, as the minimum cost
// required to make a single character
// a palindrome is 0
for (int i = 0; i < N; i++)
{
dp[i, i] = 0;
}
// Iterating over all possible substrings
// of length 2 to N, and computing the
// minimum cost required to make each
// substring a palindrome
for (int L = 2; L <= N; L++)
{
for (int i = 0; i < N - L + 1; i++)
{
int j = i + L - 1;
if (S[i] == S[j])
{
dp[i, j] = dp[i + 1, j - 1];
}
else
{
dp[i, j] = Math.Min(Math.Min(dp[i, j - 1] + X,
dp[i + 1, j] + X), dp[i + 1, j - 1] + Y);
}
}
}
// Returning the minimum cost required
// to make the entire string a palindrome
return dp[0, N - 1];
}
static void Main(string[] args)
{
int N = 5;
int X = 1;
int Y = 2;
string S = "rrefa";
// Function call
int answer = MinCost(S, N, X, Y);
Console.WriteLine(answer);
}
}
JavaScript
function minCost(S, N, X, Y)
{
// Initializing a 2D array to store the
// minimum cost required to make a
// substring from i to j a palindrome
const dp = new Array(N);
for (let i = 0; i < N; i++) {
dp[i] = new Array(N).fill(0);
}
// Filling the diagonal elements of the
// dp matrix with 0, as the minimum cost
// required to make a single character
// a palindrome is 0
for (let i = 0; i < N; i++) {
dp[i][i] = 0;
}
// Iterating over all possible substrings
// of length 2 to N, and computing the
// minimum cost required to make each
// substring a palindrome
for (let L = 2; L <= N; L++) {
for (let i = 0; i <= N - L; i++) {
const j = i + L - 1;
if (S[i] === S[j]) {
dp[i][j] = dp[i + 1][j - 1];
} else {
dp[i][j] = Math.min(dp[i][j - 1] + X, dp[i + 1][j] + X, dp[i + 1][j - 1] + Y);
}
}
}
// Returning the minimum cost required
// to make the entire string a palindrome
return dp[0][N - 1];
}
// Driver code
const N = 5;
const X = 1;
const Y = 2;
const S = "rrefa";
// Function call
const answer = minCost(S, N, X, Y);
console.log(answer);
Time Complexity:- The time complexity of the given code is O(N^2) because there are two nested loops, where the outer loop iterates N-1 times and the inner loop iterates N-L+1 times (where L ranges from 2 to N). Each iteration of the inner loop takes constant time, so the total time complexity is O((N-1) * (N-1)) = O(N^2).
Space Complexity:- The space complexity of the given code is also O(N^2) because it uses a 2D array (dp) of size NxN to store the minimum cost required to make each substring a palindrome.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem