Explore your understanding of hash maps and sets with these scenario-based questions focusing on entity lookup and tracking state. This quiz covers key concepts like efficient search, duplication checks, and the differences between common data structures in programming.
Given a collection of unique user IDs, which data structure allows you to most efficiently check if a user already exists when processing logins?
Explanation: A hash set enables constant-time (O(1)) presence checking, making it ideal for verifying if a user ID exists. Linked lists and array lists require linear time (O(n)) for such checks since they scan each element. A queue is primarily designed for FIFO access and is not optimized for fast lookups. Therefore, a hash set is the most suitable option for this scenario.
When tracking which items have been purchased by a customer in a shopping cart application, which data structure allows you to map each customer ID to a list of item IDs?
Explanation: A hash map efficiently associates a unique customer ID (the key) with a list of item IDs (the value), enabling quick access to each customer's purchase list. Stacks and priority queues are not meant for key-value relationships; they manage elements based on order or priority. A hash set stores unique items but does not support mapping one entity to collections of others.
You need to count the number of distinct web pages visited from a list that may contain duplicates. Which approach best ensures that each page is counted only once?
Explanation: Using a set automatically removes duplicates, so each web page is stored only once in the collection. Adding URLs to a stack or queue maintains all entries, including duplicates, making it unreliable for unique counting. Sorting the list could help but requires extra steps and is less efficient in both time and code clarity compared to using a set.
If you are managing player scores in a video game where you must update a player’s latest score frequently, which data structure is most appropriate to store and update scores by player ID?
Explanation: A hash map allows you to directly associate each player ID with their current score and to update it in constant time. An array queue or stack stores elements linearly and does not provide direct access by player ID. A tree set is best suited for storing unique items in a sorted order, not for key-value pair updates.
Suppose you want to check if a student's name exists in your registry before assigning them new coursework. What operation would a hash set offer for this scenario?
Explanation: A hash set provides constant-time (O(1)) operations for checking if an item exists, which is ideal for verifying student names quickly. Automatic ordering is not provided by hash sets; ordered sets or trees are used for that. Priority-based access is a feature of priority queues, not sets. Sequential search is common in lists, not in hash sets.