Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on String
  • Practice String
  • MCQs on String
  • Tutorial on String
  • String Operations
  • Sort String
  • Substring & Subsequence
  • Iterate String
  • Reverse String
  • Rotate String
  • String Concatenation
  • Compare Strings
  • KMP Algorithm
  • Boyer-Moore Algorithm
  • Rabin-Karp Algorithm
  • Z Algorithm
  • String Guide for CP
Open In App
Next Article:
Count of palindromes that can be obtained by concatenating equal length prefix and substrings
Next article icon

Convert s1 into a Palindrome such that s1 contains s2 as Substring

Last Updated : 02 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given two strings s1 and s2, The task is to convert s1 into a palindrome such that s1 contains s2 as a substring in a minimum number of operations. In a single operation, we can replace any word of s1 with any character. If it is not possible to convert s1 such that it is a palindrome as well as contains a substring of s2, then return -1.

Examples:

Input: s1 = "abaa",  s2 = "bb"
Output: 1
Explanation: We can replace s1[2]='a' with 'b'. So, the new s1 will be like "abba", having s2 as a substring.

Input: s1 = "abbd",  s2 = "mr"
Output: 4
Explanation:

  • 1st: s1="mrbd", 2 operations (this is the minimum operation to make s2 a substring of s1) 
  • 2nd: s1="mrrm",  2 operations  (this is the minimum operation to make s1 palindrome)

Approach: To solve the problem follow the below idea:

The idea is for each index i in s1 we will include s2 and check if it is possible to convert the new string to palindrome without changing the included string s2. If it is possible calculate the cost for each index and return the minimum one, if not then return -1.

Steps to solve the above approach:

  • Traverse string s1 from [0, l1-l2] both inclusive and for each index, i create a new string temp.
  • Temp = k1(substring of s1 from [0, i] ) + s2 + k2(substring of s2 from i+l2 till l1 i.e. [i + l2, l1] ) 
    • For every such replacement of s2 in s1 keep on storing the cost.
    • Now for every such temp created, we need to check if it is possible to create the palindrome without changing replaced s2
    • Run a loop in for every j in temp from [0, ceil(l1/2)) as we are checking for palindrome so no need to traverse half string 
    • If pointer j is outside the indexes of s2 i.e. j < i || j ≥ i + l2 and temp[j]!=temp[l1-j-1] update cost++
    • Now if pointer j is inside the indexes of s2 then we will check if pointer l1-j-1 is outside of indexes of s2 i.e. l1-j-1<i or l1 - j - 1 ≥ i + l2 and temp[j]!=temp[l1-j-1] update cost++.
    • Else if both pointer j and l1-j-1 are inside the indexes of s2 and temp[j]!=temp[l1-j-1] then break the loop. For this index i the cost will be -1.
  • Return the minimum cost for the whole string, return -1 if not possible.

Below is the code to implement the above approach:

C++
// C++ code for the above approach #include <bits/stdc++.h> using namespace std;  // Function to count number of operations // required int specialPalindrome(string s1, string s2) {     int l1 = s1.length(), l2 = s2.length();     int ans = INT_MAX;     for (int i = 0; i < l1 - l2 + 1; i++) {          // Place s2 in all possible         // positions in s1         string temp             = s1.substr(0, i) + s2 + s1.substr(i + l2);         int cost = 0;          // Calculate cost to place s2         for (int j = i; j < i + l2; j++) {              if (s1[j] != temp[j])                 cost++;         }         int z = 0;          // Find the cost to convert new         // string to palindrome         for (int j = 0; j < ceil(l1 / 2.0); j++) {              // If s2 is in the             // first half of new             // string             if ((j < i || j >= i + l2)                 && temp[j] != temp[l1 - j - 1])                 cost++;              // If s2 is in the second             // half of new string             else if (temp[j] != temp[l1 - j - 1]                      && (l1 - j - 1 < i                          || l1 - j - 1 >= i + l2))                 cost++;              // If s2 is in both halves             else if (temp[j] != temp[l1 - j - 1]) {                  z = 1;                 break;             }         }         if (z == 0)             ans = min(ans, cost);     }     if (ans == INT_MAX) {         return -1;     }     return ans; }  // Driver code int main() {      string s1 = "abaa", s2 = "bb";      // Function call     int ans = specialPalindrome(s1, s2);     cout << ans;     return 0; } 
Java
// Java code for the above approach import java.util.*;  public class Main {      // Function to count number of operations     // required     public static int specialPalindrome(String s1,                                         String s2)     {         int l1 = s1.length(), l2 = s2.length();         int ans = Integer.MAX_VALUE;         for (int i = 0; i < l1 - l2 + 1; i++) {              // Place s2 in all possible             // positions in s1             String temp = s1.substring(0, i) + s2                           + s1.substring(i + l2);             int cost = 0;              // Calculate cost to place s2             for (int j = i; j < i + l2; j++) {                  if (s1.charAt(j) != temp.charAt(j))                     cost++;             }             int z = 0;              // Find the cost to convert new             // string to palindrome             for (int j = 0; j < Math.ceil(l1 / 2.0); j++) {                  // If s2 is in the                 // first half of new                 // string                 if ((j < i || j >= i + l2)                     && temp.charAt(j)                            != temp.charAt(l1 - j - 1))                     cost++;                  // If s2 is in the second                 // half of new string                 else if (temp.charAt(j)                              != temp.charAt(l1 - j - 1)                          && (l1 - j - 1 < i                              || l1 - j - 1 >= i + l2))                     cost++;                  // If s2 is in both halves                 else if (temp.charAt(j)                          != temp.charAt(l1 - j - 1)) {                      z = 1;                     break;                 }             }             if (z == 0)                 ans = Math.min(ans, cost);         }         if (ans == Integer.MAX_VALUE) {             return -1;         }         return ans;     }      // Driver code     public static void main(String[] args)     {         String s1 = "abaa", s2 = "bb";          // Function call         int ans = specialPalindrome(s1, s2);         System.out.println(ans);     } } // This code is contributed by Prajwal Kandekar 
Python3
# Python3 code for the above approach  import math  # Function to count number of operations required def specialPalindrome(s1, s2):      l1 = len(s1)     l2 = len(s2)     ans = float('inf')      for i in range(l1-l2+1):          # Place s2 in all possible positions in s1         temp = s1[:i] + s2 + s1[i+l2:]          cost = 0         # Calculate cost to place s2         for j in range(i, i+l2):             if s1[j] != temp[j]:                 cost += 1          z = 0         # Find the cost to convert new string to palindrome         for j in range(math.ceil(l1/2)):             # If s2 is in the first half of new string             if (j < i or j >= i+l2) and temp[j] != temp[l1-j-1]:                 cost += 1             # If s2 is in the second half of new string             elif temp[j] != temp[l1-j-1] and (l1-j-1 < i or l1-j-1 >= i+l2):                 cost += 1             # If s2 is in both halves             elif temp[j] != temp[l1-j-1]:                 z = 1                 break          if z == 0:             ans = min(ans, cost)      if ans == float('inf'):         return -1     return ans  # Driver code if __name__ == '__main__':     s1 = "abaa"     s2 = "bb"      # Function call     ans = specialPalindrome(s1, s2)     print(ans) 
C#
// C# code for the above approach  using System;  public class GFG {      // Function to count number of operations required     static int specialPalindrome(string s1, string s2)     {          int l1 = s1.Length, l2 = s2.Length;         int ans = int.MaxValue;         for (int i = 0; i < l1 - l2 + 1; i++) {              // Place s2 in all possible positions in s1             string temp = s1.Substring(0, i) + s2                           + s1.Substring(i + l2);             int cost = 0;              // Calculate cost to place s2             for (int j = i; j < i + l2; j++) {                  if (s1[j] != temp[j])                     cost++;             }             int z = 0;              // Find the cost to convert new string to             // palindrome             for (int j = 0; j < Math.Ceiling(l1 / 2.0);                  j++) {                  // If s2 is in the first half of new string                 if ((j < i || j >= i + l2)                     && temp[j] != temp[l1 - j - 1])                     cost++;                  // If s2 is in the second half of new string                 else if (temp[j] != temp[l1 - j - 1]                          && (l1 - j - 1 < i                              || l1 - j - 1 >= i + l2))                     cost++;                  // If s2 is in both halves                 else if (temp[j] != temp[l1 - j - 1]) {                     z = 1;                     break;                 }             }             if (z == 0)                 ans = Math.Min(ans, cost);         }         if (ans == int.MaxValue) {             return -1;         }         return ans;     }      static public void Main()     {          // Code         string s1 = "abaa", s2 = "bb";          // Function call         int ans = specialPalindrome(s1, s2);         Console.WriteLine(ans);     } }  // This code is contributed by karthik. 
JavaScript
// Javascript code for the above approach  function specialPalindrome(s1, s2) {      let l1 = s1.length;     let l2 = s2.length;     let ans = Number.MAX_VALUE;      for (let i = 0; i <= l1 - l2; i++) {          // Place s2 in all possible positions in s1         let temp = s1.substring(0, i) + s2 + s1.substring(i + l2);          let cost = 0;         // Calculate cost to place s2         for (let j = i; j < i + l2; j++) {             if (s1[j] != temp[j]) {                 cost += 1;             }         }          let z = 0;         // Find the cost to convert new string to palindrome         for (let j = 0; j < Math.ceil(l1 / 2); j++) {             // If s2 is in the first half of new string             if ((j < i || j >= i + l2) && temp[j] != temp[l1 - j - 1]) {                 cost += 1;             }             // If s2 is in the second half of new string             else if (temp[j] != temp[l1 - j - 1] && (l1 - j - 1 < i || l1 - j - 1 >= i + l2)) {                 cost += 1;             }             // If s2 is in both halves             else if (temp[j] != temp[l1 - j - 1]) {                 z = 1;                 break;             }         }          if (z == 0) {             ans = Math.min(ans, cost);         }     }      if (ans == Number.MAX_VALUE) {         return -1;     }     return ans; }  // Driver code let s1 = "abaa"; let s2 = "bb";  // Function call let ans = specialPalindrome(s1, s2); console.log(ans);  // This code is contributed by Tapesh(tapeshuda420) 

