Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What data structure for O(1) random insertion/deletion and O(1) random access?

I don't know what data structure to use for this problem. I want the structure to have:

  • Constant time insertion or deletion.
  • Constant time retrieval by id.

The actual system is:

I've got a bunch of objects each with a unique id. My program will need to receive requests for an id and return the relevant object.

Whenever it receives a request I want it to: search the structure to see if it's there. If it is, return it. If it isn't, load it from the disk into memory (put it in the structure so that next time it is requested it doesn't have to use the disk) and then return it.

I'm using C.

Here's a similar question but I'm not sure how relevant it is.

like image 260
Ollie Saunders Avatar asked Sep 03 '25 16:09

Ollie Saunders


2 Answers

A Hash table might be a pretty good solution in your case -- even if it's not in O(1) when there's a colision : it's a quite efficient solution.

like image 102
Pascal MARTIN Avatar answered Sep 05 '25 09:09

Pascal MARTIN


The only structure that fits it is... C array. SomeObject arr[MAX_NUM_OBJECTS] handles this in fast and efficient way

like image 37
alemjerus Avatar answered Sep 05 '25 08:09

alemjerus