Golang program to implement a hash table with linear probing


Hash tables are efficient data structures used to store key-value pairs, making them essential for various applications. Linear probing is a collision resolution technique that helps handle situations when two keys map to the same index in the hash table. In this article, we will explore the implementation of a Hash Table with Linear Probing in Golang, using arrays and maps, gaining insights into their workings and practical applications. In the below examples we are going to perform insertion and retrieval operations using a hash mechanism and collision resolution strategy.

Explanation

In the below example, keys [10 , 25, 40 , 31 , 70 ] are inserted at their hashed indexes. Whenever a collision occur the the linear probing involves placing the element in the next emty index.

Index:   0    1    2    3    4    5    6    7
Key:    [10] [25] [ ]  [40] [ ]  [31] [ ]  [70]

Algorithm

  • Initialise the Hash Table − Create a new struct type HashTable with a slice named table of type Entry. This slice will store the key-value pairs in the hash table.

  • Create the Hash Function − Implement a hash function that takes a key as input and returns an integer representing the hash value. The hash function should distribute keys uniformly across the hash table to minimise collisions.

  • Insertion Operation − Insert the key-value pair into the first available empty slot.

  • Lookup Operation − Calculate the hash value using the hash function.

  • Deletion Operation − Calculate the hash value using the hash function.

  • Resizing the Hash Table − Monitor the load factor (the ratio of the number of elements to the number of slots) to avoid excessive collisions.

Syntax

type HashTable struct{ table []Entry }

The syntax implements a hash table with linear probing using a custom struct type. We define a struct named HashTable, representing the hash table, and declare a slice named table to store the entries in the hash table.

type HashTable map[int]Entry

The syntax implements a hash table with linear probing using the built-in map type in Golang. We define a custom type named HashTable, which is essentially a map with integer keys and Entry values. The Entry struct represents a key-value pair.

insert(key int, value interface{}) 

The syntax insert is used to add a new key-value pair to a data structure, where key is an integer representing the unique identifier of the value, and value is the data to be stored associated with that key.

Example 1

In this example, we will implement a hash table with linear probing in go. We will define a struct HashTableLinear that contains two arrays keys and values to store the key-value pairs. We will provide methods to insert and retrieve elements from the hash table.

package main

import (
	"fmt"
)

const hashTableSize = 10

type HashTableLinear struct {
	keys   [hashTableSize]int
	values [hashTableSize]interface{}
	size   int
}

func hashFunction(key int) int {
	return key % hashTableSize
}

func (ht *HashTableLinear) insert(key int, value interface{}) {
	index := hashFunction(key)

	for ht.keys[index] != 0 {
		index = (index + 1) % hashTableSize
	}

	ht.keys[index] = key
	ht.values[index] = value
	ht.size++
}

func (ht *HashTableLinear) get(key int) interface{} {
	index := hashFunction(key)

	for ht.keys[index] != key {
		index = (index + 1) % hashTableSize
	}

	return ht.values[index]
}

func main() {
	ht := HashTableLinear{}

	ht.insert(101, "Alice")
	ht.insert(205, "Bob")
	ht.insert(306, "John")
	ht.insert(401, "Sarah")
	ht.insert(502, "Michael")

	fmt.Println("Name for key 205:", ht.get(205))
	fmt.Println("Name for key 401:", ht.get(401))
	fmt.Println("Name for key 306:", ht.get(306))
}

Output

Name for key 205: Bob
Name for key 401: Sarah
Name for key 306: John

Example 2

In this example, we will implement hash table with linear probing in go using maps in Go. Linear probing is a collision resolution technique where, if a collision occurs during insertion, the algorithm searches for the next available slot in the hash table sequentially until it finds an empty slot. We will use a map data structure in Go to simulate the hash table.

package main

import (
	"fmt"
)

func main() {
	hashTable := make(map[int]string)

	hashTable[1] = "One"
	hashTable[2] = "Two"
	hashTable[3] = "Three"
	hashTable[4] = "Four"

	fmt.Println("Value for key 1:", hashTable[1])
	fmt.Println("Value for key 3:", hashTable[3])

	if value, exists := hashTable[2]; exists {
		fmt.Println("Key 2 exists with value:", value)
	} else {
		fmt.Println("Key 2 does not exist in the hash table.")
	}

	delete(hashTable, 4)

	if _, exists := hashTable[4]; exists {
		fmt.Println("Key 4 still exists in the hash table.")
	} else {
		fmt.Println("Key 4 is successfully removed from the hash table.")
	}
}

Output

Value for key 1: One
Value for key 3: Three
Key 2 exists with value: Two
Key 4 is successfully removed from the hash table.

Real-life implementations

Student Information System

Consider a student information system for a school or university that needs to manage student records efficiently. A hash table with linear probing can help store and retrieve student information quickly.

Online Shopping Cart

Imagine you're building an e-commerce website, and one of the crucial components is the shopping cart. Users add products to their cart while browsing and shopping. To efficiently manage the items in the shopping cart, a Hash Table with Linear Probing could be a great solution.

Conclusion

Hash tables, revered for their ability to efficiently store and retrieve key-value pairs, are the cornerstone of countless applications. In this article we have looked at how we can write a program that illustrates implementation of a Hash Table with Linear Probing in go using two methods: one with arrays and another with maps. The first method uses arrays to store key-value pairs and handles collisions using linear probing technique. The second method utilises Golang's built-in map data structure, which internally implements a hash table with linear probing. These implementations provide efficient ways to store and retrieve key-value pairs, making hash tables an essential data structure for various applications.

Updated on: 05-Sep-2023

245 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements