algoritmauzmanı
Sign in
TREN
9.4Hashing Applications
Lesson 9.4.2

Counting and finding duplicates with hashing

The first answer that comes to mind for "does this array contain a repeated element?" is comparing every element with all the others: two nested loops, . A hash table answers it in a single pass, because it answers "have I seen this before?" in on average. Many exam and interview questions rest on this idea: counting, finding duplicates, the common elements of two arrays.

What you will learn
  • How to find the first repeated element of an array in one pass with a hash set
  • How to count elements with a hash dictionary
  • Why the price of going from O(n²) to O(n) time is extra memory
6 minTime O(n)Memory O(n)C · Java · Python

1Idea

The idea is this: the array is read once from start to end and the elements seen so far are kept in a hash set. For each element we first check whether it is in the set. If it is, the element was seen before and it is the first repeat. If not, it is added to the set and we go on. If no repeat turns up by the end of the array, -1 is returned.

C has no built-in hash set; the insert function of the chained table does exactly this job, because it returns false when the key is already there. In Java, HashSet's add method works the same way. In Python a set is used. In all three languages "is it there" and "add" are O(1) on average.

Counting

To find how many times each element appears, a dictionary is used instead of a set: the key is the element itself and the value is its count. If the element is not in the dictionary it is added with a count of 1, otherwise its count goes up by one. This too finishes in one pass, in O(n).

def count(arr):    counter = {}    for x in arr:        counter[x] = counter.get(x, 0) + 1  # start at 0 if missing    return counter # count([15, 7, 26, 9, 7, 15, 7])  ->  {15: 2, 7: 3, 26: 1, 9: 1}
java.util.HashMap<Integer, Integer> count(int[] arr) {    java.util.HashMap<Integer, Integer> counter = new java.util.HashMap<>();    for (int x : arr)        counter.merge(x, 1, Integer::sum);  // 1 if missing, else add one    return counter;}

The same pattern fits other questions: the common elements of two arrays (put one in a set, search the other), two elements that add up to a target (is target - x in the set for each x?), the most frequent element (count, then find the largest count).

2Step by step

The drawing looks for the first repeated element in the array 15, 7, 26, 9, 7, 15. The row below is the hash set of elements seen so far; under each element is the bucket it lands in (M = 11). At each step the matching lines of code light up.

arrayseen (hash set)15071262937415515bucket 47bucket 726bucket 49bucket 9i
  1. Start. The set is empty.
  2. 15 is not in the set. It is added and lands in bucket 4.
  3. 7 is not in the set, so it is added.
  4. 26 also lands in bucket 4. The bucket holds 15 but not 26, so 26 is not in the set. It is added. The same bucket does not mean the same element.
  5. 9 is not in the set, so it is added.
  6. 7 is in the set: this element was seen before.
  7. The function returns 7. 15 repeats too, but its second appearance comes after 7's.

#define M 11 struct Node {    int data;    struct Node* next;}; struct HashTable {    struct Node* buckets[M];    int count;}; int hash(int key) {    return key % M;} void create(struct HashTable* t) {    for (int i = 0; i < M; i++)        t->buckets[i] = NULL;    t->count = 0;} bool insert(struct HashTable* t, int key) {     // 9.3.1    int i = hash(key);    for (struct Node* p = t->buckets[i]; p != NULL; p = p->next)        if (p->data == key)            return false;               // already there    struct Node* node = malloc(sizeof(struct Node));    if (node == NULL) return false;    node->data = key;    node->next = t->buckets[i];    t->buckets[i] = node;    t->count++;    return true;} void clear(struct HashTable* t) {    for (int i = 0; i < M; i++) {        struct Node* p = t->buckets[i];        while (p != NULL) {            struct Node* following = p->next;            free(p);            p = following;        }    }} int firstRepeat(int arr[], int n) {    struct HashTable seen;    create(&seen);    int result = -1;                    // -1 if nothing repeats    for (int i = 0; i < n; i++) {        if (!insert(&seen, arr[i])) {   // seen before            result = arr[i];            break;        }    }    clear(&seen);    return result;}
int firstRepeat(int[] arr) {    java.util.HashSet<Integer> seen = new java.util.HashSet<>();    for (int i = 0; i < arr.length; i++) {        if (!seen.add(arr[i]))          // add returns false if present            return arr[i];              // seen before    }    return -1;                          // nothing repeats}
def first_repeat(arr):    seen = set()    for x in arr:        if x in seen:                   # seen before            return x        seen.add(x)    return -1                           # nothing repeats

The snippets focus on the operation in this lesson. The C examples need stdlib.h.

3Complexity

Time
O(n)

The array is read once; for each element the search and insertion in the set take O(1) on average. In total O(n). In the worst case, with every element in the same bucket, O(n²).

Memory
O(n)

The set holds at most n elements: O(n). The nested-loop solution uses no extra room but takes O(n²).

This is a typical trade between time and memory. If the array may be sorted there is a third way: sorting and then checking neighbouring elements takes O(n log n) and may need no extra room, but the order of the "first" repeat is lost.

4Common mistake

A common mistake is checking the set after adding the element to it:

for x in arr:    seen.add(x)    if x in seen:        # always true        return x

The element was just added, so the condition is always true and the function returns the first element of the array. Check first, then add. In Java, using the return value of add gets this order right in a single step.

5Try it

What does first_repeat return for the array [4, 9, 4, 9]?

Show the answer

The answer is B. 4 and 9 are added to the set. The third element, 4, is in the set and the function returns 4 right away.

What is the price of using a hash set instead of nested loops to find a repeat in an array of a million elements?

Show the answer

The answer is A. A hash set brings the time down from O(n²) to O(n) on average; in exchange it needs O(n) extra memory. The result is correct and the array does not need to be sorted.

Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.