Length of longest substring to be deleted to make a string equal to another string
Last Updated :
30 May, 2022
Given two strings str1 and str2, where str2 is a subsequence of str1, the task is to find the length of the longest substring of str1 which when removed, makes the strings str2 and str1 equal.
Examples:
Input: str1 = “programmingbloods”, str2 = “ibloods”
Output: 8
Explanation:
Substrings to be removed from str1 are [“program”, “ng”]. Therefore, the length of the longest deleted substring is 8.
Input: str1=“GeeksforGeeks”, str2=“forks”
Output: 5
Naive Approach: The simplest approach is to generate all possible substrings of str1 and for each substring, remove it from str1 and check if the resulting string becomes equal to str2 or not. Print the length of longest such substrings.
Time Complexity: O(2N)
Auxiliary Space: O(N)
Efficient Approach: To optimize the above approach, the idea is to find the occurrence of str2 in str1. Traverse both strings from left to right and check if both characters are equal or not. If found to be true, proceed to the right in both strings. Otherwise, proceed to the right only in str2. Similarly, to find the last occurrence of str2 in str1, traverse both strings from right to left and proceed similarly. Follow the steps below to solve the problem:
- Initialize a variable, res=0 to store the length of the longest deleted substring.
- Create an array, pos[] to store the position of the first occurrence of str2 in str1.
- Traverse both strings from left to right and store the position of the first occurrence of str2 by deleting some characters of str1.
- Initialize a variable, lastPos = length(str1)-1 to store the position of the current character in the last occurrence of str2 by deleting some characters of str1.
- Traverse both strings from right to left and check if both characters match then find the position of the current character of str2 in pos[] else continue.
- If res > (lastPos - pos[i-1]-1) then update the res = lastPos - pos[i-1]-1.
- Finally, return the res.
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 print the length
// of longest substring to be deleted
int longDelSub(string str1, string str2)
{
// Stores the length of string
int N = str1.size();
int M = str2.size();
// Store the position of
// previous matched
// character of str1
int prev_pos = 0;
// Store the position of first
// occurrence of str2 in str1
int pos[M];
// Find the position of the
// first occurrence of str2
for (int i = 0; i < M; i++) {
// Store the index of str1
int index = prev_pos;
// If both characters not matched
while (index < N
&& str1[index] != str2[i]) {
index++;
}
pos[i] = index;
prev_pos = index + 1;
}
// Store the length of the
// longest deleted substring
int res = N - prev_pos;
prev_pos = N - 1;
// Store the position of last
// occurrence of str2 in str1
for (int i = M - 1; i >= 0; i--) {
int index = prev_pos;
// If both characters not matched
while (index >= 0
&& str1[index] != str2[i]) {
index--;
}
// Update res
if (i != 0) {
res = max(
res,
index - pos[i - 1] - 1);
}
prev_pos = index - 1;
}
// Update res.
res = max(res, prev_pos + 1);
return res;
}
// Driver Code
int main()
{
// Given string
string str1 = "GeeksforGeeks";
string str2 = "forks";
// Function Call
cout << longDelSub(str1, str2);
return 0;
}
Java
// Java program to implement
// the above approach
import java.io.*;
class GFG{
// Function to print the length
// of longest substring to be deleted
static int longDelSub(String str1, String str2)
{
// Stores the length of string
int N = str1.length();
int M = str2.length();
// Store the position of
// previous matched
// character of str1
int prev_pos = 0;
// Store the position of first
// occurrence of str2 in str1
int pos[] = new int[M];
// Find the position of the
// first occurrence of str2
for(int i = 0; i < M; i++)
{
// Store the index of str1
int index = prev_pos;
// If both characters not matched
while (index < N &&
str1.charAt(index) !=
str2.charAt(i))
{
index++;
}
pos[i] = index;
prev_pos = index + 1;
}
// Store the length of the
// longest deleted substring
int res = N - prev_pos;
prev_pos = N - 1;
// Store the position of last
// occurrence of str2 in str1
for(int i = M - 1; i >= 0; i--)
{
int index = prev_pos;
// If both characters not matched
while (index >= 0 &&
str1.charAt(index) !=
str2.charAt(i))
{
index--;
}
// Update res
if (i != 0)
{
res = Math.max(res,
index -
pos[i - 1] - 1);
}
prev_pos = index - 1;
}
// Update res.
res = Math.max(res, prev_pos + 1);
return res;
}
// Driver Code
public static void main (String[] args)
{
// Given string
String str1 = "GeeksforGeeks";
String str2 = "forks";
// Function call
System.out.print(longDelSub(str1, str2));
}
}
// This code is contributed by code_hunt
Python3
# Python3 program to implement
# the above approach
# Function to print the length
# of longest substring to be deleted
def longDelSub(str1, str2):
# Stores the length of string
N = len(str1)
M = len(str2)
# Store the position of
# previous matched
# character of str1
prev_pos = 0
# Store the position of first
# occurrence of str2 in str1
pos = [0] * M
# Find the position of the
# first occurrence of str2
for i in range(M):
# Store the index of str1
index = prev_pos
# If both characters not matched
while (index < N and
str1[index] != str2[i]):
index += 1
pos[i] = index
prev_pos = index + 1
# Store the length of the
# longest deleted substring
res = N - prev_pos
prev_pos = N - 1
# Store the position of last
# occurrence of str2 in str1
for i in range(M - 1, -1, -1):
index = prev_pos
# If both characters not matched
while (index >= 0 and
str1[index] != str2[i]):
index -= 1
# Update res
if (i != 0) :
res = max(res,
index -
pos[i - 1] - 1)
prev_pos = index - 1
# Update res.
res = max(res, prev_pos + 1)
return res
# Driver Code
# Given string
str1 = "GeeksforGeeks"
str2 = "forks"
# Function call
print(longDelSub(str1, str2))
# This code is contributed by code_hunt
C#
// C# program to implement
// the above approach
using System;
class GFG{
// Function to print the length
// of longest substring to be deleted
static int longDelSub(string str1,
string str2)
{
// Stores the length of string
int N = str1.Length;
int M = str2.Length;
// Store the position of
// previous matched
// character of str1
int prev_pos = 0;
// Store the position of first
// occurrence of str2 in str1
int[] pos = new int[M];
// Find the position of the
// first occurrence of str2
for(int i = 0; i < M; i++)
{
// Store the index of str1
int index = prev_pos;
// If both characters not matched
while (index < N &&
str1[index] != str2[i])
{
index++;
}
pos[i] = index;
prev_pos = index + 1;
}
// Store the length of the
// longest deleted substring
int res = N - prev_pos;
prev_pos = N - 1;
// Store the position of last
// occurrence of str2 in str1
for(int i = M - 1; i >= 0; i--)
{
int index = prev_pos;
// If both characters not matched
while (index >= 0 &&
str1[index] != str2[i])
{
index--;
}
// Update res
if (i != 0)
{
res = Math.Max(res,
index -
pos[i - 1] - 1);
}
prev_pos = index - 1;
}
// Update res.
res = Math.Max(res, prev_pos + 1);
return res;
}
// Driver code
public static void Main()
{
// Given string
string str1 = "GeeksforGeeks";
string str2 = "forks";
// Function call
Console.Write(longDelSub(str1, str2));
}
}
// This code is contributed by code_hunt
JavaScript
<script>
// JavaScript Program to implement
// the above approach
// Function to print the length
// of longest substring to be deleted
function longDelSub( str1, str2)
{
// Stores the length of string
var N = str1.length;
var M = str2.length;
// Store the position of
// previous matched
// character of str1
var prev_pos = 0;
// Store the position of first
// occurrence of str2 in str1
var pos = new Array(M);
// Find the position of the
// first occurrence of str2
for (let i = 0; i < M; i++) {
// Store the index of str1
var index = prev_pos;
// If both characters not matched
while (index < N
&& str1[index] != str2[i]) {
index++;
}
pos[i] = index;
prev_pos = index + 1;
}
// Store the length of the
// longest deleted substring
var res = N - prev_pos;
prev_pos = N - 1;
// Store the position of last
// occurrence of str2 in str1
for (let i = M - 1; i >= 0; i--) {
var index = prev_pos;
// If both characters not matched
while (index >= 0
&& str1[index] != str2[i]) {
index--;
}
// Update res
if (i != 0) {
res = Math.max(
res,
index - pos[i - 1] - 1);
}
prev_pos = index - 1;
}
// Update res.
res = Math.max(res, prev_pos + 1);
return res;
}
// Driver Code
// Given string
var str1 = "GeeksforGeeks";
var str2 = "forks";
// Function Call
console.log(longDelSub(str1, str2));
// This code is contributed by ukasp.
</script>
Time Complexity: O(N + M)
Auxiliary Space: O(M)
Similar Reads
Longest Substring of A that can be changed to Substring of B in at most T cost Given two strings A and B of the same length and two positive integers K and T. The task is to find the longest substring of A that can be converted to the same substring at the same position in B in less than or equal to T cost. Converting any character of A to any other character costs K units. No
13 min read
Find length of longest subsequence of one string which is substring of another string Given two strings X and Y. The task is to find the length of the longest subsequence of string X which is a substring in sequence Y.Examples: Input : X = "ABCD", Y = "BACDBDCD"Output : 3Explanation: "ACD" is longest subsequence of X which is substring of Y.Input : X = "A", Y = "A"Output : 1Perquisit
15+ min read
Javascript Program To Find Length Of The Longest Substring Without Repeating Characters Given a string str, find the length of the longest substring without repeating characters. For âABDEFGABEFâ, the longest substring are âBDEFGAâ and "DEFGAB", with length 6.For âBBBBâ the longest substring is âBâ, with length 1.For "GEEKSFORGEEKS", there are two longest substrings shown in the below
5 min read
Length of the longest substring with equal 1s and 0s Given a binary string. We need to find the length of the longest balanced substring. A substring is balanced if it contains an equal number of 0 and 1. Examples: Input : input = 110101010Output : Length of longest balanced sub string = 8 Input : input = 0000Output : Length of longest balanced sub st
10 min read
Count characters of a string which when removed individually makes the string equal to another string Given 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",
8 min read