HashTables

(You might also see them called HashMaps, Maps or Dictionaries)

Arrays/Lists

These are collections of elements which are available in most programming languages in some form

(Lists in Python, Arrays/ArrayLists in Java, Arrays/Vectors in C++)

Find the number 5

How many elements do you need to check?

8 2 3 16 11 14 5 1 7 10
def find(elems, val):
    for i in range(len(elems)):
        if elems[i] == val:
            return i

What if the value of a number was used to determine its position?

What is being used to determine the position of elements here?

10 12 14 5 16 9
def find(elems, val);
    return elems[val%len(elems)]

HashTables

Used to store pairs of values and access the values very quickly no matter how many there are

Example

a c d a d b b a e e

An array of characters

a 3
b 3
c 1
d 2
e 2

A HashTable of characters to amount in the array

Key

Value

Whats the point?

Much faster to access compared to checking every element in an array

Problems like Two Sum can be solved far faster than they can with the simple solution

Code Example

Python:

(HashTables in Python are called dictionaries)

def HashMapExample():
    map = {}
    map['a'] = 10
    map['b'] = 7
    map['r'] = 2
    
    print(map['a']) #prints 10
    print(map['b']) #prints 7
    
int main ()
{
     std::map<char,int> map;

     map['a']=10;
     map['b']=30;
     map['c']=50;
     map['d']=70;

     cout << map['a']; //prints 10
     cout << map['b']; //prints 30


}

C++:

Practice #1

https://leetcode.com/problems/contains-duplicate/

Practice #2

https://leetcode.com/problems/matchsticks-to-square

HashTables

By theasocialmatzah

HashTables

  • 159