algorithm - Best data structure for a given set of operations - Add, Retrieve Min/Max and Retrieve a specific object -
i looking optimal (time , space) optimal data structure supporting following operations:
- add persons (name, age) global data store of persons
- fetch person minimum , maximum age
- search person's age given name
here's think of:
- keep array of persons, , keep adding end of array when new person added
- keep hash of person name vs. age, assist in fetching person's age given name
- maintain 2 objects minperson , maxperson person min , max age. update if needed, when new person added.
now, although keep hash better performance of (3), think may not best way if there many collisions in hash. also, addition of person mean overhead of adding hash.
is there can further optimized here?
note: looking best (balanced) approach support these operations in minimum time , space.
it looks need data structure needs fast inserts , supports fast queries on 2 different keys (name , age).
i suggest keeping 2 data structures, 1 sorted data structure (e.g. balanced binary search tree) key age , value pointer person object, other hashtable key name , value pointer person object. notice don't keep 2 copies of same object.
a balanced binary search tree provide o(log(n)) inserts , max/min queries, while hastable give o(1) (amortized) inserts , lookups.
when add new person, add pointer both data structures. min/max age query, can retrieve object querying bst. name query can query hashtable.
your question not ask updates/deletes, doable suitably updating both data structures.
Comments
Post a Comment