I need to offer a data structure like struck, with these functions:
init()
with a time complexity of O(1): initialization of an empty structure.push(x)
with a time complexity of O(1): insert a new element with key x to the structure.pop()
with a time complexity of O(1): remove the element that was last inserted into the structure.getMiddle()
with a time complexity of O(1): return the key of the middle (n/2) element (in insertion order).getAt(k)
with a time complexity of O(log k): return the key of the kth element (in insertion order).
Space complexity is O(n), when n is the nunmber of the elements in the structure.
I am allowed to use the following structures: ADT, Queue, Stack, Array, Linked List, Binary Tree and Binary Search Tree.
I thought about using a linked list, because the initialization of a list is O(1). To insert an element and to remove an element is also O(1). In the functions of push
and pop
, I thought to use a pointer that points to the middle, and at every insert or delete, the pointer would move. So, in the middle
function, return the key at this pointer.
My problem is the last program. I thought about performing a binary search, but the time complexity is O(log(n)) and I need O(log(k)). I thought to split the list in the kth element, but I don't know how.
Do you have any suggestion to solve this problem?