Minimum characters to be deleted from the beginning of two strings to make them equal
Last Updated :
26 May, 2021
Given two strings S and T, the task is to find the minimum number of characters to be deleted from the beginning of these strings to make the two strings identical.
Two empty strings will always be an identical strings.
Examples:
Input: S = “geeksforgeeks” T = “peeks”
Output: 10
Explanation:
Substring “geeksforg” from S and “p” from T are deleted to make both the strings equals to “eeks”
Input: S = “geeksforgeeks” T = “code”
Output: 17
Explanation:
Both the strings had to be deleted completely.
Approach:
Traverse both the strings simultaneously from the end and compare the characters of the two strings. The first indices i (index of S1) and j (index of S2) where the characters of the two strings differ is the length up to which the characters of S1 and S2 need to be deleted. Hence, the final value of i + j is the required answer.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int minDel(string s1, string s2)
{
int i = s1.length();
int j = s2.length();
while (i > 0 && j > 0) {
if (s1[i - 1] != s2[j - 1]) {
break ;
}
i--;
j--;
}
return i + j;
}
int main()
{
string s1 = "geeksforgeeks" ,
s2 = "peeks" ;
cout << minDel(s1, s2) << endl;
}
|
Java
import java.util.*;
class GFG{
static int minDel(String s1, String s2)
{
int i = s1.length();
int j = s2.length();
while (i > 0 && j > 0 )
{
if (s1.charAt(i - 1 ) != s2.charAt(j - 1 ))
{
break ;
}
i--;
j--;
}
return i + j;
}
public static void main(String args[])
{
String s1 = "geeksforgeeks" ,
s2 = "peeks" ;
System.out.print(minDel(s1, s2));
}
}
|
Python3
def minDel(s1, s2):
i = len (s1)
j = len (s2)
while (i > 0 and j > 0 ):
if (s1[i - 1 ] ! = s2[j - 1 ]):
break
i - = 1
j - = 1
return i + j
if __name__ = = '__main__' :
s1 = "geeksforgeeks"
s2 = "peeks"
print (minDel(s1, s2))
|
C#
using System;
class GFG{
static int minDel( string s1, string s2)
{
int i = s1.Length;
int j = s2.Length;
while (i > 0 && j > 0)
{
if (s1[i - 1] != s2[j - 1])
{
break ;
}
i--;
j--;
}
return i + j;
}
public static void Main()
{
string s1 = "geeksforgeeks" ,
s2 = "peeks" ;
Console.Write(minDel(s1, s2));
}
}
|
Javascript
<script>
function minDel(s1, s2)
{
var i = s1.length;
var j = s2.length;
while (i > 0 && j > 0) {
if (s1[i - 1] != s2[j - 1]) {
break ;
}
i--;
j--;
}
return i + j;
}
var s1 = "geeksforgeeks" ,
s2 = "peeks" ;
document.write( minDel(s1, s2) );
</script>
|
Time Complexity: O( min(len(S1), len(S2)) )
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...