Learn Hash Tables in 13 minutes #️⃣

Bro Code
20 Oct 202113:26

Summary

TLDRCe script vidéo explique les hash tables comme une collection de paires clé-valeur. Il montre comment les clés sont transformées en codes de hachage grâce à une formule, et comment ces codes sont utilisés pour stocker les données dans un tableau de hachage de taille limitée. Le script aborde également les collisions et leur résolution par chaînage, ainsi que l'importance de la taille du tableau de hachage pour la performance. Enfin, il illustre la mise en œuvre d'un tableau de hachage en Java avec des exemples concrets.

Takeaways

  • 🔑 Un tableau de hachage (hash table) est une collection de paires clé-valeur.
  • 👨‍🏫 Dans l'exemple donné, les clés sont des identifiants uniques des étudiants et les valeurs sont leurs noms.
  • 🔢 La méthode `hashCode` prend une clé en entrée et renvoie un entier appelé hach (hash).
  • 📏 Pour un entier, le hach est simplement le nombre lui-même.
  • 🗄️ Le hach est ensuite utilisé pour déterminer l'index où placer la paire clé-valeur dans le tableau de hachage.
  • 🔄 En cas de collision (deux clés ayant le même hach), on utilise une liste chaînée pour gérer les entrées dans le même compartiment (bucket).
  • 🔄 La résolution la plus courante d'une collision est de transformer chaque compartiment en liste chaînée.
  • 📚 Le script illustre comment gérer les collisions avec des exemples concrets.
  • 💾 Le tableau de hachage peut être dynamiquement agrandi pour accueillir plus d'éléments.
  • 🔍 La recherche dans un tableau de hachage est rapide, mais les collisions peuvent ralentir le processus.
  • 📉 L'efficacité d'un tableau de hachage dépend de la taille du tableau et du nombre de collisions.

Q & A

  • Qu'est-ce qu'un tableau de hachage (hash table) ?

    -Un tableau de hachage est une collection d'appaires clé-valeur. Chaque appairage est appelé une entrée, avec une clé et une valeur associée.

  • Comment se fait-il le hachage d'un entier en Java ?

    -En Java, le hachage d'un entier est très simple, car la formule est le nombre lui-même. Par exemple, le hach de 100 est 100 et le hach de 123 est 123.

  • Que signifie 'collision' dans un tableau de hachage ?

    -Une 'collision' se produit lorsqu'un hachage calculé donne la même valeur pour deux clés différentes.

  • Comment est résolue une collision dans un tableau de hachage ?

    -La résolution la plus courante d'une collision est de transformer chaque compartiment, ou 'bucket', en une liste chaînée. Si un compartiment contient déjà une entrée, on y ajoute l'adresse de la prochaine entrée.

  • Quel est le but de la méthode 'put' dans un tableau de hachage ?

    -La méthode 'put' sert à ajouter une nouvelle entrée, ou à mettre à jour une entrée existante, dans le tableau de hachage en utilisant une clé spécifique.

  • Comment se fait-il le hachage d'une chaîne de caractères ?

    -Le hachage d'une chaîne de caractères utilise une formule différente qui prend la valeur ASCII de chaque caractère dans la chaîne et l'intègre dans la formule.

  • Quelle est la méthode utilisée pour accéder aux valeurs dans un tableau de hachage ?

    -La méthode 'get' est utilisée pour accéder aux valeurs dans un tableau de hachage en passant la clé correspondante.

  • Comment est-il possible de supprimer une entrée dans un tableau de hachage ?

    -La méthode 'remove' permet de supprimer une entrée en utilisant la clé associée à cette entrée.

  • Quelle est la complexité temporelle d'un tableau de hachage en cas d'absence de collision ?

    -En l'absence de collision, la meilleure complexité temporelle d'un tableau de hachage est O(1), ce qui signifie qu'il fonctionne en temps constant.

  • Comment peut-on réduire le nombre de collisions dans un tableau de hachage ?

    -On peut réduire le nombre de collisions en augmentant la taille du tableau de hachage, ce qui permet de répartir les entrées de manière plus efficace.

Outlines

00:00