Output
1

Time Complexity: O(N*M) where N is size of s1 and M is size of s2
Auxiliary Space: O(N) because the maximum elements at a time in the temp are the size of S1.


Next Article
Count of palindromes that can be obtained by concatenating equal length prefix and substrings
author
pkrsingh025
Improve
Article Tags :
  • Strings
  • DSA
Practice Tags :
  • Strings

Similar Reads

  • Length of the longest substring that do not contain any palindrome
    Given a string of lowercase, find the length of the longest substring that does not contain any palindrome as a substring. Examples: Input : str = "daiict" Output : 3 dai, ict are longest substring that do not contain any palindrome as substring Input : str = "a" Output : 0 a is itself a palindrome
    6 min read
  • Minimum Repetitions of s1 such that s2 is a substring of it
    Given two strings s1 and s2, the task is to find the minimum number of times s1 has to be repeated such that s2 is a substring of it. If no such solution exists, print -1. Examples: Input: s1 = "abcd", s2 = "cdabcdab"Output: 3 Explanation: After repeating s1 three times, s1 will become “abcdabcdabcd
    15+ min read
  • Check if a string contains a palindromic sub-string of even length
    S is string containing only lowercase English alphabets. We need to find if there exists at least one palindromic sub-string whose length is even. Examples: Input : aassssOutput : YESInput : gfgOutput : NOApproach: Approach to solve this problem is to check all even-length substrings of the given st
    8 min read
  • Count of palindromes that can be obtained by concatenating equal length prefix and substrings
    Prerequisites: Z-algorithm Given a string S, the task is to find the maximum number of palindromes that can be formed after performing the given steps: Choose a non-empty prefix P and a non-empty substring T of equal length.Reverse either P or T and concatenate them. Note: P and T can be overlapping
    6 min read
  • Count substrings of a given string whose anagram is a palindrome
    Given a string S of length N containing only lowercase alphabets, the task is to print the count of substrings of the given string whose anagram is palindromic. Examples: Input: S = "aaaa"Output: 10Explanation:Possible substrings are {"a", "a", "a", "a", "aa", "aa", "aa", "aaa", "aaa", "aaaa"}. Sinc
    10 min read
  • Maximum length palindromic substring such that it starts and ends with given char
    Given a string str and a character ch, the task is to find the longest palindromic sub-string of str such that it starts and ends with the given character ch.Examples: Input: str = "lapqooqpqpl", ch = 'p' Output: 6 "pqooqp" is the maximum length palindromic sub-string that starts and ends with 'p'.I
    7 min read
  • Find the count of palindromic sub-string of a string in its sorted form
    Given string str consisting of lowercase English alphabets, the task is to find the total number of palindromic sub-strings present in the sorted form of str. Examples: Input: str = "acbbd" Output: 6 All palindromic sub-string in it's sorted form ("abbcd") are "a", "b", "b", "bb", "c" and "d". Input
    5 min read
  • Count pair of strings whose concatenation of substrings form a palindrome
    Given an array of strings arr[], the task is to count the pair of strings whose concatenation of substrings form a palindrome.Examples: Input: arr[] = {"gfg", "gfg"} Output: 1 Explanation: One possible way of choosing s1 and s2 is s1 = "gf", s2 = "g" such that s1 + s2 i.e "gfg" is a palindrome.Input
    5 min read
  • Count Palindromic Substrings in a Binary String
    Given a binary string S i.e. which consists only of 0's and 1's. Calculate the number of substrings of S which are palindromes. String S contains at most two 1's. Examples: Input: S = "011"Output: 4Explanation: "0", "1", "1" and "11" are the palindromic substrings. Input: S = "0" Output: 1Explanatio
    7 min read
  • Find a palindromic string B such that given String A is a subsequence of B
    Given a string [Tex]A [/Tex]. Find a string [Tex]B [/Tex], where B is a palindrome and A is a subsequence of B. A subsequence of a string is a string that can be derived from it by deleting some (not necessarily consecutive) characters without changing the order of the remaining characters. For exam
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences