I am required to implement two operations below with performance constraints,
/** insert a character, c at a given position, pos **/
void insert(char c, int pos);
/** return the current character at given position, pos **/
char query(int pos);
Both of these functions can be called 10^8 times :(. Inserting new value at any position will change/increase all of positions of its right parts elements.
At first, I was thinking to implement with Array
but that costs a lot in worst case insert()
, because every time I need to shift right part of the array when I insert new value somewhere at the beginning of the Array.
Then I was thinking to implement with Linked List
, but this has the same cost for query()
function because, to get the actual value I must move forward/backword of the linked list.
I wonder if there is any well known algorithm or data structure which can be helpful in this situation.
Update #1:
Similar question was posted here (Data structure: insert, remove, contains, get random element, all at O(1)) before,
but hash is not feasible for this problem because of frequent collisions when the value is of char type. There can be only 26 char in 10^8 positions. Also I don't need to solve in O(1) because this problem seems not solvable in O(1) by its nature. I want some trade of or hybrid solution where worst case of array and linkedlist will be minimized.
As @DAIe mentioned in comment I need some string like operations. Moreover, insert to positio
n operation is not a hashtable operation at all.