Open In App

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

Last Updated : 23 Aug, 2021
Improve
Improve
Like Article
Like
Save
Share
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:
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:
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)



Similar Reads

Modify characters of a string by adding integer values of same-indexed characters from another given string
Given two strings S and N of the same length, consisting of alphabetical and numeric characters respectively, the task is to generate a new string obtained by adding the integer value of each character of string N with the ASCII value of the same indexed character of string S. Finally, print the resultant string.Note: If the sum exceeds 122, then s
6 min read
Check if a Binary String can be converted to another by reversing substrings consisting of even number of 1s
Given two binary strings A and B of length N, the task is to check if the string A can be converted to B by reversing substrings of A which contains even number of 1s. Examples: Input: A = "10011", B = "11100"Output: YesExplanation: Reverse substring A[2, 5], 10011 → 11100.After completing the above steps, strings A and B are the same. Input: A = "
9 min read
Bitwise XOR of same indexed array elements after rearranging an array to make XOR of same indexed elements of two arrays equal
Given two arrays A[] and B[] consisting of N positive integers, the task is to the Bitwise XOR of same indexed array elements after rearranging the array B[] such that the Bitwise XOR of the same indexed elements of the arrays A[] becomes equal. Examples: Input: A[] = {1, 2, 3}, B[] = {4, 6, 7}Output: 5Explanation:Below are the possible arrangement
14 min read
Rearrange array such that all even-indexed elements in the Array is even
Given an array arr[], the task is to check if it is possible to rearrange the array in such a way that every even index(1-based indexing) contains an even number. If such a rearrangement is not possible, print "No". Otherwise, print "Yes" and print a possible arrangement Examples: Input: arr[] = {2, 4, 8, 3, 1} Output: Yes 3 4 8 2 1Input: arr[] = {
6 min read
Maximum sum of even indexed elements obtained by right shift on an even sized subarray
Given an array arr[], we need to find the maximum sum of the even indexed elements that can be obtained by performing right shift operation on any sub-array of even length by 1. Examples: Input: arr[] = {5, 1, 3, 4, 5, 6} Output: 15 Explanation: We can perform a right shift on index 2 to 5 then resulting array is: arr[] = {5, 1, 6, 3, 4, 5} Sum of
14 min read
Longest Common Subsequence (LCS) by repeatedly swapping characters of a string with characters of another string
Given two strings A and B of lengths N and M respectively, the task is to find the length of the longest common subsequence that can be two strings if any character from string A can be swapped with any other character from B any number of times. Examples: Input: A = "abdeff", B = "abbet"Output: 4Explanation: Swapping A[5] and B[4] modifies A to "a
7 min read
Minimize swaps of same-indexed characters to make sum of ASCII value of characters of both the strings odd
Given two N-length strings S and T consisting of lowercase alphabets, the task is to minimize the number of swaps of the same indexed elements required to make the sum of the ASCII value of characters of both the strings odd. If it is not possible to make the sum of ASCII values odd, then print "-1". Examples: Input:S = ”acd”, T = ”dbf”Output: 1Exp
9 min read
Minimize a binary string by repeatedly removing even length substrings of same characters
Given a binary string str of size N, the task is to minimize the length of given binary string by removing even length substrings consisting of sam characters, i.e. either 0s or 1s only, from the string any number of times. Finally, print the modified string. Examples: Input: str ="101001"Output: "10"Explanation: The string can be minimized in the
8 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 versa. Examples: Input: S = "011", T = "101" Outpu
15 min read
Minimize cost to make all characters of a Binary String equal to '1' by reversing or flipping characters of substrings
Given a binary string S, and two integers A, which denotes the cost of reversing a substring, and B, which denotes the cost of flipping all characters of a substring, the task is to find the minimum cost to reduce the string S to 1s only. Examples: Input: S = "01100", A = 1, B = 5Output: 6Explanation: One possible way to make all characters equal t
8 min read
Article Tags :
Practice Tags :