DEV Community

genichm
genichm

Posted on • Edited on

Prepare to Coding Interview > Know Data Structures > Hash Table

Hash table is a mapping between keys and values, each key can have several values, values can repeat, some implementations of the hash tables does not allow repeating values.

Adding value to the hash table

  1. Compute the hash code
  2. Map the hash code to the array index by hashCode % array.length
  3. Put the value to the index

Get the value from Has Table

  1. Compute the hash code
  2. Map the hash code to the array index by hashCode % array.length
  3. Go to the index and find the value if present

Base implementation with C# is below:

public class HashTableSimpleImplementation
{
    /*
        * Simple implementation of HashTable
    */
    private LinkedList<string>[] _hashTable;

    private int _hashTableSezie = 10;

    public HashTableSimpleImplementation()
    {
        _hashTable = new LinkedList<string>[_hashTableSezie];

        Init();
    }

    private void Init()
    {
        for(int i=0; i < _hashTable.Length; i++)
        {
            _hashTable[i] = new LinkedList<string>();
        }
    }

    /// <summary>
    /// Adding value to the hash table
    /// 1. Compute the hash code
    /// 2. Map the hash code to the array index by hashCode % array.length
    /// 3. Put the value to the index
    /// </summary>
    /// <param name="value"></param>
    public int Add(string value)
    {
        var index = GetIndex(value);

        _hashTable[index].AddLast(value);

        return index;
    }

    /// <summary>
    /// 1. Compute the hash code
    /// 2. Map the hash code to the array index by hashCode % array.length
    /// 3. Go to the index and find the value if present
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public string? Get(string value)
    {
        var index = GetIndex(value);

        var list = _hashTable[index];

        foreach(var item in list)
        {
            if (item.Equals(value))
            {
                return value;
            }
        }

        return null;
    }

    private int GetIndex(string value)
    {
        var hashCode = GetHashCode(value);

        var index = hashCode % _hashTableSezie;

        return index;
    }

    /// <summary>
    /// This implementation of hash code returns different code
    /// for the same string value on each run of the application
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    private int GetHashCode(string value)
    {
        var hashCode = value.GetHashCode();

        return hashCode > 0 ? hashCode : hashCode * -1;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)