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
  • Practice Searching Algorithms
  • MCQs on Searching Algorithms
  • Tutorial on Searching Algorithms
  • Linear Search
  • Binary Search
  • Ternary Search
  • Jump Search
  • Sentinel Linear Search
  • Interpolation Search
  • Exponential Search
  • Fibonacci Search
  • Ubiquitous Binary Search
  • Linear Search Vs Binary Search
  • Interpolation Search Vs Binary Search
  • Binary Search Vs Ternary Search
  • Sentinel Linear Search Vs Linear Search
Open In App
Next Article:
Convert given Strings into T by replacing characters in between strings any number of times
Next article icon

Replace even-indexed characters of minimum number of substrings to convert a string to another

Last Updated : 23 Aug, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given two strings, str1 and str2 of length N, the task is to convert the string str1 to string str2 by selecting a substring and replacing all characters present at even indices of the substring by any possible characters, even number of times.

Examples:

Input: str1 = “abcdef”, str2 = “ffffff” 
Output: 2 
Explanation: 
Selecting the substring {str1[0], …, str[4]} and replacing all the even indices of the substring by ‘f’ modifies str1 to “fbfdff”. 
Selecting the substring {str1[1], …, str[3]} and replacing all the even indices of the substring by ‘f’ modifies str1 to “ffffff”, which is the same as str2. 
Therefore, the required output is 2.

Input: str1 = “rtrtyy”, str2 = “wtwtzy” 
Output: 1 
Explanation: 
Selecting the substring {str1[0], …, str[4]} and replacing str1[0] by ‘w’, str1[[2] by ‘w’ and str[4] by ‘t’ modifies str1 to “wtwtzy”, which is same as str2. Therefore, the required output is 1.

Approach: The problem can be solved using Greedy technique. Follow the steps below to solve the problem:

  • Initialize a variable, say cntOp, to store the minimum count of given operations required to convert the string str1 to str2.
  • Iterate over the characters of the string. For every ith index, check if str1[i] and str2[i] are same or not. If found to be different, then find the longest substring possible that contains different characters at even indices in both the strings. Replace even indexed characters of that substring of str1 and increment the value of cntOp by 1.
  • Finally, print the value of cntOp.

Below is the implementation of the above approach:

C++




// C++ program to implement
// the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to count the minimum number of
// substrings of str1 such that replacing
// even-indexed characters of those substrings
// converts the string str1 to str2
int minOperationsReq(string str1, string str2)
{
    // Stores length of str1
    int N = str1.length();
 
    // Stores minimum count of operations
    // to convert str1 to str2
    int cntOp = 0;
 
    // Traverse both the given string
    for (int i = 0; i < N; i++) {
 
        // If current character in
        // both the strings are equal
        if (str1[i] == str2[i]) {
            continue;
        }
 
        // Stores current index
        // of the string
        int ptr = i;
 
        // If current character in both
        // the strings are not equal
        while (ptr < N && str1[ptr] != str2[ptr]) {
 
            // Replace str1[ptr]
            // by str2[ptr]
            str1[ptr] = str2[ptr];
 
            // Update ptr
            ptr += 2;
        }
 
        // Update cntOp
        cntOp++;
    }
 
    return cntOp;
}
 
// Driver Code
int main()
{
    string str1 = "abcdef";
    string str2 = "ffffff";
 
    cout << minOperationsReq(str1, str2);
    return 0;
}
 
 

Java




// Java program to implement
// the above approach
 
import java.io.*;
 
class GFG {
 
    // Function to count the minimum number of
    // substrings of str1 such that replacing
    // even-indexed characters of those substrings
    // converts the string str1 to str2
    static int min_Operations(String str1,
                              String str2)
    {
        // Stores length of str1
        int N = str1.length();
 
        // Convert str1 to character array
        char[] str = str1.toCharArray();
 
        // Stores minimum count of operations
        // to convert str1 to str2
        int cntOp = 0;
 
        // Traverse both the given string
        for (int i = 0; i < N; i++) {
 
            // If current character in both
            // the strings are equal
            if (str[i] == str2.charAt(i)) {
                continue;
            }
 
            // Stores current index
            // of the string
            int ptr = i;
 
            // If current character in both the
            // string are not equal
            while (ptr < N && str[ptr] != str2.charAt(ptr)) {
 
                // Replace str1[ptr]
                // by str2[ptr]
                str[ptr] = str2.charAt(ptr);
 
                // Update ptr
                ptr += 2;
            }
 
            // Update cntOp
            cntOp++;
        }
 
        return cntOp;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        String str1 = "abcdef";
        String str2 = "ffffff";
        System.out.println(
            min_Operations(str1, str2));
    }
}
 
 

Python3




# Python3 program to implement
# the above approach
  
# Function to count the minimum number of
# substrings of str1 such that replacing
# even-indexed characters of those substrings
# converts the str1 to str2
def minOperationsReq(str11, str22):
     
    str1 = list(str11)
    str2 = list(str22)
         
    # Stores length of str1
    N = len(str1)
  
    # Stores minimum count of operations
    # to convert str1 to str2
    cntOp = 0
  
    # Traverse both the given string
    for i in range(N):
  
        # If current character in
        # both the strings are equal
        if (str1[i] == str2[i]):
            continue
         
        # Stores current index
        # of the string
        ptr = i
  
        # If current character in both
        # the strings are not equal
        while (ptr < N and str1[ptr] != str2[ptr]):
  
            # Replace str1[ptr]
            # by str2[ptr]
            str1[ptr] = str2[ptr]
  
            # Update ptr
            ptr += 2
         
        # Update cntOp
        cntOp += 1
     
    return cntOp
 
# Driver Code
str1 = "abcdef"
str2 = "ffffff"
  
print(minOperationsReq(str1, str2))
 
# This code is contributed by code_hunt
 
 

C#




// C# program to implement
// the above approach
using System;
 
class GFG
{
 
    // Function to count the minimum number of
    // substrings of str1 such that replacing
    // even-indexed characters of those substrings
    // converts the string str1 to str2
    static int min_Operations(String str1,
                              String str2)
    {
       
        // Stores length of str1
        int N = str1.Length;
 
        // Convert str1 to character array
        char[] str = str1.ToCharArray();
 
        // Stores minimum count of operations
        // to convert str1 to str2
        int cntOp = 0;
 
        // Traverse both the given string
        for (int i = 0; i < N; i++)
        {
 
            // If current character in both
            // the strings are equal
            if (str[i] == str2[i])
            {
                continue;
            }
 
            // Stores current index
            // of the string
            int ptr = i;
 
            // If current character in both the
            // string are not equal
            while (ptr < N && str[ptr] != str2[ptr])
            {
 
                // Replace str1[ptr]
                // by str2[ptr]
                str[ptr] = str2[ptr];
 
                // Update ptr
                ptr += 2;
            }
 
            // Update cntOp
            cntOp++;
        }
 
        return cntOp;
    }
 
    // Driver Code
    public static void Main(String[] args)
    {
        String str1 = "abcdef";
        String str2 = "ffffff";
        Console.WriteLine(
            min_Operations(str1, str2));
    }
}
 
// This code contributed by gauravrajput1
 
 

Javascript




<script>
 
// Javascript program to implement
// the above approach
 
// Function to count the minimum number of
    // substrings of str1 such that replacing
    // even-indexed characters of those substrings
    // converts the string str1 to str2
    function min_Operations( str1,  str2)
    {
        // Stores length of str1
    var N = str1.length;
 
    // Stores minimum count of operations
    // to convert str1 to str2
    var cntOp = 0;
 
    // Traverse both the given string
    for (var i = 0; i < N; i++) {
 
        // If current character in
        // both the strings are equal
        if (str1.charCodeAt(i)== str2.charCodeAt(i))
        {
        
            continue;
        }
 
        // Stores current index
        // of the string
        var ptr = i;
 
        // If current character in both
        // the strings are not equal
        while (ptr < N && str1[ptr] != str2[ptr]) {
 
            // Replace str1[ptr]
            // by str2[ptr]
           
            str1 = str1.substring(0, ptr) + str2[ptr]
            + str1.substring(ptr + 1);
            // Update ptr
            ptr += 2;
        }
 
        // Update cntOp
        cntOp++;
    }
 
    return cntOp;
    }
 
    // Driver Code
     
         str1 = "abcdef";
         str2 = "ffffff";
        document.write(min_Operations(str1, str2));
 
// This code is contributed by todaysgaurav
 
</script>
 
 
Output: 
2

 

Time complexity: O(N) 
Auxiliary Space: O(1)



Next Article
Convert given Strings into T by replacing characters in between strings any number of times

R

RohitOberoi
Improve
Article Tags :
  • DSA
  • Searching
  • Strings
  • substring
Practice Tags :
  • Searching
  • Strings

Similar Reads

  • Convert given Strings into T by replacing characters in between strings any number of times
    Given an array, arr[] of N strings and a string T of size M, the task is to check if it is possible to make all the strings in the array arr[] same as the string T by removing any character from one string, say arr[i] and inserting it at any position to another string arr[j] any number of times. Exa
    9 min read
  • Minimum number of given operations required to convert a string to another string
    Given two strings S and T of equal length. Both strings contain only the characters '0' and '1'. The task is to find the minimum number of operations to convert string S to T. There are 2 types of operations allowed on string S: Swap any two characters of the string.Replace a '0' with a '1' or vice
    15 min read
  • Minimum number of subsequences required to convert one string to another
    Given two strings A and B consisting of only lowercase letters, the task is to find the minimum number of subsequences required from A to form B. Examples: Input: A = "abbace" B = "acebbaae" Output: 3 Explanation: Sub-sequences "ace", "bba", "ae" from string A used to form string B Input: A = "abc"
    8 min read
  • Minimum number of characters to be replaced to make a given string Palindrome
    Given string str, the task is to find the minimum number of characters to be replaced to make a given string palindrome. Replacing a character means replacing it with any single character in the same position. We are not allowed to remove or add any characters. If there are multiple answers, print t
    5 min read
  • Minimum moves to make String Palindrome incrementing all characters of Substrings
    Given a string S of length N, the task is to find the minimum number of moves required to make a string palindrome where in each move you can select any substring and increment all the characters of the substring by 1. Examples: Input: S = "264341"Output: 2?Explanation: We can perform the following
    6 min read
  • Minimum number of subsequences required to convert one string to another using Greedy Algorithm
    Given two strings A and B consists of lowercase letters, the task to find the minimum number of subsequence required to form A from B. If it is impossible to form, print -1.Examples: Input: A = "aacbe", B = "aceab" Output: 3 Explanation: The minimum number of subsequences required for creating A fro
    13 min read
  • Minimize length of prefix of string S containing all characters of another string T
    Given two string S and T, the task is to find the minimum length prefix from S which consists of all characters of string T. If S does not contain all characters of string T, print -1. Examples: Input: S = "MarvoloGaunt", T = "Tom" Output: 12 Explanation: The 12 length prefix "MarvoloGaunt" contains
    7 min read
  • Minimum characters to be replaced in Ternary string to remove all palindromic substrings for Q queries
    Given a ternary string S of length N containing only '0', '1' and '2' characters and Q queries containing a range of indices [L, R], the task for each query [L, R] is to find the minimum number of characters to convert to either '0', '1' or '2' such that there exists no palindromic substring of leng
    11 min read
  • Count characters to be shifted from the start or end of a string to obtain another string
    Given two strings A and B where string A is an anagram of string B. In one operation, remove the first or the last character of the string A and insert at any position in A. The task is to find the minimum number of such operations required to be performed to convert string A into string B. Examples
    6 min read
  • Minimum characters to be replaced in given String to make all characters same
    Given a string str of size N consisting of lowercase English characters, the task is to find the minimum characters to be replaced to make all characters of string str same. Any character can be replaced by any other character. Example: Input: str="geeksforgeeks"Output: 9Explanation: Replace all the
    7 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