Skip to content

Hash Table ​

A hash table turns each input into a numeric key and stores it at that key's slot; when searching, it checks only that slot, which greatly cuts down search time.

At a Glance ​

It is a concept you must know to solve algorithm problems. Hashing is applied to problems where brute force (exhaustive search, comparing everything one by one) times out.

Think of school lockers. You compute a locker number from the letters of a name and put the item in that locker. When you look for it later, you do not have to open every student's locker; you compute the number the same way and open only that one.

  • Hash function: a function that turns an input (such as a string) into a number (key) within a fixed range. It is the formula for computing the locker number.
  • Collision: when different inputs produce the same key. It is like two people's belongings ending up in one locker. Collisions should be avoided as much as possible, but there is no guarantee they can always be avoided. So each slot is built to hold several items.

As in the figure below, putting a name (key) into the hash function gives a slot number, and the phone number (value) is stored in that slot.

A hash table that turns names into slot numbers with a hash function and stores phone numbers

Image source: Wikimedia Commons (CC BY-SA 3.0, Jorge Stolfi)

Python's dict and set are exactly hash tables. The hash map data structure itself is covered in more detail in the hash map article. Following the original source, this article walks through solving a problem by implementing a hash table yourself.

Practice Problem ​

Codeforces 4C - Registration system

N (1~100,000) strings are given one after another. Print OK for a string seen for the first time, and string+number for a string that has appeared before. The number is how many times that string has come in again (1, 2, 3, ...).

Sample Input ​

5
abcd
abc
abcd
abcd
ab

Sample Output ​

OK
OK
abcd1
abcd2
OK

The problem is easy to understand. Check whether the same string has come in before, and if it has, print it with a number attached.

But N can be up to 100,000. With brute force, comparing each new string against all previous strings takes about N² comparisons, i.e. on the order of 10 billion, which times out. That is why it must be solved with a hash table: store each input string under a hash key and keep the number of comparisons as low as possible.

It is a great practice problem for applying hash tables to algorithm problems. It is especially good practice if you are preparing for Samsung's regular SW Competency Test (Type B), which requires you to implement a hash table yourself without libraries.

Implementing the Hash Table ​

To reduce searching as much as possible, a hash table computes a key value for each input and manages it at that key's slot.

Choosing the Size ​

There are at most 100,000 inputs. Dividing them into 1000 slots (buckets) puts about 100 in each slot on average. So managing them with a 1000 × 100 two-dimensional array is efficient.

Because of collisions, some slots may receive more than the average. To allow for this, the original source multiplies the second dimension (the capacity of one slot) by 4 and generously sets it to 400.

NameValueMeaning
HASH_SIZE1000Number of slots (buckets). The key is one of 0~999
HASH_LEN400Number of different strings one slot can hold (average 100 × 4)
HASH_VAL17The multiplier used when computing the key. Chosen to be a prime

HASH_VAL is used to compute the key for an input. To keep keys from overlapping as much as possible, a prime such as 17, 19 or 23 is usually used. Multiplying by a prime tends to spread results evenly even when the letter order or combination differs only slightly. However, using a prime does not eliminate collisions; it is a trick to reduce them.

The Function That Makes the Key ​

You can get an integer value (character code) for each character of a string. Using this, loop over the length of the string to create a key unique to that string. Everyone does this differently, and the method below is not the only right answer.

  1. Start with key = 0.
  2. For each character, mix it in with key = key × HASH_VAL + character code + HASH_VAL.
  3. At the end, use the remainder after dividing by HASH_SIZE as the key.

The computed value is very large, so only the remainder after dividing by HASH_SIZE is used as the key. That keeps the key always between 0 and 999. In exchange, the more data there is, the more inevitable it becomes that some strings share a key (collide). The goal is to build it quickly while keeping collisions as low as possible.

The key is used as an array index, so it must not be negative. In the original Java code, the integer can overflow during the computation and become negative, so it is made positive with if (key < 0) key = -key;. Python integers have no size limit, and the code below takes the remainder for each character to keep the number small, so it is always 0 or greater.

Searching Within the Same Key ​

Once you have the key, you must check whether this string has come into that key's slot before. Now you do not need to look everywhere, only in this key's slot, which saves an enormous amount of time.

However, with lots of data, a different string may be stored under the same key. In the figure below, John Smith and Sandra Dee both go to slot 152 (a collision) and are stored in a row in the same slot. The only difference is that the figure links them with a linked list, while the implementation in this article stores them in order in a fixed-size array for each slot.

Two keys colliding into the same slot and being stored together in it

Image source: Wikimedia Commons (CC BY-SA 3.0, Jorge Stolfi)

So we go through the key's slot and compare whether the strings match exactly. Three arrays are used for this.

ArraySizeWhat it stores
s_data[key][i]HASH_SIZE × HASH_LENThe input string itself
data[key][i]HASH_SIZE × HASH_LENHow many times that string has come in again
length[key]HASH_SIZENumber of different strings stored in each key's slot

There are two output conditions.

  • Print OK: if length for that key's slot is 0, the data is definitely new. Even if length is 1 or more, if the same string was not found in that slot, the data is also new.
  • Print string+count: if length is 1 or more and the same string was found in the slot, increase the count by 1 and print string+count.

Managing slots with lists that keep growing (Java's ArrayList, Python's append) makes implementation easy, since you just keep adding. But when libraries are not allowed, as in Samsung's SW Competency Test (Type B), you must declare arrays in advance and fill them in. The original source recommends using arrays whenever possible, since fixed-size arrays can save more time than ArrayList. The Python code below follows the same approach and uses lists of a fixed size.

