Google Interview Question for Software Engineers


Country: United States
Interview Type: In-Person




Comment hidden because of low score. Click to expand.
1
of 1 vote

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!

import java.util.Stack;
class CharNode {
    char ch;
    CharNode prev;
    CharNode next;

    public CharNode(char ch) { this.ch = ch; }
}

class Edit {
    String edition; //"DEL", "INS", "LEFT", "RIGHT"
    CharNode data;
    public Edit(String edition, CharNode cur) {
        data = cur;
        this.edition = edition;
    }
}

public class TextEditor {
    private Stack<Edit> undo_stack;
    private CharNode cursor;
    private CharNode end;

    public TextEditor() {
        undo_stack = new Stack();
        end = new CharNode('\0');
        cursor = end;
    }

    public void moveCursorLeft() {
        if(cursor.prev == null) return;
        cursor = cursor.prev;
        undo_stack.push(new Edit("RIGHT", null));
    }

    public void moveCursorRight() {
        if(cursor == end) return;
        cursor = cursor.next;
        undo_stack.push(new Edit("LEFT", null));
    }

    public void insertCharacter(char ch) {
        CharNode n = new CharNode(ch);
        insert(n);
        undo_stack.push(new Edit("DEL", null));
    }

    public void backspace() {
        if(cursor.prev == null) return;
        undo_stack.push(new Edit("INS", delete(cursor.prev)));
    }

    public void undo() {
        if(undo_stack.isEmpty()) return;
        Edit edit = undo_stack.pop();
        switch(edit.edition) {
            case "LEFT":
                cursor = cursor.prev; break;
            case "RIGHT":
                cursor = cursor.next; break;
            case "DEL":
                delete(cursor.prev); break;
            case "INS":
                insert(edit.data); break;
            default:
                return;
        }
    }

    public String toString() {
        StringBuilder text = new StringBuilder();
        CharNode n = end.prev;
        if(cursor == end) text.append('|');
        while(n != null) {
            text.insert(0, n.ch);
            if(cursor == n) text.insert(0, '|');
            n = n.prev;
        }
        return text.toString();
    }

    private void insert(CharNode node) {
        CharNode prev = cursor.prev;
        node.next = cursor;
        cursor.prev = node;
        if(prev != null) {
            prev.next = node;
            node.prev = prev;
        }
    }

    private CharNode delete(CharNode del) {
        if(del.prev != null) {
            del.prev.next = cursor;
        }
        cursor.prev = del.prev;
        return del;
    }
}

- aonecoding4 December 04, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

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;
}

- toan@tabvn.com December 16, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#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|
|
|

- lesit.jae December 17, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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;
    }
}

- nitinguptaiit April 12, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

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;
    }
}

- nitinguptaiit April 12, 2019 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

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 + " ";

    }
}

- nitinguptaiit April 12, 2019 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

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();

}

- nitinguptaiit April 12, 2019 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

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();
}

- bertelli.lorenzo April 14, 2019 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More