Simple Text Editor


Problem Statement :


In this challenge, you must implement a simple text editor. Initially, your editor contains an empty string, S. You must perform Q operations of the following 4  types:

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


Input Format


The first line contains an integer, Q, denoting the number of operations.
Each line i of the Q subsequent lines (where 0 < = i  < Q ) defines an operation to be performed. Each operation starts with a single integer, t  , 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 t = 1  and , W = "abcd" line i will be 1 abcd.


Output Format

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


Solution :



title-img


                            Solution in C :

In C++ :



#include <iostream>
#include <string>
#include <stack>

int main() {

    std::string text, arg;
    int cmd;
    std::stack<std::string> history;
    
    std::cin >> cmd;
    while (std::cin >> cmd) {
        switch (cmd) {
            case 1: // Append
                std::cin >> arg;
                history.push(text);
                text.append(arg);
                break;
            case 2: // Erase
                std::cin >> cmd;
                history.push(text);
                text.erase(text.length() - cmd);
                break;
            case 3: // Get
                std::cin >> cmd;
                std::cout << text[cmd - 1] << '\n';
                break;
            case 4: // Undo
                text = std::move(history.top());
                history.pop();
                break;
        }        
    }
    return 0;
}








In Java :





import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
      
        Scanner sc = new Scanner(System.in);
        String str = "";
        int top = 0;
        int q = Integer.parseInt(sc.nextLine());
        MyStack stack = new MyStack(q);
        for(int i = 0; i < q; ++i){
            String st[] = sc.nextLine().split(" ");
            int query = Integer.parseInt(st[0]);
            if(query == 1){
                Node newNode = new Node(query,str.length());
                stack.top++;
                stack.list[stack.top] = newNode;
                str += st[1];
            } else if(query == 2){
                int k = Integer.parseInt(st[1]);
                Node newNode = new Node(query,str.substring(str.length()-k));
                stack.top++;
                stack.list[stack.top] = newNode;
                str = str.substring(0,str.length()-k);
            } else if(query == 3){
                int index = Integer.parseInt(st[1]);
                System.out.println(str.charAt(index-1));
            } else if(query == 4){
                Node newNode = stack.list[stack.top];
                stack.top--;
                if(newNode.qtype == 1){
                    str = str.substring(0,newNode.idx);
                } else if(newNode.qtype == 2){
                    str += newNode.w;
                }
            }
        }
    }
}
class MyStack{
    Node list[];
    int top;
    MyStack(int size){
        this.list = new Node[size];
        this.top = -1;
    }
}
class Node{
    int qtype;
    int idx;
    String w;
    Node(int x, String y){
        this.qtype = x;
        this.w = y;
    }
    Node(int x, int index){
        this.qtype = x;
        this.idx = index;
    }
}








In C :





#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

#define STACK_SIZE 1000000
#define MAX_W_SIZE ((1000000) + (1))

char* stack[STACK_SIZE];
int sp = -1;

int is_empty() {
    return (sp < 0);
}

int is_full() {
    return (sp > STACK_SIZE);
}

void push(char* cp) {
    if (!is_full()) {
        stack[++sp] = cp;
    }
}

char* peek() {
    char* top = '\0';
    if (!is_empty()) {
        top = stack[sp];
    }
    return top;
}

char* pop() {
    char* top = peek();
    if (top) {
        stack[sp--] = '\0';
    }
    return top;
}

int get_len(char* warg) {
    int len = 0;
    while(*warg) {
        len++; warg++;
    }
    return len;
}
void do_append(char* warg) {
    int len = get_len(warg);
    
    char* current = peek();
    if (!current) {
        current = (char*) malloc(sizeof(char) * (len + 1));
        for (int i = 0; i < len; i++) {
        current[i] = warg[i];
        }
        current[len] = '\0';
        push(current);
    } else {
		int j = 0;
        int current_len = get_len(current);
        char* current_new = (char*)malloc(sizeof(char) * (current_len + len + 1));
        
        if (current_new) {
            for (int i = 0; i < current_len; i++) {
                current_new[i] = current[i];
            }
			for (int i = current_len; i < current_len + len; i++) {
				current_new[i] = warg[j++];
			}
            current_new[current_len + len] = '\0';
            push(current_new);
        }
    }   
}

