Skip to content
Azhimathi Mayam logoDSA Study HubPCCST303 · KTU · S3
Module 4 · syllabusAsked 4× in KTU papersChecked by code · teacher review pending

Hashing and hash functions

Map keys to table indices: division, mid-square, folding and digit analysis.

Syllabus says: “Hashing - Hashing functions: Mid square, Division, Folding, Digit Analysis”

On this page · 15 sections
ormakkurippu ✎
Never-forget card

DIVISION: k mod m (pick m prime). MID-SQUARE: square, take the middle digits. FOLDING: cut into parts and add. DIGIT ANALYSIS: keep the most evenly spread digits.

Picture it

Hostel room allotment by the last two digits of the admission number — quick, but two students can get the same room (collision).

Write this in the exam

A hash function maps a key to an address in the hash table; common methods are division, mid-square, folding and digit analysis, and a good function is fast and spreads keys uniformly.

Learning objectives

  • Explain hashing, hash tables and load factor.
  • Compute addresses using the four syllabus hash functions.
  • Choose a good table size.

Introduction

Linear search takes O(n) and binary search O(log n). Hashing aims for O(1) average time by computing where a key should be stored instead of searching for it.

Definitions

  • Hash table: an array of m slots (buckets) indexed 0 … m − 1.
  • Hash function h: maps a key k to a home address h(k) in 0 … m − 1.
  • Collision: two different keys with the same home address (synonyms).
  • Load factor α = n/m, where n is the number of keys stored.

The four hash functions in the syllabus

1. Division

h(k) = k mod m. Choose m prime and not close to a power of 2, otherwise only the low-order digits/bits of the key matter.

2. Mid-square

Square the key and take r digits from the middle, where r is the number of digits needed for an address (r = 2 for m = 100). The middle digits depend on every digit of the key, which spreads keys well. Convention used here: if the square has L digits, start at position ⌊(L − r)/2⌋.

3. Folding

Split the key into parts of r digits. Shift folding adds the parts as they are; boundary folding reverses every other part first. Example (shift): 123456 → 12 + 34 + 56 = 102 → 102 mod 100 = 02.

4. Digit analysis

Used for a static set of keys known in advance (e.g. a list of employee IDs). Each digit position is analysed across all keys; positions with skewed distributions are discarded, and the remaining digits form the address.

Where it is used

Symbol tables in compilers, database indexes, caches, dictionaries/sets in every major language, spell checkers.

Worked example

Engine-computed exampleschecked by code
  • division (m = 13): h(1276) = 1276 mod 13 = 2
  • midsquare (m = 100): 3205² = 10272025; middle 2 digits = 72 → 72
  • folding (m = 100): split 123456 into 2-digit parts: 12 + 34 + 56 = 102; 102 mod 100 = 2
  • digit (m = 11): key 7341: digits at positions 2, 4 → 31; 31 mod 11 = 9

Now watch it run

Every frame comes from really running the algorithm on your input — change it and break it! Tap ▶ Play, or step one frame at a time with ◀ ▶.

Loading visualizer…

Algorithm / pseudocode

Open addressing (insert)
  1. 1Operation(k)
  2. 2h ← hash(k)
  3. 3for i ← 0 to m − 1: s ← probe(h, i)
  4. 4if T[s] empty: (insert) store k at first tombstone seen, else at s
  5. 5if T[s] empty: (search/delete) report not found
  6. 6if T[s] = tombstone: remember it, continue
  7. 7if T[s] = k: (search) found
  8. 8if T[s] = k: (delete) T[s] ← tombstone
  9. 9if T[s] = k: (insert) duplicate — reject
  10. 10otherwise collision → next i
  11. 11no slot found → fail
  12. 12end

C implementation

hash_functions.ctested ✓ 160/160 cases
C
/*
 * Hash functions for keys 0..99999 and table size m (2..31):
 *   division      h(k) = k mod m
 *   mid-square    take the middle r digits of k*k, then mod m
 *   folding       shift folding: split k into r-digit parts from the left, add, then mod m
 *   digit         digit analysis: pick chosen digit positions (1-based, key zero-padded to width w)
 * r = number of digits in (m - 1), i.e. how many digits an address needs.
 *
 * Input:  m method [w count p1 p2 ...]   (method: 1 division, 2 mid-square, 3 folding, 4 digit;
 *                                         w/count/positions only for method 4)
 *         then one key per line until end of input.
 * Output: "HASH key home" for every key.
 */
