Minimize a string by removing all occurrences of another string

27 May, 2022
Given two strings S1 and S2 of length N and M respectively, consisting of lowercase letters, the task is to find the minimum length to which S1 can be reduced by removing all occurrences of the string S2 from the string S1.
Examples:
Input: S1 =”fffoxoxoxfxo”, S2 = “fox”;Output: 3Explanation:By removing “fox” starting from index 2, the string modifies to “ffoxoxfxo”.By removing “fox” starting from index 1, the string modifies to “foxfxo”.By removing “fox” starting from index 0, the string modifies to “fxo”.Therefore, the minimum length of string S1 after removing all occurrences of S2 is 3.
Input: S1 =”abcd”, S2 = “pqr”Output: 4
Approach: The idea to solve this problem is to use Stack Data Structure. Follow the steps below to solve the given problem:
Initialize a stack to store the characters of the string S1 in it.
Traverse the given string S1 and perform the following operations:Push the current character in the stack.If the size of the stack is at least M, then check if the top M characters of the stack form the string S2 or not. If found to be true, then remove those characters.
Push the current character in the stack.
If the size of the stack is at least M, then check if the top M characters of the stack form the string S2 or not. If found to be true, then remove those characters.
After completing the above steps, the remaining size of the stack is the required minimum length.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h> using namespace std; // Function to find the minimum length// to which string str can be reduced to// by removing all occurrences of string Kint minLength(string str, int N,              string K, int M){     // Initialize stack of characters    stack<char> stackOfChar;     for (int i = 0; i < N; i++) {         // Push character into the stack        stackOfChar.push(str[i]);         // If stack size >= K.size()        if (stackOfChar.size() >= M) {             // Create empty string to            // store characters of stack            string l = "";             // Traverse the string K in reverse            for (int j = M - 1; j >= 0; j--) {                 // If any of the characters                // differ, it means that K                // is not present in the stack                if (K[j] != stackOfChar.top()) {                     // Push the elements                    // back into the stack                    int f = 0;                    while (f != l.size()) {                         stackOfChar.push(l[f]);                        f++;                    }                     break;                }                 // Store the string                else {                     l = stackOfChar.top()                        + l;                     // Remove top element                    stackOfChar.pop();                }            }        }    }     // Size of stack gives the    // minimized length of str    return stackOfChar.size();} // Driver Codeint main(){    string S1 = "fffoxoxoxfxo";    string S2 = "fox";     int N = S1.length();    int M = S2.length();     // Function Call    cout << minLength(S1, N, S2, M);    return 0;}
// Java program for the above approachimport java.util.*;class GFG{ // Function to find the minimum length// to which String str can be reduced to// by removing all occurrences of String Kstatic int minLength(String str, int N,              String K, int M){     // Initialize stack of characters    Stack<Character> stackOfChar = new Stack<Character>();     for (int i = 0; i < N; i++)    {         // Push character into the stack        stackOfChar.add(str.charAt(i));         // If stack size >= K.size()        if (stackOfChar.size() >= M)        {             // Create empty String to            // store characters of stack            String l = "";             // Traverse the String K in reverse            for (int j = M - 1; j >= 0; j--)            {                 // If any of the characters                // differ, it means that K                // is not present in the stack                if (K.charAt(j) != stackOfChar.peek())                {                     // Push the elements                    // back into the stack                    int f = 0;                    while (f != l.length())                    {                        stackOfChar.add(l.charAt(f));                        f++;                    }                     break;                }                 // Store the String                else                {                    l = stackOfChar.peek()                        + l;                     // Remove top element                    stackOfChar.pop();                }            }        }    }     // Size of stack gives the    // minimized length of str    return stackOfChar.size();} // Driver Codepublic static void main(String[] args){    String S1 = "fffoxoxoxfxo";    String S2 = "fox";     int N = S1.length();    int M = S2.length();     // Function Call    System.out.print(minLength(S1, N, S2, M));}} // This code is contributed by 29AjayKumar
# Python3 program for the above approach # Function to find the minimum length# to which string str can be reduced to# by removing all occurrences of string Kdef minLength(Str, N, K, M) :     # Initialize stack of characters    stackOfChar = []     for i in range(N) :         # Push character into the stack        stackOfChar.append(Str[i])         # If stack size >= K.size()        if (len(stackOfChar) >= M) :             # Create empty string to            # store characters of stack            l = ""             # Traverse the string K in reverse            for j in range(M - 1, -1, -1) :                 # If any of the characters                # differ, it means that K                # is not present in the stack                if (K[j] != stackOfChar[-1]) :                     # Push the elements                    # back into the stack                    f = 0                    while (f != len(l)) :                        stackOfChar.append(l[f])                        f += 1                     break                 # Store the string                else :                    l = stackOfChar[-1] + l                     # Remove top element                    stackOfChar.pop()     # Size of stack gives the    # minimized length of str    return len(stackOfChar) # Driver code S1 = "fffoxoxoxfxo"S2 = "fox" N = len(S1)M = len(S2) # Function Callprint(minLength(S1, N, S2, M)) # This code is contributed by divyeshrabadiya07
// C# program for the above approachusing System;using System.Collections.Generic;class GFG{ // Function to find the minimum length// to which String str can be reduced to// by removing all occurrences of String Kstatic int minLength(String str, int N,              String K, int M){     // Initialize stack of characters    Stack<char> stackOfChar = new Stack<char>();    for (int i = 0; i < N; i++)    {         // Push character into the stack        stackOfChar.Push(str[i]);         // If stack size >= K.Count        if (stackOfChar.Count >= M)        {             // Create empty String to            // store characters of stack            String l = "";             // Traverse the String K in reverse            for (int j = M - 1; j >= 0; j--)            {                 // If any of the characters                // differ, it means that K                // is not present in the stack                if (K[j] != stackOfChar.Peek())                {                     // Push the elements                    // back into the stack                    int f = 0;                    while (f != l.Length)                    {                        stackOfChar.Push(l[f]);                        f++;                    }                    break;                }                 // Store the String                else                {                    l = stackOfChar.Peek()                        + l;                     // Remove top element                    stackOfChar.Pop();                }            }        }    }     // Size of stack gives the    // minimized length of str    return stackOfChar.Count;} // Driver Codepublic static void Main(String[] args){    String S1 = "fffoxoxoxfxo";    String S2 = "fox";     int N = S1.Length;    int M = S2.Length;     // Function Call    Console.Write(minLength(S1, N, S2, M));}} // This code is contributed by 29AjayKumar
<script> // JavaScript program for the above approach // Function to find the minimum length// to which string str can be reduced to// by removing all occurrences of string Kfunction minLength(str, N, K, M){     // Initialize stack of characters    var stackOfChar = [];     for (var i = 0; i < N; i++) {         // Push character into the stack        stackOfChar.push(str[i]);         // If stack size >= K.size()        if (stackOfChar.length >= M) {             // Create empty string to            // store characters of stack            var l = "";             // Traverse the string K in reverse            for (var j = M - 1; j >= 0; j--) {                 // If any of the characters                // differ, it means that K                // is not present in the stack                if (K[j] != stackOfChar[stackOfChar.length-1]) {                     // Push the elements                    // back into the stack                    var f = 0;                    while (f != l.length) {                         stackOfChar.push(l[f]);                        f++;                    }                     break;                }                 // Store the string                else {                     l = stackOfChar[stackOfChar.length-1]                        + l;                     // Remove top element                    stackOfChar.pop();                }            }        }    }     // Size of stack gives the    // minimized length of str    return stackOfChar.length;} // Driver Codevar S1 = "fffoxoxoxfxo";var S2 = "fox";var N = S1.length;var M = S2.length; // Function Calldocument.write( minLength(S1, N, S2, M)); </script>
3
 
Time complexity: O(N*M), as we are using nested loops for traversing N*M times.Auxiliary Space: O(N), as we are using extra space for stack.
divyeshrabadiya07
29AjayKumar
rutvik_56
akshaysingh98088
rohitkumarsinghcna
cpp-stack-functions
substring
Stack
Strings
Strings
Stack
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
What is Data Structure: Types, Classifications and Applications
Design a stack with operations on middle element
How to efficiently implement k stacks in a single array?
Real-time application of Data Structures
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Different Methods to Reverse a String in C++