Simple Text Editor HackerRank Solution

In this Simple Text Editor HackerRank solution, Implement a simple text editor. The editor initially contains an empty string, . Perform  operations of the following  types:

  1. append – Append string  to the end of .
  2. delete – Delete the last  characters of .
  3. print – Print the  character of .
  4. undo – Undo the last (not previously undone) operation of type  or , reverting  to the state it was in prior to that operation.

Example

operation
index   S       ops[index]  explanation
-----   ------  ----------  -----------
0       abcde   1 fg        append fg
1       abcdefg 3 6         print the 6th letter - f
2       abcdefg 2 5         delete the last 5 letters
3       ab      4           undo the last operation, index 2
4       abcdefg 3 7         print the 7th characgter - g
5       abcdefg 4           undo the last operation, index 0
6       abcde   3 4         print the 4th character - d

The results should be printed as:

f
g
d

Input Format

The first line contains an integer, , denoting the number of operations.
Each line  of the  subsequent lines (where ) defines an operation to be performed. Each operation starts with a single integer,  (where ), denoting a type of operation as defined in the Problem Statement above. If the operation requires an argument,  is followed by its space-separated argument. For example, if  and , line  will be 1 abcd.

Constraints

  • The sum of the lengths of all  in the input .
  • The sum of  over all delete operations .
  • All input characters are lowercase English letters.
  • It is guaranteed that the sequence of operations given as input is possible to perform.

Output Format

Each operation of type  must print the  character on a new line.

Sample Input

STDIN   Function
-----   --------
8       Q = 8
1 abc   ops[0] = '1 abc'
3 3     ops[1] = '3 3'
2 3     ...
1 xy
3 2
4 
4 
3 1

Sample Output

c
y
a

Explanation

Initially,  is empty. The following sequence of  operations are described below:

  1. . We append  to , so .
  2. Print the  character on a new line. Currently, the  character is c.
  3. Delete the last  characters in  (), so .
  4. Append  to , so .
  5. Print the  character on a new line. Currently, the  character is y.
  6. Undo the last update to , making  empty again (i.e., ).
  7. Undo the next to last update to  (the deletion of the last  characters), making .
  8. Print the  character on a new line. Currently, the  character is a.

Simple Text Editor HackerRank solution

I will Provide solution in Multiple programming languages for you. If you are not able to find the code in required language then please share in comments so that our team can help you.

Problem Solution in Java

public class Operation
{
        public int type;
        public string argument;


        public Operation(int t, string arg)
        {
            type = t;
            argument = arg;
        }
    }
   
    static void Main(String[] args) {
       
        int t = Convert.ToInt32(Console.ReadLine().Trim());        
        List<Operation> ops = new List<Operation>();
        for (int tItr = 0; tItr < t; tItr++)
        {          
            string s = Console.ReadLine().TrimEnd();
            int type =  s[0] - '0';
            string arg = string.Empty;
            if(type != 4)
            {
                arg = s.Substring(2, s.Length - 2);
            }
            Operation oper = new Operation(type, arg);            
            ops.Add(oper);
        }
       
        StringBuilder sb = new StringBuilder();                
        Stack<Operation> operations = new Stack<Operation>();
       
        for(int i = 0; i < ops.Count; i++)
        {                        
            if(ops[i].type == 1)
            {            
                sb.Append(ops[i].argument);    
                           
                operations.Push(new Operation(5, ops[i].argument));
            }
            else if(ops[i].type == 2)
            {                
                int k = Convert.ToInt32(ops[i].argument);
                String last = sb.ToString().Substring(sb.Length - k);
                sb.Remove(sb.Length - k, k);
               
                operations.Push(new Operation(6, last));
            }
            else if(ops[i].type == 3)
            {                
                int k = Convert.ToInt32(ops[i].argument);
                Console.WriteLine(sb.ToString()[k-1]);
            }
            else if(ops[i].type == 4)
            {
                if(operations.Count > 0)        
                {
                    Operation operation = operations.Pop();
                    if(operation.type == 6)
                    {
                        sb.Append(operation.argument);
           
                    }
                    else if(operation.type == 5)
                    {
                            int k = operation.argument.Length;                
                            sb.Remove(sb.Length - k, k);
                    }
                }
            }
        }
    }
}

Problem Solution in Python

class Editor:
    def __init__(self):
        self.data = []
        self.histories = []
   
    def backup(self):
        self.histories.append(self.data.copy())
       
    def insert(self, content):
        self.backup()
        self.data += list(content)


    def delete(self, count):
        self.backup()
        endIdx = len(self.data) - int(count)
        self.data = self.data[:endIdx]
   
    def printIdx(self, idx):
        print(self.data[int(idx) - 1])
       
    def undo(self, arg = None):
        self.data = self.histories.pop()
        if not self.data:
            self.data = []
           
    def commandToFn(self, command):
        return {
            "1": "insert",
            "2": "delete",
            "3": "printIdx",
            "4": "undo",
        }[command]
           
    def execute(self, instruction):
       
        command = instruction[0]
        content = instruction[1] if len(instruction) == 2 else None
       
        return getattr(self, self.commandToFn(command))(content)
   
       
       
if __name__ == '__main__':
    editor = Editor()


    for op in range(int(input())):
        editor.execute(input().split())

Problem Solution in JavaScript

function processData(input) {
    input = input.split('\n');
    let S = "";
    let lastStateOfS = [S];
   
    for(let i = 1; i < input.length; i++){
            let query = input[i].split(' ');
            if(query[0] === '1'){
                S += query[1];
                lastStateOfS.push(S)
            } else if (query[0] === '2'){
                let charsToDelete = +query[1];
                S = S.substring(0, S.length - charsToDelete);
                lastStateOfS.push(S)
            } else if (query[0] === '3'){
                console.log(S[+query[1] - 1]);
            } else{
                lastStateOfS.pop();
                S = lastStateOfS[lastStateOfS.length - 1];
            }
    }


    return S;
}
Solve original Problem on HackerRank here. Checkout more HackerRank Problems

Leave a Comment