Skip to content
thecscience
THECSICENCE

Learn everything about computer science

  • Home
  • Human values
  • NCERT Solutions
  • HackerRank solutions
    • HackerRank Algorithms problems solutions
    • HackerRank C solutions
    • HackerRank C++ solutions
    • HackerRank Java problems solutions
    • HackerRank Python problems solutions
thecscience
THECSICENCE

Learn everything about computer science

HackerRank Append and Delete Problem Solution

Yashwant Parihar, April 16, 2023April 16, 2023

In this Post, we will solve HackerRank Append and Delete Problem Solution.

You have two strings of lowercase English letters. You can perform two types of operations on the first string:

  1. Append a lowercase English letter to the end of the string.
  2. Delete the last character of the string. Performing this operation on an empty string results in an empty string.

Given an integer, k, and two strings, & and t, determine whether or not you can convert s to t by performing exactly k of the above operations on 8. If it’s possible, print Yes. Otherwise, print No.
Example

s = [a, b, c]
t = [d, e, f]
k = 6
To convert s to t, we first delete all of the characters in 3 moves. Next we add each of the characters of t in order. On the 6th move, you will have the matching string. Return Yes.

If there were more moves available, they could have been eliminated by performing multiple deletions on an empty string. If there were fewer than 6 moves, we would not have succeeded in creating the new string.

Function Description

Complete the appendAndDelete function in the editor below. It should return a string, either Yes or No.

appendAndDelete has the following parameter(s):

  • string s: the initial string
  • string t: the desired string
  • int k: the exact number of operations that must be performed

Returns

  • string: either Yes or No

Input Format

The first line contains a string s, the initial string.
The second line contains a string t, the desired final string.
The third line contains an integer k, the number of operations.

Sample Input 0

hackerhappy
hackerrank
9

Sample Output 0

Yes

Explanation 0
We perform 5 delete operations to reduce string s to hacker. Next, we perform 4 append operations (i.e., r, a, n, and k), to get hackerrank. Because we were able to convert s to t by performing exactly k = 9 operations, we return Yes.

Sample Input 1

aba
aba
7

Sample Output 1

Yes

Explanation 1
We perform 4 delete operations to reduce string s to the empty string. Recall that though the string will be empty after 3 deletions, we can still perform a delete operation on an empty string to get the empty string. Next, we perform 3 append operations (i.e., a, b, and a). Because we were able to convert s tot by performing exactly k = 7 operations, we return Yes.

Sample Input 2

ashley
ash
2

Sample Output 2

No

Explanation 2

To convert ashley to ash a minimum of 3 steps are needed. Hence we print No as answer.

HackerRank Append and Delete Problem Solution
HackerRank Append and Delete Problem Solution

Append and Delete C Solution

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

int main(){
    char* s = (char *)malloc(512000 * sizeof(char));
    scanf("%s",s);
    char* t = (char *)malloc(512000 * sizeof(char));
    scanf("%s",t);
    int k; 
    scanf("%d",&k);
    int diffLoc = 0;
    for (diffLoc = 0; (*(s + diffLoc) ^ *(t + diffLoc)) == 0; diffLoc++);
    int len_s = strlen(s) - diffLoc;
	int len_t = strlen(t) - diffLoc;
    if (k < len_s + len_t)
		    printf("No");
	    else
        {
            if ( len_s ==  len_t )
            {
                printf("Yes");
            }
            else
            {
               if ( (k + len_s + len_t) % 2 )
               {
                   printf("No");                     
               }
               else
               {
		         printf("Yes");
               }
            }
        }
    return 0;
}

Append and Delete C++ Solution

#include <iostream>
#include <algorithm>

static bool solve(const std::string &s, const std::string &t, int k) {
    const auto n = s.length();
    const auto m = t.length();
    int length = 0;
    
    while (length < m && length < n && s[length] == t[length]) {
        length++;
    }
    
    auto deleteCount = n - length;
    auto appendCount = m - length;
    
    if (deleteCount + appendCount > k) {
        return false;
    }
    else if (n + m <= k) {
        return true;
    }
    
    return (k - (deleteCount + appendCount)) % 2 == 0;
}

int main() {
    std::string s;
    std::string t;
    int k{};
    std::cin >> s >> t >> k;
    std::cout << (::solve(s, t, k) ? "Yes\n" : "No\n");
    return 0;
}

Append and Delete C Sharp Solution

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution {

    static void Main(String[] args) {
        string s = Console.ReadLine();
        string t = Console.ReadLine();
        int k = Convert.ToInt32(Console.ReadLine());
        
        var newS = new HashSet<string>() { s };
        var operations = 0;
        
        while (operations < k)
        {
            operations++;
            newS = newS.Aggregate(new HashSet<string>(), (acc, x) =>
            {
                acc.Add(x += (x.Length >= t.Length ? "x" : t.Substring(x.Length,1)));
                if (x.Length > 1)
                {
                    acc.Add(x.Substring(0, x.Length-2));
                }
                else
                {
                    acc.Add("");
                }

                return acc;
            });
        }

        if (newS.Any(x => x == t) && operations == k)
        {
            Console.WriteLine("Yes");
        }
        else
        {
            Console.WriteLine("No");
        }
    }
}

Append and Delete Java Solution

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;

class Result {

    /*
     * Complete the 'appendAndDelete' function below.
     *
     * The function is expected to return a STRING.
     * The function accepts following parameters:
     *  1. STRING s
     *  2. STRING t
     *  3. INTEGER k
     */

    public static String appendAndDelete(String s, String t, int k) {
        // Write your code here
        int index = 0;

        while(index < s.length() && index < t.length()) {
            if(s.charAt(index) != t.charAt(index)) break;
            index++; // 1
        }

        int delete = s.length() - index;
        int append = t.length() - index; // 7 - 5 = 2

        // aba
        if(delete == 0 && append == 0) {
            return "Yes";
        }
        else if(k - append > t.length() || delete + append == k ) {
            return "Yes";
        }
        else if(delete == 0) {
            String answer = "";

            if(k <= 2 || k % append != 0) {
                return "No";
            }
            else if (s.length() + k > t.length()) {
                return "Yes";
            }


            return answer;

        }
        else {
            return "No";
        }
    }

}

public class Solution {
    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

        String s = bufferedReader.readLine();

        String t = bufferedReader.readLine();

        int k = Integer.parseInt(bufferedReader.readLine().trim());

        String result = Result.appendAndDelete(s, t, k);

        bufferedWriter.write(result);
        bufferedWriter.newLine();

        bufferedReader.close();
        bufferedWriter.close();
    }
}

Append and Delete JavaScript Solution

process.stdin.resume();
process.stdin.setEncoding('ascii');

var input_stdin = "";
var input_stdin_array = "";
var input_currentline = 0;

process.stdin.on('data', function (data) {
    input_stdin += data;
});

process.stdin.on('end', function () {
    input_stdin_array = input_stdin.split("\n");
    main();    
});

function readLine() {
    return input_stdin_array[input_currentline++];
}

/////////////// ignore above this line ////////////////////

function main() {
    var s = readLine();
    var t = readLine();
    var k = parseInt(readLine());
    if( k >= t.length + s.length){
        console.log('Yes');
        return;
    }
    var sLetters = s.split('');
    var tLetters = t.split('');
    var equals = 0;
    for(let  i = 0, len = sLetters.length; i < len; i++){
        if(sLetters[i] == tLetters[i]){
            equals++;
        }else{
            break;
        }
    }    
    var removed = sLetters.length - equals;
    var added = tLetters.length - equals;
    
    if(removed + added > k){
        console.log('No');
        return;
    }
    
    var kIsOdd = k % 2 != 0;
    var operationsIsOdd = (removed + added) % 2 != 0;
    
    if(kIsOdd == operationsIsOdd){
        console.log('Yes');
    }else{
        console.log('No');
    }

}

Append and Delete Python Solution

#!/bin/python3

import sys


s = input().strip()
t = input().strip()
k = int(input().strip())

isPossible = False
if k >= (len(s)+len(t)):
    isPossible=True
elif s == t:
    if (k%2 == 0):
        isPossible=True
else:
    k-=abs(len(s) - len(t))
    if len(s) <= len(t):
        l = len(s)
    else:
        l = len(t)
    isEqual = True
    for i in range(l):
        if s[i] != t[i]:
            isEqual = False
            k-=2*(l-i)
            if k == 0:
                isPossible = True
            if (k > 0) and (k%2 == 0):
                isPossible = True
            break
    if isEqual:
        if k == 0:
                isPossible = True
        if (k > 0) and (k%2 == 0):
                isPossible = True
if isPossible:
    print("Yes")
else:
    print("No")


    

other solutions

  • HackerRank Sherlock and Squares Solution
  • HackerRank Library Fine Problem Solution
c C# C++ HackerRank Solutions java javascript python CcppCSharpHackerrank Solutionsjavajavascriptpython

Post navigation

Previous post
Next post

Leave a Reply

You must be logged in to post a comment.

  • HackerRank Dynamic Array Problem Solution
  • HackerRank 2D Array – DS Problem Solution
  • Hackerrank Array – DS Problem Solution
  • Von Neumann and Harvard Machine Architecture
  • Development of Computers

Blogs that I follow

  • Programming
  • Data Structures
©2025 THECSICENCE | WordPress Theme by SuperbThemes