Converting one string to other using append and delete last operations - GeeksforGeeks

30 Apr, 2021
Given an integer k and two strings str1 and str2 determine whether or not we can convert str1 to str2 by performing exactly k of the below operations on str1. a) Append a lowercase English alphabetic letter to the end of the str1. b) Delete the last character in str1 (Performing this operation on an empty string results in an empty string)Examples:  
Input : k = 7, str1 = aba, str2 = aba
Output : Yes
(4 operations to convert str1 to an 
empty string(to make string empty we 
have to perform one more delete 
operation) and 3 append operations)

Input : k = 5, str1 = pqruvs, str2 = pqrxy 
Output : Yes
(3 delete operations and 2 append operations)
 
First of all we determine the common prefix of both strings and then depending upon the value of common prefix, str1.length, str2.length and k we can conclude result. Below are the cases. CASE A: Cases where we can change str1 to str2 :  
If str1.length + str2.length <= k then we can delete str1 completely and re-construct str2 easily.
If [k-(str1.length-prefix.length + str2.length-prefix.length)] is even then we can easily construct str2 from str1. This is because str1.length-prefix.length is number of letter to be deleted and str2.length-prefix.length is number of letter to be added in str1 after deletion of uncommon letter. After this if the operations left is even then we can add and remove any random letter which cost even number of operations.
CASE B: In rest of all cases we cannot construct str2 from str1.  
C++
Java
Python3
C#
PHP
Javascript
// CPP Program to convert str1 to str2 in// exactly k operations#include <bits/stdc++.h>using namespace std; // Returns true if it is possible to convert// str1 to str2 using k operations.bool isConvertible(string str1, string str2,                                      int k){    // Case A (i)    if ((str1.length() + str2.length()) < k)        return true;     // finding common length of both string    int commonLength = 0;    for (int i = 0; i < min(str1.length(),                           str2.length()); i++) {        if (str1[i] == str2[i])            commonLength++;        else            break;    }     // Case A (ii)-    if ((k - str1.length() - str2.length() +                     2 * commonLength) % 2 == 0)        return true;     // Case B-    return false;} // driver programint main(){    string str1 = "geek", str2 = "geek";    int k = 7;    if (isConvertible(str1, str2, k))       cout << "Yes";    else       cout << "No";     str1 = "geeks",  str2 = "geek";    k = 5;       cout << endl;    if (isConvertible(str1, str2, k))       cout << "Yes";    else       cout << "No";    return 0;}
// java Program to convert str1 to// str2 in exactly k operationsimport java.io.*; class GFG {         // Returns true if it is possible to convert    // str1 to str2 using k operations.    static boolean isConvertible(String str1, String str2,                                                     int k)    {        // Case A (i)        if ((str1.length() + str2.length()) < k)            return true;             // finding common length of both string        int commonLength = 0;        for (int i = 0; i < Math.min(str1.length(),                                str2.length()); i++)        {            if (str1 == str2)                commonLength++;            else                break;        }             // Case A (ii)-        if ((k - str1.length() - str2.length() +                     2 * commonLength) % 2 == 0)            return true;             // Case B        return false;    }                   // Driver program    public static void main (String[] args)    {        String str1 = "geek";        String str2 = "geek";        int k = 7;        if (isConvertible(str1, str2, k))        System.out.println( "Yes");        else        System.out.println ( "No");             str1 = "geeks";        str2 = "geek";        k = 5;                 if (isConvertible(str1, str2, k))        System.out.println( "Yes");        else        System.out.println ( "No");                 }} // This code is contributed by vt_m.
# Python 3 Program to convert str1 to# str2 in exactly k operations # Returns true if it is possible to convert# str1 to str2 using k operations.def isConvertible(str1, str2, k):         # Case A (i)    if ((len(str1) + len(str2)) < k):        return True     # finding common length of both string    commonLength = 0    for i in range(0, min(len(str1),                          len(str2)), 1):        if (str1[i] == str2[i]):            commonLength += 1        else:            break     # Case A (ii)-    if ((k - len(str1) - len(str2) + 2 *                commonLength) % 2 == 0):        return True     # Case B-    return False # Driver Codeif __name__ == '__main__':    str1 = "geek"    str2 = "geek"    k = 7    if (isConvertible(str1, str2, k)):        print("Yes")    else:        print("No")     str1 = "geeks"    str2 = "geek"    k = 5    if (isConvertible(str1, str2, k)):        print("Yes")    else:        print("No") # This code is contributed by# Sanjit_Prasad
// C# Program to convert str1 to// str2 in exactly k operationsusing System; class GFG {         // Returns true if it is possible to convert    // str1 to str2 using k operations.    static bool isConvertible(string str1, string str2,                                                    int k)    {        // Case A (i)        if ((str1.Length + str2.Length) < k)            return true;             // finding common length of both string        int commonLength = 0;        for (int i = 0; i < Math.Min(str1.Length,                                str2.Length); i++)        {            if (str1 == str2)                commonLength++;            else                break;        }             // Case A (ii)-        if ((k - str1.Length - str2.Length +                    2 * commonLength) % 2 == 0)            return true;             // Case B        return false;    }                   // Driver program    public static void Main ()    {        string str1 = "geek";        string str2 = "geek";        int k = 7;        if (isConvertible(str1, str2, k))        Console.WriteLine( "Yes");        else        Console.WriteLine ( "No");             str1 = "geeks";        str2 = "geek";        k = 5;                 if (isConvertible(str1, str2, k))        Console.WriteLine( "Yes");        else        Console.WriteLine ( "No");                 }} // This code is contributed by vt_m.
<?php// PHP Program to convert str1 to str2 in// exactly k operations // Returns true if it is possible to convert// str1 to str2 using k operations.function isConvertible($str1, $str2, $k)                                                 {    // Case A (i)    if ((strlen($str1) + strlen($str2)) < $k)        return true;     // finding common length of both string    $commonLength = 0;    for ($i = 0; $i < min(strlen($str1),                          strlen($str2)); $i++)    {        if ($str1 == $str2)            $commonLength += 1;        else            break;    }     // Case A (ii)-    if (($k - strlen($str1) - strlen($str2) +                 2 * $commonLength) % 2 == 0)        return true;     // Case B    return false;}  // Driver Code$str1 = "geek";$str2 = "geek";$k = 7; if (isConvertible($str1, $str2, $k))    echo "Yes" . "\n";else    echo "No" . "\n"; $str1 = "geeks";$str2 = "geek";$k = 5; if (isConvertible($str1, $str2, $k))    echo "Yes" . "\n";else    echo "No" . "\n";     // This code is contributed by// Mukul Singh?>
<script> // Javascript Program to convert str1 to str2 in// exactly k operations // Returns true if it is possible to convert// str1 to str2 using k operations.function isConvertible(str1, str2, k){    // Case A (i)    if ((str1.length + str2.length) < k)        return true;     // finding common length of both string    var commonLength = 0;    for (var i = 0; i < Math.min(str1.length,                           str2.length); i++) {        if (str1[i] == str2[i])            commonLength++;        else            break;    }     // Case A (ii)-    if ((k - str1.length - str2.length +                     2 * commonLength) % 2 == 0)        return true;     // Case B-    return false;} // driver programvar str1 = "geek", str2 = "geek";var k = 7;if (isConvertible(str1, str2, k))   document.write( "Yes");else   document.write( "No");str1 = "geeks",  str2 = "geek";k = 5;   document.write("<br>");if (isConvertible(str1, str2, k))   document.write( "Yes");else   document.write("No"); // This code is contributed by noob2000.</script>
No
Yes
 
YouTubeGeeksforGeeks500K subscribersConverting one string to other using append and delete last operations | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:45•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=lmAkZ1bKcc8" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Sanjit_Prasad
Code_Mech
noob2000
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python program to check if a string is palindrome or not
Check for Balanced Brackets in an expression (well-formedness) using Stack
KMP Algorithm for Pattern Searching
Convert string to char array in C++
Different methods to reverse a string in C/C++
Array of Strings in C++ (5 Different Ways to Create)
Longest Palindromic Substring | Set 1
Reverse words in a given string
Caesar Cipher in Cryptography
Length of the longest substring without repeating characters