You can use a HashMap
(of ID to array index) in conjunction with an array (or ArrayList
).
add
could be done in O(1) by simply adding to the array and adding the ID and index to the HashMap
.
remove
could be done in O(1) by doing a lookup (and removal) from the HashMap
to find the index, then move the last index in the array to that index, update that element's index in the HashMap
and decreasing the array size by one.
getRandomElement
could be done in O(1) by returning a random element from the array.
Example:
Array: [5,3,2,4]
HashMap: [5->0, 3->1, 2->2, 4->3]
To remove 3:
Look up (and remove) key 3 in the HashMap (giving 3->1)
Swap 3 and, the last element, 4 in the array
Update 4's index in the HashMap to 1
Decrease the size of the array by 1
Array: [5,4,2]
HashMap: [5->0, 2->2, 4->1]
To add 6:
Simply add it to the array and HashMap
Array: [5,4,2,6]
HashMap: [5->0, 2->2, 4->1, 6->3]