void do_erase(int iarg) {
    char* current = peek();
    
    if (current) {
        int current_len = get_len(current);
        if (current_len >= iarg) {
            char* current_new = (char*)malloc(sizeof(char) * (current_len - iarg + 1));
            if (current_new) {
                for (int i = 0; i < current_len - iarg; i++) {
                    current_new[i] = current[i];
                }
                current_new[current_len - iarg] = '\0';
                push(current_new);
            }
        }
    }
}

void do_get(int iarg, char* ch) {
    char* current = peek();
    
    if (current) {
        int current_len = get_len(current);
        if (current_len >= iarg) {
            *ch = current[iarg - 1];   
        }
    }
}

void do_undo() {
    pop();
}

int main() {

    int Q;
    int op;
    int iarg;
    char warg[MAX_W_SIZE];
    scanf("%d", &Q);
    
    for (int i = 0; i < Q; i++) {
        scanf("%d", &op);
        
        if (op == 1) {
            scanf("%s", warg);
            do_append(warg);
        } else if (op == 2) {
            scanf("%d", &iarg);
            do_erase(iarg);
        } else if (op == 3) {
            scanf("%d", &iarg);
            char ch = '\0';
            do_get(iarg, &ch);
            fflush(stdout);
            printf("%c\n", ch);
        } else if (op == 4) {
            do_undo();
        }
    }
    return 0;
}








In Python3 :






q = int(input())
stack = ['']
for _ in range(q):
    o_type, *par = input().split()
    o_type = int(o_type)
    if o_type in (1, 2, 3):
        par = par[0]
        if o_type in (2, 3):
            par = int(par)

    if o_type == 1:
        stack.append(stack[-1] + par)
    elif o_type == 2:
        stack.append(stack[-1][:-par])
    elif o_type == 3:
        print(stack[-1][par - 1])
    elif o_type == 4:
        stack.pop()
                        




View More Similar Problems

Print in Reverse

Given a pointer to the head of a singly-linked list, print each data value from the reversed list. If the given list is empty, do not print anything. Example head* refers to the linked list with data values 1->2->3->Null Print the following: 3 2 1 Function Description: Complete the reversePrint function in the editor below. reversePrint has the following parameters: Sing

View Solution →

Reverse a linked list

Given the pointer to the head node of a linked list, change the next pointers of the nodes so that their order is reversed. The head pointer given may be null meaning that the initial list is empty. Example: head references the list 1->2->3->Null. Manipulate the next pointers of each node in place and return head, now referencing the head of the list 3->2->1->Null. Function Descriptio

View Solution →

Compare two linked lists

You’re given the pointer to the head nodes of two linked lists. Compare the data in the nodes of the linked lists to check if they are equal. If all data attributes are equal and the lists are the same length, return 1. Otherwise, return 0. Example: list1=1->2->3->Null list2=1->2->3->4->Null The two lists have equal data attributes for the first 3 nodes. list2 is longer, though, so the lis

View Solution →

Merge two sorted linked lists

This challenge is part of a tutorial track by MyCodeSchool Given pointers to the heads of two sorted linked lists, merge them into a single, sorted linked list. Either head pointer may be null meaning that the corresponding list is empty. Example headA refers to 1 -> 3 -> 7 -> NULL headB refers to 1 -> 2 -> NULL The new list is 1 -> 1 -> 2 -> 3 -> 7 -> NULL. Function Description C

View Solution →

Get Node Value

This challenge is part of a tutorial track by MyCodeSchool Given a pointer to the head of a linked list and a specific position, determine the data value at that position. Count backwards from the tail node. The tail is at postion 0, its parent is at 1 and so on. Example head refers to 3 -> 2 -> 1 -> 0 -> NULL positionFromTail = 2 Each of the data values matches its distance from the t

View Solution →

Delete duplicate-value nodes from a sorted linked list

This challenge is part of a tutorial track by MyCodeSchool You are given the pointer to the head node of a sorted linked list, where the data in the nodes is in ascending order. Delete nodes and return a sorted list with each distinct value in the original list. The given head pointer may be null indicating that the list is empty. Example head refers to the first node in the list 1 -> 2 -

View Solution →