Efficient data structure to implement simple text editor?

I was given this problem in an interview:

What data structure would you use to implement a simple text editor that does these 4 functions:

a) goto(line number)

b) insert(char input,location)

c) delete(location)

d) printAll() //print entire file

Given that i'm such a newb, i was stumped. I came up with making a 2d array that would allow for o(1) time for goto, but o(n) for everything else (shifting everything in the array). there were other downfalls too dealing with space issues and such, but he wanted me to optimize this data structure. I then came up with a linked list of arrays, but that had similar problems.

But thinking about it further is driving me a little crazy so I'm wondering if you guys have any suggestions on how to answer this question...

one thing that came to mind after is to implement the data structure as a binary tree, where each node contains

class Node

{

char theChar

int position;// ie 0 = first character in the file, and 81 could be the first character in the 2nd line

node left,right,parent;

}

so how it works is the cursor would know where the location was so i would know where to delete and insert within the tree.

insert{

//search for location to insert after (log n)

//create new character node and append to current node

//increment position for all subsequent children

}

delete(x){

searchfor x position

if found, remove node and decrement position valuefor all children

}

goto(line #){

return line # * 80 (or whatever max lengthfor a single line)

}

the major problem i see here is balancing the tree after every insert/delete

Thanks in advance.

[2414 byte] By [lapcherna] at [2007-10-3 1:50:22]
# 1
One of many great things emacs has given us is the gap buffer: http://en.wikipedia.org/wiki/Gap_bufferTo see a Java implementation of this you can look in the Java SDK source. The document model (I forget exactly what its called), used in Swing uses a gap buffer.
RadcliffePikea at 2007-7-14 18:48:46 > top of Java-index,Other Topics,Algorithms...
# 2
that is an interesting solution... to anticipate insertions/deletions in a certain area and leave gaps there (shifting the array to create gaps on occasion).... i wouldn't have been able to come up with kind of solution :( but it's good that i know now, thanks!
lapcherna at 2007-7-14 18:48:46 > top of Java-index,Other Topics,Algorithms...