I need a data structure with the following properties:
- Each element of the structure must be unique.
- Add: Adds one element to the data structure unless the element already
exists. - Pop: Removes one element from the data structure and returns the element
removed. It’s unimportant which element is removed.
No other operations are required for this structure. A naive implementation with a list will require almost O(1) time for Pop and O(N) time for Add (since the entire list must be checked to ensure
uniqueness). I am currently using a red-black tree to fulfill the needs of this data structure, but I am wondering if I can use something less complicated to achieve almost the same performance.
I prefer answers in C#, but Java, Javascript, and C++ are also acceptable.
My question is similar to this question, however I have no need to lookup or remove the maximum or minimum value (or indeed any particular kind of value), so I was hoping there would be improvements in that respect. If any of the structures in that question are appropriate here, however, let me know.
So, what data structure allows only unique elements, supports fast add and remove, and is less complicated than a red-black tree?
What about the built-in
HashSet<T>?It contains only unique elements.
Remove(pop) is O(1) andAddis O(1) unless the internal array must be resized.