ADVANCED DATA STRUCTURES PROGRAM • LEVEL 18 — ADVANCED HASHING

Place Keys with Cuckoo Hashing

Learn how to place keys with cuckoo hashing using a clear C program.

AdvancedCollision resolutionHash-table design

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
A0:105 A1:50 A2:100 A4:67 A5:75 A6:20 B0:53

COMPLETE C PROGRAM

Complete C implementation

ads-cuckoo-hashing.c
Open in compiler
#include <stdio.h>

void insert(int a[],int b[],int key){int table=0;for(int move=0;move<20;move++){int slot=table?((key/7)%7):(key%7);int*target=table?b:a;if(!target[slot]){target[slot]=key;return;}int displaced=target[slot];target[slot]=key;key=displaced;table^=1;}}

int main(void)
{
    int first[7]={0},second[7]={0},keys[]={20,50,53,75,100,67,105};for(int i=0;i<7;i++)insert(first,second,keys[i]);
    for(int i=0;i<7;i++){if(first[i])printf("A%d:%d ",i,first[i]);}
    for(int i=0;i<7;i++){if(second[i])printf("B%d:%d ",i,second[i]);}
    putchar('\n');return 0;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

A0:105 A1:50 A2:100 A4:67 A5:75 A6:20 B0:53
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Evict a collision victim to its alternate table until an empty slot is found.
  3. Display the computed result.

Evict a collision victim to its alternate table until an empty slot is found.

EFFICIENCY

Time and space complexity

Time complexity

Expected O(1) lookup and insertion

Auxiliary space

O(table size)

DEBUGGING CHECKLIST

Common mistakes

Check this

Use the correct format specifier for every variable.

Check this

Initialize variables before using their values.

Check this

Check braces, semicolons and input order carefully.

Try it yourself

Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.