Hashmap Interview Questions

Hash tables (or hash maps) are one of the most widely used data structures in computer science. They allow for efficient storage, retrieval, and manipulation of data by using key-value pairs.
Share on :

Hash tables (or hash maps) are one of the most widely used data structures in computer science. They allow for efficient storage, retrieval, and manipulation of data by using key-value pairs. Hash tables have an average time complexity of O(1) for search, insert, and delete operations, making them a critical tool in solving a variety of coding problems.

In this blog, we’ll go over the top HashMap interview questions, complete with Python solutions to help you prepare for technical interviews.

1. Two Sum Problem

Problem Statement: Given an array of integers and a target sum, return the indices of two numbers that add up to the target.

  • Concept: Hashing for complement lookup
  • Difficulty Level: Easy

Approach: Use a hash map to store the complement (target - current number) and check if the complement exists while iterating through the array.

def two_sum(nums, target):
    hash_map = {}
    for i, num in enumerate(nums):
        complement = target - num
        if complement in hash_map:
            return [hash_map[complement], i]
        hash_map[num] = i

Example:

nums = [2, 7, 11, 15]
target = 9
print(two_sum(nums, target))  # Output: [0, 1]

2. Find the First Non-Repeating Character

Problem Statement: Given a string, find the first non-repeating character and return its index. If it doesn't exist, return -1.

  • Concept: Hashing to count occurrences
  • Difficulty Level: Medium

Approach: Use a hash table to store the count of each character, then iterate through the string to find the first character with a count of 1.

def first_unique_char(s):
    char_count = {}
    
    for char in s:
        char_count[char] = char_count.get(char, 0) + 1

    for i, char in enumerate(s):
        if char_count[char] == 1:
            return i

    return -1

Example:

s = "leetcode"
print(first_unique_char(s))  # Output: 0

3. Group Anagrams

Problem Statement: Given a list of strings, group the anagrams together.

  • Concept: Hashing with sorted string as key
  • Difficulty Level: Medium

Approach: Use a hash table where the key is the sorted version of the string, and the value is a list of anagrams.

from collections import defaultdict

def group_anagrams(strs):
    anagram_map = defaultdict(list)
    
    for word in strs:
        sorted_word = ''.join(sorted(word))
        anagram_map[sorted_word].append(word)
    
    return list(anagram_map.values())

Example:

strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
print(group_anagrams(strs))  # Output: [['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]

4. Subarray Sum Equals K

Problem Statement: Given an array of integers and an integer k, find the total number of continuous subarrays whose sum equals to k.

  • Concept: Hashing with prefix sums
  • Difficulty Level: Medium

Approach: Use a hash map to store the prefix sum and its frequency. As you iterate through the array, check if the prefix sum minus k exists in the hash map, indicating a valid subarray.

def subarray_sum(nums, k):
    count = 0
    prefix_sum = 0
    prefix_map = {0: 1}  # Initialize with 0 sum to handle subarrays starting from index 0

    for num in nums:
        prefix_sum += num
        count += prefix_map.get(prefix_sum - k, 0)
        prefix_map[prefix_sum] = prefix_map.get(prefix_sum, 0) + 1

    return count

Example:

nums = [1, 1, 1]
k = 2
print(subarray_sum(nums, k))  # Output: 2

5. Find All Duplicates in an Array

Problem Statement: Given an array of integers where 1 ≤ a[i] ≤ n (n is the size of the array), some elements appear twice, and others appear once. Find all the elements that appear twice.

  • Concept: Hashing for frequency count
  • Difficulty Level: Medium

Approach: Use a hash map to track the count of each element, and return elements that appear twice.

def find_duplicates(nums):
    element_map = {}
    duplicates = []
    
    for num in nums:
        if num in element_map:
            duplicates.append(num)
        else:
            element_map[num] = 1

    return duplicates

Example:

nums = [4, 3, 2, 7, 8, 2, 3, 1]
print(find_duplicates(nums))  # Output: [2, 3]

6. Longest Substring Without Repeating Characters

Problem Statement: Given a string, find the length of the longest substring without repeating characters.

  • Concept: Hashing with sliding window
  • Difficulty Level: Medium

