Saturday, 16 Oct 2021

# Count characters of a string which when removed individually makes the string equal to another string

Count characters of a string which when removed individually makes the string equal to another stringGiven two strings A and B of size N and M respectively, the task is to count characters of the string A, which when removed individually makes both the strings equal. If there exists several such characters, then print their respective positions. Otherwise, print “-1”.Examples:Input: A = “abaac”, B = “abac”Output: 2             3 4Explanation: Following removals are possible that can make the strings equal:Removing A modifies A to “abac”, which becomes equal to B.Removing A modifies A to “abac”, which becomes equal to B.Therefore, two possible removals satisfy the conditions.Input: A = “abs”, B = “bkk”Output: -1Approach: The given problem can be solved based on the following observations: Suppose, if removing the character at index i, makes both strings equal then the prefix of the string i.e substring over the range [0, i-1] must be equal and the suffix of the string i.e substring over the range [i+1, N-1] must be equal too.Suppose i is the index satisfying that the substring over the range [0, i-1] is the longest equal prefix string. And j is the index satisfying that the substring over the range [j+1, N-1] is the longest equal suffix stringThen, if i>=j then only, there exist characters removing which makes the both strings equal. And total count of such characters removing which individually makes the strings equal is i-j+1.Follow the steps below to solve the problem:Initialize two variables say X as 0 and Y as N-1 to store the ending index of the longest equal prefix string and starting index of the longest equal suffix string.Iterate the over the characters of the string B and then in each iteration check if the current character is equal to the character at index X of the string A, then increment X by 1. Otherwise, break.Iterate the over the characters of the string B in reverse and then in each iteration check if the current character is equal to the character at index Y of the string A, then decrement Y by 1. Otherwise, break.Now if the difference between N and M is equal to 1 and Y is less than the X then:Print the total count of such characters as X-Y+1.Then print the indices of the character by iterating over the range [Y+1, X+1].Otherwise, print “-1”.Below is the implementation of the above approach:C++#include using namespace std;void RemoveOneChar(string A, string B,                   int N, int M){            int X = 0;            int Y = N – 1;        for (int i = 0; i < M; i++) {        if (A[X] != B[i])            break;        X++;    }        for (int i = M - 1; i >= 0; i–) {        if (A[Y] != B[i])            break;        Y–;    }            if (N – M == 1 && Y < X) {                        cout