How It Works ​

Suppose the inputs come in the order apple → banana → abc → abc, and assume the keys of apple and abc are both 5. (A collision.)

OrderInputkeyWhat is checkedState after savingOutput
1apple5length[5] = 0 → first times_data[5][0] = apple, length[5] = 1OK
2banana3length[3] = 0 → first times_data[3][0] = banana, length[3] = 1OK
3abc5length[5] = 1, so compare cell 0: apple ≠ abc → first times_data[5][1] = abc, length[5] = 2OK
4abc5length[5] = 2, so compare cells 0 and 1: cell 1 abc matchesdata[5][1] = 1abc1

Steps 3 and 4 are the key part.

  • Step 3: something has come into key 5's slot before, but it is only apple, so abc is new. Put abc at the current length[5] position (cell 1), then increase length[5] to 2.
  • Step 4: only 2 entries in key 5's slot need to be compared. Cell 0 is apple, and abc is found in cell 1. Increase data[5][1] by 1 and return that value 1, and abc1 is printed by attaching 1 to abc.

Python Code ​

A Hand-Built Hash Table ​

python
HASH_SIZE = 1000   # Number of slots (buckets)
HASH_LEN = 400     # Number of different strings one slot can hold
HASH_VAL = 17      # Multiplier (a prime)

data = [[0] * HASH_LEN for _ in range(HASH_SIZE)]       # Number of times it came in again
length = [0] * HASH_SIZE                                # Number of strings stored in each slot
s_data = [[None] * HASH_LEN for _ in range(HASH_SIZE)]  # The actual strings


def get_hash_key(s):
    key = 0
    for ch in s:
        # 1. Mix the key for each character, taking the remainder each time so the number stays small
        key = (key * HASH_VAL + ord(ch) + HASH_VAL) % HASH_SIZE
    return key  # 2. Always between 0 and HASH_SIZE-1


def checking(key, s):
    for i in range(length[key]):       # 3. Search only within the same key's slot
        if s_data[key][i] == s:
            data[key][i] += 1          # 4. A string that already existed: count +1, then return it
            return data[key][i]
    s_data[key][length[key]] = s       # 5. A new string: store it at the current length position
    length[key] += 1                   #    then count +1
    return -1                          #    -1 if it is new


def solve(lines):
    out = []
    for s in lines:
        cnt = checking(get_hash_key(s), s)
        out.append("OK" if cnt == -1 else s + str(cnt))  # 6. Output rule
    return out


print("\n".join(solve(["abcd", "abc", "abcd", "abcd", "ab"])))
# Output:
# OK
# OK
# abcd1
# abcd2
# OK
  1. ord(ch) is the character's code number. It is the same formula as in the original full code (key * 17 + character + 17), but % HASH_SIZE is applied for every character so that negative or overly large numbers never appear. The result is the same as taking the remainder once at the end.
  2. The returned key can be used directly as a slot number.
  3. Compare only as many entries as are stored in that key's slot (length[key]). That is usually a few dozen to a hundred, not all 100,000.
  4. If the same string is found, increase its count and return the count.
  5. If it is not found, store it in the slot's empty position (length[key]), then increase the count. This is the same order as s_data[key][length[key]++] = str in the original Java.
  6. If it is -1, print OK; otherwise print string+count.

For an actual submission, read N and the strings with sys.stdin and pass them to solve. If more than 400 different strings pile into one slot, an IndexError occurs, so if that is a concern, increase HASH_LEN or use the dict version below.

A Version Solved with Python's dict ​

If libraries are allowed, Python's dict does the process above for you internally.

python
def solve_dict(lines):
    seen = {}                        # 1. String → number of times it came in again
    out = []
    for s in lines:
        if s in seen:                # 2. Check whether it came in before, O(1) on average
            seen[s] += 1
            out.append(s + str(seen[s]))
        else:
            seen[s] = 0              # 3. If it is new, register it with 0
            out.append("OK")
    return out


print(solve_dict(["abcd", "abc", "abcd", "abcd", "ab"]))
# Output: ['OK', 'OK', 'abcd1', 'abcd2', 'OK']
  1. The dict's keys are strings and its values are the number of times each came in again.
  2. The in check internally finds the slot by hash and compares, so it is O(1) on average.
  3. A new string is registered with a count of 0, and OK is printed.

Time and Space Complexity ​

CaseOne lookup/insertProcessing N itemsReason
BestO(1)O(N)The key's slot is empty, or the string is found right away in the first cell
AverageO(1)O(N)If strings spread evenly across slots, each slot holds few items
WorstO(N)O(N²)If every string piles into one slot, you end up comparing everything
  • Here O(1) means "the number of comparisons within a slot" is constant. Computing the key and comparing strings takes time proportional to the string length L, so strictly speaking each operation is O(L).
  • Space complexity: the hand-built version uses the pre-allocated array size O(HASH_SIZE × HASH_LEN), and the dict version uses O(N), proportional to the number of stored strings.
  • The key point is that brute force O(N²) (about 10 billion operations) becomes O(N) on average (about 100,000) with hashing. For complexity notation, see the time complexity article.

Summary ​

ConceptPlain-language summary
Hash tableCompute a locker number from a name, and store and look up items only in that locker
Hash functionA formula that turns a string into a slot number within a fixed range
CollisionDifferent strings getting the same slot number. They are told apart by comparing once more inside the slot
Prime HASH_VALA trick that spreads slot numbers evenly instead of piling them on one side