DSA: Topic 2: Hash Maps & Sets
Why interviewers ask hash map questions They want to see if you can: Trade a little extra memory for much faster runtime. Recognise repeated lookups. Avoid nested loops. A common interview progression is: Candidate writes O(n²) → Interviewer asks, "Can you optimise this?" → Expected answer: use a hash map. What is a Hash Map? In Python, a hash map is a dictionary . student = { " Alice " : 95 , "…
Hash maps, also known as dictionaries in Python, are data structures that allow for fast lookups by storing key-value pairs. They provide O(1) average time complexity for insertion, search, and deletion operations. Sets are another type of data structure that store unique elements, enabling efficient membership tests and duplicate removal. When faced with problems that involve frequent lookups, checking for existence, counting frequencies, or matching pairs, hash maps or sets are often the optimal choice.
To tackle frequency counting problems, such as finding the most common element in an array, a frequency table can be built using a hash map. For each element in the input array, its count is updated in the hash map. This approach avoids redundant counting operations and significantly improves efficiency.
In scenarios where the presence of duplicates needs to be determined efficiently, a hash map (or set) can be utilized. By iterating through the array and checking if each element already exists in the hash map, duplicate elements can be identified quickly. This approach reduces the time complexity from O(n²) for the brute-force method to O(n) by avoiding nested loops.
One of the most famous interview problems involving hash maps is the Two Sum problem. Given an array of integers and a target sum, the task is to find the indices of two numbers whose sum equals the target. Instead of using a brute-force approach with nested loops (resulting in O(n²) time complexity), a more efficient solution can be achieved by maintaining a hash map of elements encountered so far.
For each element, the complement needed to reach the target sum is calculated, and if the complement is found in the hash map, the corresponding indices are returned. This optimised solution has a time complexity of O(n), making it the expected answer in interviews.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.