#include <stdio.h>
#include <string.h>

static int num_digits(long long x) {
    int d = 1;
    while (x >= 10) { x /= 10; d++; }
    return d;
}

static long long parse_digits(const char *s, int from, int len) {
    long long v = 0;
    for (int i = from; i < from + len; i++) v = v * 10 + (s[i] - '0');
    return v;
}

static int division(long k, int m) { return (int)(k % m); }

static int mid_square(long k, int m) {
    int r = num_digits(m - 1);
    char s[32];
    long long sq = (long long)k * k;
    int len = snprintf(s, sizeof s, "%lld", sq);
    if (len <= r) return (int)(sq % m);              /* square is short: use all of it */
    int start = (len - r) / 2;                        /* middle r digits */
    return (int)(parse_digits(s, start, r) % m);
}

static int folding(long k, int m) {
    int r = num_digits(m - 1);
    char s[32];
    int len = snprintf(s, sizeof s, "%ld", k);
    long long sum = 0;
    for (int i = 0; i < len; i += r) {
        int part = (i + r <= len) ? r : len - i;     /* last part may be shorter */
        sum += parse_digits(s, i, part);
    }
    return (int)(sum % m);
}

static int digit_analysis(long k, int m, int width, const int *pos, int count) {
    char s[32];
    snprintf(s, sizeof s, "%0*ld", width, k);         /* left-pad with zeros */
    long long v = 0;
    for (int i = 0; i < count; i++) v = v * 10 + (s[pos[i] - 1] - '0');
    return (int)(v % m);
}

int main(void) {
    int m, method, width = 0, count = 0, pos[8];
    if (scanf("%d %d", &m, &method) != 2 || m < 2 || m > 31 || method < 1 || method > 4) return 1;
    if (method == 4) {
        if (scanf("%d %d", &width, &count) != 2 || width < 1 || width > 10 || count < 1 || count > 8) return 1;
        for (int i = 0; i < count; i++)
            if (scanf("%d", &pos[i]) != 1 || pos[i] < 1 || pos[i] > width) return 1;
    }
    long k;
    while (scanf("%ld", &k) == 1) {
        if (k < 0 || k > 99999) return 1;
        if (method == 4 && num_digits(k) > width) return 1;
        int h = method == 1 ? division(k, m)
              : method == 2 ? mid_square(k, m)
              : method == 3 ? folding(k, m)
              : digit_analysis(k, m, width, pos, count);
        printf("HASH %ld %d\n", k, h);
    }
    return 0;
}
Sample run · division method, m = 11 · real output from gcc

Input (stdin)

11 1
72
13
36

Output (stdout)

HASH 72 6
HASH 13 2
HASH 36 3

Open in the Code Lab →

Common mistakes

  • Taking mid-square digits from the key instead of its square.
  • Forgetting the final mod m when the extracted value exceeds the table size.
  • Choosing m = 10 or 100 with division for keys ending in similar digits.

Asked in KTU exams (4)

Quick check — can you get them all?

Question 1

Q1.Division method, m = 11: h(43) = ?

Question 2

Q2.Shift folding of 123456789 into 3-digit parts (address = sum)?

Question 3

Q3.Why choose a prime table size for the division method?

Practice

Every visualizer has a Practice mode: predict the next state before the animation reveals it. You can also work through the topic's question set on the practice page.

Exam-ready summary

  • Division: k mod m (m prime).
  • Mid-square: middle r digits of k².
  • Folding: add r-digit parts (shift/boundary).
  • Digit analysis: keep the well-distributed digit positions of a known key set.

References

  • Horowitz, Sahni & Anderson-Freed, Fundamentals of Data Structures in C, 2/e — Ch. 7 (Sorting), Ch. 8 (Hashing) §8.2
  • Cormen, Leiserson, Rivest & Stein, Introduction to Algorithms, 3/e — Ch. 2, 6, 7, 8, 11 §11.3

Explanations on this page are original. Textbook references point to where the standard treatment can be read; no text is reproduced from them.

Prefer revising from notes? Module-wise notes and question papers on Azhimathi Mayam (opens in a new tab)