📚 Introduction aux tableaux de hachage

Le premier paragraphe introduit les tableaux de hachage comme une collection de paires clé-valeur, où chaque clé est unique et associée à une valeur. On explique comment les enseignants peuvent utiliser ces tableaux pour associer des identifiants d'étudiants à leurs noms. Le processus de hachage est décrit, où chaque clé est transformée en un entier appelé 'hach' grâce à une formule. Dans le cas des entiers, le hach est simplement l'entier lui-même. Ensuite, on explique comment les hachs sont répartis dans le tableau de hachage en utilisant le modulo de la taille du tableau pour obtenir l'index. On mentionne également les collisions qui se produisent lorsqu'au moins deux clés donnent le même hach et on explique comment gérer ces collisions en utilisant des listes chaînées.

05:01

💻 Implémentation d'un tableau de hachage en Java

Le deuxième paragraphe décrit comment implémenter un tableau de hachage en Java. On commence par déclarer le tableau de hachage et on définit les types de données des paires clé-valeur. On utilise les classes wrapper pour les types primitifs, comme Integer et String. On crée un tableau de hachage avec une capacité initiale et un facteur de charge. On utilise la méthode 'put' pour ajouter des éléments au tableau de hachage et la méthode 'get' pour y accéder. On explique également comment itérer sur les clés d'un tableau de hachage à l'aide d'une boucle for et comment utiliser la méthode 'remove' pour en supprimer. On illustre comment afficher les codes de hachage des clés et comment calculer les index correspondants dans le tableau de hachage.

10:03

🔍 Gestion des collisions et optimisation des tableaux de hachage

Le troisième paragraphe traite de la gestion des collisions et des stratégies pour optimiser les tableaux de hachage. On explique que les collisions peuvent être réduites en augmentant la taille du tableau de hachage, ce qui consomme plus de mémoire. On montre comment le hachage fonctionne pour les chaînes de caractères en utilisant la valeur ASCII de chaque caractère. On calcule les nouveaux hachs pour chaque clé et on détermine l'index où chaque entrée sera placée en utilisant le modulo de la taille du tableau de hachage. On illustre comment les collisions peuvent être évitées en augmentant la taille du tableau et on explique comment le temps d'exécution d'un tableau de hachage varie en fonction du nombre de collisions. On conclut en soulignant que les tableaux de hachage sont un excellent moyen de stocker des paires clé-valeur avec une insertion, une recherche et une suppression rapides, surtout pour les grands ensembles de données.

Mindmap

Keywords

💡Table de hachage

La table de hachage est une structure de données qui stocke des paires clé-valeur. Chaque clé est unique et permet de retrouver rapidement la valeur associée. Dans le script, l'exemple donné est celui d'un enseignant qui crée une table de hachage pour associer des identifiants uniques à des noms d'étudiants. La table de hachage est efficace pour de grands ensembles de données et offre des performances rapides pour l'insertion, la recherche et la suppression de paires clé-valeur.

💡Paire clé-valeur

Dans le contexte d'une table de hachage, une 'paire clé-valeur' fait référence à la relation entre un identifiant unique (la clé) et la donnée correspondante (la valeur). Par exemple, dans le script, la clé pourrait être un numéro d'étudiant et la valeur associée le nom de l'étudiant. Cette paire permet de structurer et d'accéder efficacement aux données.

💡Hachage

L'hachage est le processus par lequel une clé est transformée en une valeur numérique, appelée 'hach', grâce à une formule spécifique. Dans le script, l'hachage d'un entier est simplement le nombre lui-même. Cet hach est ensuite utilisé pour déterminer l'emplacement de la paire clé-valeur dans la table de hachage.

💡Collision

Une 'collision' se produit lorsqu'au moins deux clés donnent lieu au même hach. Dans le script, cela est illustré par l'exemple où deux chaînes de caractères différentes donnent lieu au même hach après application de la formule d'hachage. Pour gérer les collisions, on utilise souvent une technique appelée 'chaînage' où les entrées ayant le même hach sont stockées dans une liste chaînée.

💡Chaînage

