I got this question in a Java interview today.
I have to implement a collection which is an array and have add
and delete
methods which can perform only at the end of an array.
In addition to that I have to implement two more methods which is the undo
and redo
methods which can be performed only once.
For example:
Let x be an array containing {1,5,7,9}.
Now I add {44,66,77}
in it and make it {1,5,7,9,44,66,77}
.
Now when I undo it, the array should delete {44,66,77}
. And if I do redo afterwards, it should be back to {1,5,7,9,44,66,77}
.
And similarly for the delete.
What is the best way to achieve this in terms of complexity and memory?
My solution to the interviewer:
- Make one string field which stores the last operation, i.e. "Add"/"Delete".
- And a hashmap which stores key as an index of array and value as the index value of an array.
Which is a totally incorrect solution as per interviewer.