Minimum characters to be deleted from the end to make given two strings equal
Given two strings S1 and S2, the task is to find the minimum number of characters to be deleted from the end of the two strings to make them equal.
Two empty strings will be considered identical.
Examples:
Input: S1 = “abcd”, S2 = “absefr”
Output: 6
Explanation:
Characters {‘d’, ‘c’} are deleted from the end of S1 and characters {‘r’, ‘f’, ‘e’, ‘s’} are deleted from the end of S2 to make the strings equal.
Input: S1 = “geeks”, S2 = “geeksfor”
Output: 3
Explanation:
Characters {‘f’, ‘o’, ‘r’} are deleted from the end of S2.
Approach:
Iterate from the beginning of the two strings simultaneously and check if the characters are equal. The first index where the characters in the two strings differ is the index up to which all the characters from the end of both the strings need to be deleted.
Below is the implementation of above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int minDel(string s1, string s2)
{
int i = 0;
while (i < min(s1.length(),
s2.length())) {
if (s1[i] != s2[i]) {
break ;
}
i++;
}
int ans = (s1.length() - i)
+ (s2.length() - i);
return ans;
}
int main()
{
string s1 = "geeks" ,
s2 = "geeksfor" ;
cout << minDel(s1, s2)
<< endl;
}
|
Java
class GFG{
static int minDel(String s1, String s2)
{
int i = 0 ;
while (i < Math.min(s1.length(),
s2.length()))
{
if (s1.charAt(i) != s2.charAt(i))
{
break ;
}
i++;
}
int ans = ((s1.length() - i) +
(s2.length() - i));
return ans;
}
public static void main(String[] args)
{
String s1 = "geeks" ;
String s2 = "geeksfor" ;
System.out.println(minDel(s1, s2));
}
}
|
Python3
def minDel(s1, s2):
i = 0 ;
while (i < min ( len (s1), len (s2))):
if (s1[i] ! = s2[i]):
break ;
i + = 1 ;
ans = (( len (s1) - i) + ( len (s2) - i));
return ans;
if __name__ = = '__main__' :
s1 = "geeks" ;
s2 = "geeksfor" ;
print (minDel(s1, s2));
|
C#
using System;
class GFG{
static int minDel(String s1, String s2)
{
int i = 0;
while (i < Math.Min(s1.Length,
s2.Length))
{
if (s1[i] != s2[i])
{
break ;
}
i++;
}
int ans = ((s1.Length - i) +
(s2.Length - i));
return ans;
}
public static void Main(String[] args)
{
String s1 = "geeks" ;
String s2 = "geeksfor" ;
Console.WriteLine(minDel(s1, s2));
}
}
|
Javascript
<script>
function minDel( s1, s2)
{
var i = 0;
while (i < Math.min(s1.length,
s2.length)) {
if (s1[i] != s2[i]) {
break ;
}
i++;
}
var ans = (s1.length - i)
+ (s2.length - i);
return ans;
}
var s1 = "geeks" ,
s2 = "geeksfor" ;
document.write(minDel(s1, s2))
</script>
|
Time Complexity: O(min(len(s1), len(s2)))
Auxiliary Space: O(1)
Last Updated :
27 Jan, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...