Le 'chaînage' est une méthode utilisée pour résoudre les collisions dans les tables de hachage. Si plusieurs paires clé-valeur ont le même hach, elles sont stockées dans une liste chaînée à l'index correspondant au hach. Dans le script, cela est mentionné comme une solution pour gérer les collisions, permettant ainsi de stocker plusieurs entrées à la même position.

💡Modulo

Le 'modulo' est une opération mathématique utilisée pour déterminer l'index dans lequel une paire clé-valeur sera stockée dans la table de hachage. Dans le script, on utilise le modulo pour obtenir le reste de la division du hach par la taille de la table de hachage, ce qui donne l'index de stockage. Par exemple, si le hach est 123 et que la taille de la table est 10, 123 modulo 10 donne 3, qui est l'index de stockage.

💡Chargement

Le 'chargement' d'une table de hachage est le rapport entre le nombre d'entrées stockées et la taille totale de la table. Dans le script, il est mentionné que la table de hachage en Java a un facteur de chargement de 0.75 par défaut, ce qui signifie que la table se réorganise quand 75% de ses emplacements sont occupés pour accueillir plus d'entrées.

💡Complexité en temps d'exécution

La 'complexité en temps d'exécution' d'une table de hachage indique la vitesse à laquelle les opérations telles que l'insertion, la recherche ou la suppression peuvent être effectuées. Dans le script, il est expliqué que sans collision, la complexité est de l'ordre de O(1), c'est-à-dire constante et très rapide. En cas de collisions fréquentes, la complexité peut devenir de l'ordre de O(n), où n est le nombre d'entrées, ce qui signifie que les opérations peuvent devenir plus lentes.

💡Balise

Dans le script, la 'balise' est utilisée pour identifier les étapes importantes de la création et de la manipulation d'une table de hachage. Par exemple, 'table.put' est utilisé pour ajouter une entrée, 'table.get' pour récupérer une valeur associée à une clé, et 'table.remove' pour supprimer une entrée. Ces balises sont essentielles pour comprendre les opérations que l'on peut effectuer sur une table de hachage.

💡Formule d'hachage

La 'formule d'hachage' est un algorithme utilisé pour convertir une clé en un hach. Dans le script, il est expliqué que les entiers sont hachés en étant traités comme des valeurs numériques, tandis que les chaînes de caractères nécessitent une formule différente qui prend en compte la valeur ASCII de chaque caractère. Cette formule permet de calculer le hach qui sera utilisé pour déterminer l'index de stockage de la paire clé-valeur.

Highlights

Hash table is a collection of key-value pairs.

Each key-value pair is known as an entry.

Keys can be of any data type.

Hashcode method converts a key into an integer called a hash.

For integers, the hash is the number itself.

Hashes are reduced to fit the hash table's size using modulus.

The remainder from modulus operation is used as an index.

Collision occurs when two keys have the same hash.

Collisions are resolved by turning each bucket into a linked list.

Hash table lookup involves finding the index and then searching the bucket.

Efficiency of hash table is inversely proportional to the number of collisions.

The size of the hash table can be increased to reduce collisions.

Hash table has fast insertion, lookup, and deletion.

Hash table is not ideal for small data sets due to overhead.

Hash table runtime complexity varies from O(1) to O(n).

Hash table's efficiency is maximized with a balance between size and collisions.

Transcripts

play00:02

all right what's going on everybody hash

play00:04

tables a hash table is a collection of

play00:07

key value pairs each key value pair is

play00:10

known as an entry we have two pieces of

play00:13

data the first is the key and the second

play00:16

is the value in this example let's

play00:18

pretend that we're a teacher and we need

play00:20

to create a hash table of all of our

play00:22

students each student has a name and a

play00:25

unique student id number but these can

play00:28

be of any data type that you would like

play00:30

in this example the key will be an

play00:32

integer and the value will be a string

play00:34

so how do we know at which index to

play00:36

place each of these entries well what we

play00:39

could do is take each key and insert it

play00:42

into a hashcode method the hashcode

play00:44

method will take a key as input plug it

play00:47

into a formula and spit out an integer

play00:50

this integer is known as a hash now if

play00:52

