(You might also see them called HashMaps, Maps or Dictionaries)
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++)
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 iWhat 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)]Used to store pairs of values and access the values very quickly no matter how many there are
| 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
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
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++:
https://leetcode.com/problems/contains-duplicate/
https://leetcode.com/problems/matchsticks-to-square