Converting one string to other using append and delete last operations
Last Updated :
02 Aug, 2022
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.
- Append a lowercase English alphabetic letter to the end of the str1.
- 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.
Implementation:
C++
// 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 program
int 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
// java Program to convert str1 to
// str2 in exactly k operations
import 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.
Python3
# 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 Code
if __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#
// C# Program to convert str1 to
// str2 in exactly k operations
using 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
// 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
?>
JavaScript
<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 program
var 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>
Time Complexity: O(n)
Auxiliary Space: O(1)
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
SQL Commands | DDL, DQL, DML, DCL and TCL Commands SQL commands are crucial for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will e
7 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
4 min read