we're finding the hashcode of an integer

play00:55

in java that's actually really easy the

play00:57

formula is the number itself so the hash

play01:00

of 100 is 100 123 is 123. so on and so

play01:05

forth with the other keys so after

play01:08

finding the hash of your key now what

play01:10

can we do these numbers are way too

play01:12

large and the size of our hash table is

play01:15

only 10 elements what we'll do next is

play01:17

take each of these hashes and divide

play01:20

each of them by the capacity the size of

play01:23

our hash table we have 10 elements so

play01:26

take each hash divided by the capacity

play01:29

of our hash table whatever the remainder

play01:31

is we will use the remainder as an index

play01:35

and to find that we will use the modulus

play01:37

operator so 100 divides by 10 evenly the

play01:41

remainder is zero so 100 modulus 10

play01:45

gives us a remainder of zero so

play01:47

spongebob's entry we will place at index

play01:51

0 within our hash table so the hash of

play01:54

patrick's key is 123. 123 modulus 10

play01:58

gives us a remainder of 3. patrick's

play02:01

entry will be inserted at index 3 of our

play02:04

hash table so here's a little shortcut

play02:06

if you have a number modulus 10 you

play02:09

could find the remainder and that is the

play02:10

last digit 321 modulus 10 will give us a

play02:14

remainder of 1. sandy's entry will be

play02:17

placed at index 1. then squidward's

play02:19

entry will be placed at index 5.

play02:23

555 modulus 10 is 5 and gary's will be

play02:27

at index 7 following the same pattern

play02:29

now here's one situation what if two

play02:32

hashes are calculated to be the same

play02:34

value that is known as a collision and i

play02:37

can best demonstrate that with a

play02:39

separate example

play02:40

in this next example let's say that each

play02:43

key is now a string each entry is a pair

play02:46

of strings we will first need to find

play02:49

the hash of each of these keys

play02:51

so the hash code of a string uses a

play02:54

different formula basically speaking

play02:56

we're going to take the ascii value of

play02:59

each character within the string and

play03:01

plug it into this formula i went ahead

play03:03

and calculated the hash of each of these

play03:06

strings using this formula of the string

play03:09

hashcode method and the next steps are

play03:11

the same as before take each hash

play03:13

divided by the capacity of our hash

play03:16

table and find the remainder so

play03:18

beginning with the first hash

play03:21

48625 modulus 10 gives us a remainder of

play03:25

5 spongebob's entry is now at index 5

play03:29

within our hash table

play03:31

now patrick's will be at index zero now

play03:34

here's sandy's sandy's will also be zero

play03:38

we have a collision both of these

play03:40

entries will be located at the same

play03:42

index so what do we do each of these

play03:45

storage locations is also known as a

play03:47

bucket and the most common resolution

play03:50

for a collision in a hash table is that

play03:53

we will turn each bucket into a linked

play03:55

list if this bucket already has an entry

play03:58

within the first entry we will also add

play04:01

an address to the location of the next

play04:04

entry and keep on adding more if there's

play04:07

more entries within this bucket so in

play04:10

this way this becomes a linked list if

play04:12

we're looking up a key we first go to

play04:14

the index in which it's located if

play04:17

there's more than one entry we will

play04:19

search linearly through this bucket as

play04:21

if it were a linked list until we find

play04:24

the key that we're looking for so that's

play04:26

the most common resolution when there is

play04:28

a collision but ideally you would want

play04:31

each of these entries to be within their

play04:32

own bucket based on the hash of

play04:35

squidward's key squidward's entry has an

play04:38

index of nine and gary gary has an index

play04:41

of five and there's another collision we

play04:44

will add the address of gary's location

play04:47

to the first entry and this bucket

play04:49

becomes a separate linked list this

play04:51

process is known as chaining the less

play04:54

collisions that there are the more

play04:56

efficient that this hash table is going

play04:58

to look up a value ideally you would

play05:00

want each entry to have their own bucket

play05:03

but collisions are possible to reduce

play05:05

the number of collisions you can

play05:07

increase the size of the hash table but

play05:09

then again the hash table is going to

play05:11

use up more memory then so people

play05:12

usually find a balance between the two

play05:15

so yeah those are hash tables in theory

play05:17

let's create our own now all right

play05:19

everybody so let's implement a hash

play05:21

table in java so we will need to declare

play05:24

this hash table and list the data types

play05:27

of our key value pairs if we need to

play05:29

store primitive data types we can use

play05:31

the appropriate wrapper class so let's

play05:33

store integers and strings

play05:36

integer and string the integers will be

play05:39

the key is the strings will be the

play05:41

values we'll map student id numbers and

play05:44

student names and i'll name this hash

play05:46

table just simply table

play05:48

equals new

play05:50

hash table

play05:53

there we go so in java when we create a

play05:56

hash table these have an initial

play05:58

capacity of 11 elements and a load

play06:00

factor of 0.75 so once 75 of our

play06:04

elements are filled this hash table will

play06:07

dynamically expand to accommodate more

play06:09

elements now you can set a different

play06:11

capacity for your hash table instead of

play06:13

11 let's say 10 to be consistent with

play06:16

our example in the previous part of this

play06:17

lesson and if you would like to change

play06:19

the load factor you can add that as well

play06:21

instead of 75 let's say 50

play06:24

so we would pass in a floating point

play06:26

number

play06:27

so 0.5 then add an f at the end for

play06:30

floating point numbers but in this

play06:32

example let's just keep the load factor

play06:34

consistent so let's start adding some

play06:36

key value pairs to add an element to

play06:38

your hash table use the put method so

play06:41

table dot put and then we will pass in

play06:45

an integer as the key and a string as

play06:48

the value so our first student is

play06:50

spongebob he has a student id of let's

play06:53

say 100

play06:54

and let's pass in a string for the value

play06:57

spongebob

play06:58

okay that is our first student so let's

play07:00

add a couple more from the previous

play07:02

example

play07:03

so we have spongebob

play07:05

patrick with an id of one two three

play07:08

sandy with an id of three two one

play07:11

squidward with an id of five five five

play07:16

and gary with an id of 777

play07:20

now to access one of these values you

play07:22

can use the get method of tables

play07:25

so i'll display this within a print line

play07:26

statement

play07:28

table dot get and i will pass in a key

play07:31

let's get the value at key number 100 so

play07:34

this student is spongebob how can we

play07:37

display all of the key value pairs of a

play07:39

table well we could use a for loop

play07:42

so i'm going to create a for loop

play07:45

and place this within it

play07:48

so to iterate over the keys of our table

play07:51

this is what we can write we can use an

play07:53

enhanced for loop so we are iterating

play07:55

over integers

play07:57

so the data type is integer

play07:59

key

play08:01

colon so to make our hash table iterable

play08:03

we can get all of the keys from our

play08:05

table and put them within a set a set is

play08:08

iterable

play08:09

so we will iterate over table dot key

play08:13

set method

play08:14

this will take all of our keys and

play08:16

return a set and a set is something we

play08:18

can iterate over and within our print

play08:20

line statement let's print each key

play08:23

key

play08:24

plus

play08:25

then maybe i'll add a tab to separate

play08:27

these

play08:28

plus

play08:29

table

play08:30

dot get

play08:32

then pass in whatever our key is okay so

play08:35

after running this

play08:37

this will display all of our key value

play08:39

pairs and if you need to remove an entry

play08:42

well there's a remove method table dot

play08:45

remove then pass in a key let's remove

play08:48

gary so remove the entry with this key

play08:51

777

play08:52

and gary is no longer within our table

play08:55

but we'll keep them in i'll turn this

play08:56

line into a comment now just to get a

play08:58

better understanding of where these key

play09:00

value pairs are being placed let's also

play09:03

display each hash code for each of these

play09:05

elements

play09:06

so preceding our key let's display each

play09:08

hash code i'll precede our key with a

play09:11

tab

play09:15

and let's display each key's hash code

play09:18

key dot hashcode method if we're using

play09:22

the hash code of integers this will

play09:24

return the primitive integer value

play09:27

represented by the key that we're

play09:29

passing in if we're using the hashcode

play09:31

method of integers well the hash is

play09:34

going to end up being the same integer

play09:35

so you can see that these numbers are

play09:37

the same to calculate an index we can

play09:39

follow the hash with modulus operator

play09:42

then the size of our table

play09:44

we set this to originally be 10.

play09:48

so we have gary at index seven squidward

play09:51

at index five patrick at three sandy at

play09:53

one spongebob at zero now if our data

play09:56

type was strings we would use a

play09:58

different hashing formula so let's

play10:00

change the data type to string and all

play10:02

of these keys are now strings

play10:07

then let's remove modulus 10

play10:10

and change the data type of our for loop

play10:12

to strings

play10:13

string key

play10:16

okay these are the new hashes for each

play10:18

of our keys

play10:19

this key has this hash number this key

play10:22

has this hash number so on and so forth

play10:25

so different data types will have

play10:26

different hash code formulas now let's

play10:29

calculate the element in which each of

play10:31

these entries is going to be placed by

play10:33

adding modulus the size of our hash

play10:35

table 10.

play10:39

so here are the elements and we actually

play10:40

have two collisions we have a collision

play10:43

with these two keys they're both within

play10:45

bucket five as well as these two entries

play10:48

so both of these will be placed into

play10:49

bucket zero since there's more than one

play10:52

entry within the same element we will

play10:54

treat this bucket as a linked list and

play10:56

just iterate over it linearly until we

play10:58

reach the key that we're looking for

play11:00

now one way in which we can avoid

play11:01

collisions is to increase the size of

play11:04

our hash table if we set this to the

play11:06

default of 11 and change this to modulus

play11:09

11 well then these will be placed within

play11:11

different buckets and you can see that

play11:13

they changed however we still have a

play11:15

collision with spongebob and squidward

play11:18

so what if we increase this to 21.

play11:20

do we have any collisions then

play11:23

nope we do not these keys are within

play11:25

their own buckets

play11:27

all right everybody so in conclusion a

play11:29

hash table is a data structure that

play11:32

stores unique keys to values when you

play11:35

declare a hash table you state the data

play11:37

types of what you're storing and these

play11:40

are reference data types each key value

play11:42

pair is known as an entry and a benefit

play11:45

of hash tables is that they have a fast

play11:48

insertion lookup and deletion of key

play11:51

value pairs but they're not ideal for

play11:53

small data sets since there's a lot of

play11:55

overhead but they're great with large

play11:57

data sets hashing in the context of a

play12:00

hash table takes a key and computes an

play12:03

integer it utilizes a formula which will

play12:06

vary based on the key as input and its

play12:08

data type then to calculate an index we

play12:11

follow this formula we take a hash

play12:13

modulus the capacity of our table to

play12:17

calculate an index each index is also

play12:20

known as a bucket it's an indexed

play12:22

storage location for one or more entries

play12:25

they can store more than one entry in

play12:27

the case of a collision and in case that

play12:29

happens we treat each bucket as a linked

play12:31

list each entry knows where the next

play12:34

entry is located and as we discussed a

play12:36

collision is when a hash function

play12:38

generates the same index for more than

play12:40

one key less collisions equals more

play12:43

efficiency and the runtime complexity of

play12:45

a hash table varies if there are no

play12:48

collisions the best case would be a

play12:50

runtime complexity of big o of one it

play12:53

runs in constant time in case there are

play12:55

exclusively collisions as in we place

play12:58

all of our entries within the same

play13:00

bucket it's going to be one giant linked

play13:02

list and the runtime complexity of a

play13:04

linked list is big o of n it runs in

play13:07

linear time on average the runtime

play13:09

complexity of a hash table will be

play13:12

somewhere within this range so yeah

play13:14

everybody those are hash tables if you

play13:16

would like a copy of all my notes here

play13:18

i'll post them in the comments section

play13:19

down below and well yeah those are hash

play13:22

tables in computer science

Rate This

5.0 / 5 (0 votes)

Étiquettes Connexes
Hash TablesData StructuresJava ProgrammingKey-Value PairsCollision HandlingData StorageAlgorithmsComputer ScienceData ManagementEfficiency