Google Interview Question
Software EngineersCountry: United States
Interview Type: In-Person
Original Link: https://github.com/tabvn/ued/blob/master/careercup/google/design_text_editor.cpp
#include <iostream>
#include <vector>
#include <string>
const char CURSOR = '|';
struct Revision
{
std::string text;
int cursorIndex;
Revision(){
this->text = CURSOR;
this->cursorIndex = 0;
}
};
struct TextEditor
{
std::vector<Revision> revisions; // store all revisions for undo
int currentRevision;
TextEditor(){
this->currentRevision = 0;
Revision r;
this->revisions.push_back(r);
this->displayText("Start with empty text");
}
void displayText(std::string funcName){
Revision revision = this->revisions[this->currentRevision];
std::cout << funcName << std::endl;
std::cout << "text = \"" << revision.text << "\"" << std::endl;
}
/*
* Move cursor index to left
*/
void moveCursorLeft(){
Revision r = this->revisions[this->currentRevision];
char leftChar;
if(r.cursorIndex > 0){
leftChar = r.text[r.cursorIndex-1];
r.text[r.cursorIndex-1] = CURSOR;
r.text[r.cursorIndex] = leftChar;
r.cursorIndex --;
this->revisions.push_back(r);
this->currentRevision ++;
}
this->displayText("moveCursorLeft()");
}
/*
* Move cursor index to right
*/
void moveCursorRight(){
Revision r = this->revisions[this->currentRevision];
char rightChar;
if(r.cursorIndex < r.text.size() -1){
rightChar = r.text[r.cursorIndex+1];
r.text[r.cursorIndex+1] = CURSOR;
r.text[r.cursorIndex] = rightChar;
r.cursorIndex ++;
this->revisions.push_back(r);
this->currentRevision ++;
}
this->displayText("moveCursorRight()");
}
/*
* Insert the char right before cursor
*/
void insertCharacter(char ch){
Revision r = this->revisions[this->currentRevision];
r.text[r.cursorIndex] = ch;
r.text += "|";
r.cursorIndex++;
this->revisions.push_back(r); // new revision become current revision
this->currentRevision ++;
std::string s = "insertCharacter('";
s+= ch;
s+= "')";
this->displayText(s);
}
/*
* delete the char right before cursor
*/
void backspace(){
Revision r = this->revisions[this->currentRevision];
if(r.text.size() > 1 && r.cursorIndex > 0){
r.text.erase(r.cursorIndex - 1, 1);
r.cursorIndex --;
this->revisions.push_back(r);
this->currentRevision++;
}
this->displayText("backspace()");
}
/*
* Undo last edit
*/
void undo(){
if(this->currentRevision > 0){
this->currentRevision--;
}
this->displayText("undo()");
}
};
void beginTest(){
TextEditor editor;
editor.insertCharacter('a');
editor.insertCharacter('b');
editor.insertCharacter('c');
editor.moveCursorLeft();
editor.moveCursorLeft();
editor.moveCursorLeft();
editor.backspace();
editor.moveCursorLeft();
editor.undo();
editor.undo();
editor.undo();
editor.undo();
editor.undo();
}
int main(int argc, char const *argv[]){
beginTest();
return 0;
}
#include<list>
#include<stack>
using namespace std;
enum class _ops{ins, del};
struct UndoOps
{
UndoOps(_ops ops, list<char>::const_iterator it, char ch=0)
{
this->ops=ops;
this->it=it;
this->ch=ch;
}
list<char>::const_iterator it;
_ops ops;
char ch;
};
class TextEditor
{
private:
stack<UndoOps> undo_stack;
list<char> text;
list<char>::const_iterator cur;
public:
TextEditor()
{
cur=text.end();
}
~TextEditor()
{
}
void left()
{
if(cur==text.begin()) return;
--cur;
}
void right()
{
if(cur==text.end()) return;
++cur;
}
void ins(char ch)
{
cur=text.insert(cur, ch);
undo_stack.push(UndoOps(_ops::del, cur));
++cur;
}
void backspace()
{
if(cur==text.begin()) return;
list<char>::const_iterator item=cur;--item;
char ch=*item;
cur=item;cur--;
text.erase(item);
++cur;
undo_stack.push(UndoOps(_ops::ins, cur, ch));
}
void undo()
{
if(undo_stack.empty()) return;
UndoOps undo=undo_stack.top();
undo_stack.pop();
switch(undo.ops)
{
case _ops::ins:
cur=text.insert(undo.it, undo.ch);
++cur;
break;
case _ops::del:
{
cur=undo.it;--cur;
text.erase(undo.it);
++cur;
}
break;
}
}
void print()
{
for(list<char>::const_iterator it=text.begin();it!=text.end();it++)
{
if(cur==it)
cout<<'|';
cout<<*it;
}
if(cur==text.end())
cout<<'|';
cout<<endl;
}
};
int main() {
TextEditor editor;
editor.ins('a'); editor.print();
editor.ins('b'); editor.print();
editor.ins('c'); editor.print();
editor.left(); editor.print();
editor.left(); editor.print();
editor.left(); editor.print();
editor.right(); editor.print();
editor.right(); editor.print();
editor.right(); editor.print();
editor.backspace(); editor.print();
editor.left(); editor.print();
editor.undo(); editor.print();
editor.undo(); editor.print();
editor.undo(); editor.print();
editor.undo(); editor.print();
editor.undo(); editor.print();
return 0;
}
results:
a|
ab|
abc|
ab|c
a|bc
|abc
a|bc
ab|c
abc|
ab|
a|b
abc|
ab|
a|
|
|
All above code has corner case issues; here is simplest and fixed
package Java.Design.TextEditor;
import java.util.LinkedList;
import java.util.List;
import java.util.Stack;
/**
* Author: Nitin Gupta(nitin.gupta@walmart.com)
* Date: 11/04/19
* Description:
*/
public class SimpleTextEditor implements ITextEditor {
private Stack<Revision> undoStack; //holds the last action
private CharacterNode cursor; //holds the current cursor position
private CharacterNode start; //to print
int totalSize = 0;
public SimpleTextEditor() {
this.undoStack = new Stack<>();
this.cursor = new CharacterNode('\0');
start = null;
}
@Override
public void moveLeft() {
if (cursor.getPrev() == null) return;
cursor = cursor.getPrev();
undoStack.push(new Revision(Action.RIGHT, null));
}
@Override
public void moveRight() {
if (cursor.getNext() == null) return;
cursor = cursor.getNext();
undoStack.push(new Revision(Action.LEFT, null));
}
@Override
public void backspace() {
if (cursor.getPrev() == null) return; //No data to delete
totalSize--;
CharacterNode deleted = delete(cursor.getPrev());
undoStack.push(new Revision(Action.INSERT, deleted));
if (totalSize == 0)
start = null;
}
private CharacterNode delete(CharacterNode toDelete) {
if (toDelete != null) {
CharacterNode prev = toDelete.getPrev();
CharacterNode next = toDelete.getNext();
if (prev != null) {
prev.setNext(next);
}
if (next != null)
next.setPrev(prev);
if (toDelete.getPrev() == null && totalSize == 0)
start = null;
if (toDelete == start)
start = next;
}
if (cursor.getPrev() == null && totalSize == 0)
start = null;
return toDelete;
}
@Override
public void insert(char data) {
CharacterNode node = new CharacterNode(data);
CharacterNode prev = cursor.getPrev();
node.setNext(cursor);
cursor.setPrev(node);
if (prev != null) {
prev.setNext(node);
node.setPrev(prev);
} else
start = node;
if (totalSize == 0)
start = node;
undoStack.push(new Revision(Action.DELETE, node));
totalSize++;
}
@Override
public void undo() {
if (undoStack.isEmpty()) return;
Revision action = undoStack.pop();
switch (action.getAction()) {
case LEFT:
if (cursor != null)
cursor = cursor.getNext();
break;
case RIGHT:
if (cursor != null)
cursor = cursor.getPrev();
break;
case DELETE:
if (cursor != null) {
if (cursor.getPrev() == null)
start = null;
delete(cursor.getPrev());
}
break;
case INSERT:
insert(action.getData().getValue());
break;
}
}
@Override
public String print() {
List<CharacterNode> currentText = new LinkedList<>();
CharacterNode temp = start;
while (temp != null) {
if (temp == cursor)
currentText.add(new CharacterNode('|'));
if (temp.getValue() != '\0')
currentText.add(temp);
temp = temp.getNext();
}
return currentText.toString();
}
@Override
public CharacterNode getCursor() {
return cursor;
}
}
package Java.Design.TextEditor;
/**
* Author: Nitin Gupta(nitin.gupta@walmart.com)
* Date: 11/04/19
* Description:
*/
public class Revision {
private Action action;
private CharacterNode data;
public Revision(Action action, CharacterNode data) {
this.action = action;
this.data = data;
}
public CharacterNode getData() {
return data;
}
public void setData(CharacterNode data) {
this.data = data;
}
@Override
public String toString() {
return "Revision{" +
"action=" + action +
", data=" + data +
'}';
}
public Action getAction() {
return action;
}
public void setAction(Action action) {
this.action = action;
}
}
package Java.Design.TextEditor;
/**
* Author: Nitin Gupta(nitin.gupta@walmart.com)
* Date: 11/04/19
* Description:
* Define the Doubly linked list for text Editor
*/
public class CharacterNode {
private char value;
private CharacterNode next;
private CharacterNode prev;
public CharacterNode(char value) {
this.value = value;
}
public char getValue() {
return value;
}
public void setValue(char value) {
this.value = value;
}
public CharacterNode getNext() {
return next;
}
public void setNext(CharacterNode next) {
this.next = next;
}
public CharacterNode getPrev() {
return prev;
}
public void setPrev(CharacterNode prev) {
this.prev = prev;
}
@Override
public String toString() {
return value + " ";
}
}
package Java.Design.TextEditor;
import java.util.List;
/**
* Author: Nitin Gupta(nitin.gupta@walmart.com)
* Date: 11/04/19
* Description:
*/
public interface ITextEditor {
void moveLeft();
void moveRight();
void backspace();
void insert(char data);
void undo();
String print();
CharacterNode getCursor();
}
Simple C++ implementation with STL list:
class TextEditor
{
public:
TextEditor()
{
text.push_back('|');
cursor = text.begin();
}
void insertCharacter(char c)
{
text.insert(cursor, c);
undoStack.push("b");
}
void moveCursorLeft()
{
if (cursor != text.begin())
{
text.splice(std::prev(cursor), text, cursor);
undoStack.push("r");
}
}
void moveCursorRight()
{
if (cursor != std::prev(text.end()))
{
text.splice(std::next(cursor, 2), text, cursor);
undoStack.push("l");
}
}
void backspace()
{
if (cursor != text.begin())
{
char c = *std::prev(cursor);
string s = "a";
undoStack.push(s + c);
text.erase(std::prev(cursor));
}
}
void undo()
{
if (!undoStack.empty())
{
string s = undoStack.top();
undoStack.pop();
if (s[0] == 'b')
backspace();
else if (s[0] == 'r')
moveCursorRight();
else if (s[0] == 'l')
moveCursorLeft();
else if (s[0] == 'a')
insertCharacter(s[1]);
// this second pop is needed because also the undo write to stack :D
undoStack.pop();
}
}
void print()
{
for (auto it = text.begin(); it != text.end(); ++it)
std::cout << *it;
std::cout << endl;
}
private:
list<char> text;
list<char>::iterator cursor;
stack<string> undoStack;
};
int main() {
TextEditor te;
te.print();
te.insertCharacter('c');
te.insertCharacter('i');
te.insertCharacter('a');
te.insertCharacter('o');
te.print();
te.moveCursorLeft();
te.moveCursorLeft();
te.print();
te.moveCursorRight();
te.moveCursorRight();
te.print();
te.backspace();
te.print();
te.undo();
te.print();
te.undo();
te.print();
}
Looking for interview experience sharing and coaching?
Visit AONECODE.COM for ONE-ON-ONE private lessons by FB, Google and Uber engineers!
SYSTEM DESIGN
ALGORITHMS (conquer DP, Greedy, Graph, Advanced Algorithms, Clean Coding),
latest interview questions sorted by companies,
mock interviews.
Get hired from G, U, FB, Amazon, LinkedIn, Yahoo and other top-tier companies after weeks of training.
Email us aonecoding@gmail.com with any questions. Thanks!
- aonecoding4 December 04, 2018