Approach: Use two pointers and a hash map to track the most recent position of each character. Move the window whenever a repeated character is found.

def longest_substring_without_repeating(s):
    char_map = {}
    left = max_length = 0

    for right, char in enumerate(s):
        if char in char_map and char_map[char] >= left:
            left = char_map[char] + 1
        char_map[char] = right
        max_length = max(max_length, right - left + 1)

    return max_length

Example:

s = "abcabcbb"
print(longest_substring_without_repeating(s))  # Output: 3

7. Intersection of Two Arrays

Problem Statement: Given two arrays, return their intersection (elements that are common between the two arrays).

  • Concept: Hashing to store elements from one array
  • Difficulty Level: Easy

Approach: Use a hash set to store elements from the first array and check if elements from the second array exist in the set.

def intersection(nums1, nums2):
    set_nums1 = set(nums1)
    return list(set_nums1.intersection(nums2))

Example:

nums1 = [1, 2, 2, 1]
nums2 = [2, 2]
print(intersection(nums1, nums2))  # Output: [2]

8. Find the Difference

Problem Statement: Given two strings s and t, where t is generated by random shuffling s and adding one extra letter, find the extra letter.

  • Concept: Hashing with frequency count
  • Difficulty Level: Easy

Approach: Use a hash map to count the frequency of each character in s and t, and find the character with an extra occurrence in t.

def find_the_difference(s, t):
    count_map = {}
    
    for char in s:
        count_map[char] = count_map.get(char, 0) + 1
    
    for char in t:
        if char not in count_map or count_map[char] == 0:
            return char
        count_map[char] -= 1

Example:

s = "abcd"
t = "abcde"
print(find_the_difference(s, t))  # Output: "e"

9. Majority Element

Problem Statement: Given an array of size n, find the majority element. The majority element is the element that appears more than n / 2 times.

  • Concept: Hashing to count occurrences
  • Difficulty Level: Easy

Approach: Use a hash map to store the frequency of each element and check if any element has a count greater than n / 2.

def majority_element(nums):
    count_map = {}
    n = len(nums)
    
    for num in nums:
        count_map[num] = count_map.get(num, 0) + 1
        if count_map[num] > n // 2:
            return num

Example:

nums = [3, 2, 3]
print(majority_element(nums))  # Output: 3

10. Contains Duplicate

Problem Statement: Given an array of integers, find if the array contains any duplicates.

  • Concept: Hashing to track seen elements
  • Difficulty Level: Easy

Approach: Use a hash set to store elements while iterating through the array. If an element is already in the set, return True (duplicate found).

def contains_duplicate(nums):
    seen = set()
    
    for num in nums:
        if num in seen:
            return True
        seen.add(num)
    
    return False

Example:

nums = [1, 2, 3, 2, 5]
print(contains_duplicate(nums))  # Output: True

Conclusion

Hash tables are incredibly useful for solving many types of problems, particularly those involving counting, frequency tracking, and quick lookups. These top 10 hash table interview questions demonstrate how hashing can be applied to real-world problems, from detecting duplicates to finding subarrays with specific properties. By mastering these problems, you’ll gain the skills needed to handle most hash table-related questions in technical interviews.

FAQs

1. What are the key benefits of using a hash table?
Hash tables provide an average time complexity of O(1) for insertions, deletions, and lookups, making them ideal for scenarios requiring quick access to data.

2. How can I improve my understanding of hash table-related problems?
Practice consistently with coding challenges on platforms like LeetCode, HackerRank, and Codeforces. Focus on problems that involve counting elements, detecting duplicates, or solving subarray problems.

3. What are common hash table operations in coding problems?
Common operations include checking for existence of an element, counting occurrences, finding the first unique element, and retrieving values associated with specific keys.

4. How do I handle collisions in a hash table?
Collisions can be handled using techniques like chaining (storing multiple elements at the same index using a linked list) or open addressing (finding another available slot in the hash table).

5. Can hash tables be used with custom objects in Python?
Yes, as long as the objects are hashable (i.e., they have a hash method), you can use them as keys in a Python dictionary or a hash set.