Which is the following data structures be best suited for insertion, deletion, lookup, set intersection, union? Optimize time complexity.
- Bitmaps
- Binary search tree
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Foreward
The question is ambiguous, so I will make some assumptions.
First we are trying to represent a set of numbers over the range [0 to M] where M is a reasonably small number like 100,000.
The BST can simply contain the elements that are in the set.
The Bitmap can just be M bits long, and a bit is set if the number at that position is in the set, if not, the number is not in the set. I will assume that a Bitmap has already been created of size M.
In this answer I consider Self-Balancing Binary Search Trees and Bitmaps–for non-balancing BSTs you would have to deal with best case, average case, and worst cases for each operation.
Operations and Complexity
Insertion: Add n to the set.
Deletion: Remove n from the set.
Look-Up: Is n in the set?
Set Intersection: Here’s 2 sets, which ones are the same.
BSTs: Do in-order traversals of both BSTs in a kind-of-MergeSort style, if two elements are the same add that into the return BST.
Bitmap: Walk over both bitmaps, storing the ( AND ) of bytes (or say 32 bits at a time) and store it in the result location as a bitmap. O( M ) where M is the size of the range the bitmaps are initialized to.
Set Union: Here’s 2 sets, combine them.
Ambiguities in the Question
Conclusion
Bitmaps are better than self-balancing-BSTs for just about all of these operation.
Downsides of inclusion/exclusion Bitmaps: