Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Queue-like data structure with fast search and insertion

I need a datastructure with the following properties:

  1. It contains integer numbers.
  2. Duplicates aren't allowed (that is, it stores at most one of any integer).
  3. After it reaches the maximal size the first element is removed. So if the capacity is 3, then this is how it would look when putting in it sequential numbers: {}, {1}, {1, 2}, {1, 2, 3}, {2, 3, 4}, {3, 4, 5} etc.
  4. Only two operations are needed: inserting a number into this container (INSERT) and checking if the number is already in the container (EXISTS). The number of EXISTS operations is expected to be approximately 2 * number of INSERT operations.
  5. I need these operations to be as fast as possible.

What would be the fastest data structure or combination of data structures for this scenario?

like image 691
Max Avatar asked Oct 19 '25 05:10

Max


2 Answers

Sounds like a hash table using a ring buffer for storage.

like image 55
Daniel DiPaolo Avatar answered Oct 21 '25 19:10

Daniel DiPaolo


O(1) for both insert and lookup (and delete if you eventually need it).

Data structures:

Queue of Nodes containing the integers, implemented as a linked list (queue)

and

HashMap mapping integers to Queue's linked list nodes (hashmap)

Insert:

if (queue.size >= MAX_SIZE) {
    // Remove oldest int from queue and hashmap
    hashmap.remove(queue.pop());
} else if (!hashmap.exists(newInt)) { // remove condition to allow dupes.
    // add new int to queue and hashmap if not already there
    Node n = new Node(newInt);
    queue.push(n);
    hashmap.add(newInt, n);
}

Lookup:

return hashmap.exists(lookupInt);

Note: With this implementation, you can also remove integers in O(1) since all you have to do is lookup the Node in the hashmap, and remove it from the linked list (by linking its neighbors together.)

like image 41
Ben S Avatar answered Oct 21 '25 19:10

Ben S



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!