Hash Collections and Sets

19. Hash Collections and Sets#

A warehouse and a sales department each submit a list of product IDs, and a manager wants to know which IDs appear in only one list. A service desk wants the owner of ticket T-100 without scanning every ticket. Both requests are answered by hashing: turning a key into a storage position so that lookup, membership, and set comparison do not depend on the number of records. This chapter explains how C#’s Dictionary and HashSet do that work, what can go wrong when keys collide or change, and how to choose and coordinate collections for a whole workload. It builds on the collection families of Chapter 8 and the equality and comparer contracts of Chapter 13.

  • Hash code and bucket: A key’s hash code is mapped into one of m buckets. Equal keys must have equal hash codes, but equal hash codes do not mean the keys are equal.

  • Collision handling: Separate chaining keeps colliding entries in a list at the bucket; open addressing probes nearby slots and needs tombstones so deletion does not hide later entries.

  • Load factor and rehashing: The ratio of entries to buckets governs chain length. Growing the table requires recomputing every entry’s bucket, not copying old positions.

  • Sets and reconciliation: Union, intersection, and directional difference answer which IDs are shared, missing, or extra. A frequency dictionary is needed when duplicates matter.

  • Coordinated indexes: A dictionary and a priority queue can serve one workload only if updates keep them consistent, for example by lazy deletion with a version check.

Section 19.1 states dictionary contracts and equality policy, maps hash codes to buckets, implements a complete chained TicketMap, resizes it by rehashing, and contrasts open addressing with tombstones. Section 19.2 applies HashSet and frequency counts to business reconciliation, with attention to mutating set operations and keys that must keep their meaning. Section 19.3 matches structures to a service-desk workload, counts comparisons before timing anything, and dispatches from a dictionary and a priority queue with lazy deletion. Chapter 20 then uses these collections to represent and traverse graphs.

Chapter Video

Introduction to Hash Tables and Dictionaries (Data Structures & Algorithms #13) (18:39) by CS Dojo.

Hosted on YouTube; property of its original creator, embedded here for educational reference only.

Focus on the relationship between dictionary behavior, hash functions, and collision resolution. The sections supply the C# implementations and equality policies.

Learning Objectives

By the end of this chapter, you will be able to:

  1. Explain how a dictionary turns a key into a bucket in two steps, hash code and then bucket mapping, and why equal keys must have equal hash codes while equal hash codes do not imply equal keys.

  2. Choose one equality policy, such as ordinal case-insensitive comparison, apply it to every collection in a calculation, and use Add, indexer assignment, and TryGetValue according to their contracts.

  3. Trace separate chaining through insert, lookup, replace, and remove with colliding keys, and explain why linear probing needs a tombstone when an entry is deleted.

  4. Compute load factor, predict when the teaching map resizes, recompute bucket positions after rehashing, and state the expected O(1 + α) and worst-case O(n) costs of a chained lookup.

  5. Answer reconciliation questions with union, intersection, and directional difference on HashSet, preserving source sets when several answers are needed, and choose a frequency dictionary instead of a set when duplicates carry information.

  6. Select a structure for each operation in a service-desk workload, such as priority selection, lookup by ID, uniqueness, ordered reports, and arrival order, and justify the choice with operation counts rather than stopwatch timings.

  7. Coordinate a dictionary and a priority queue with lazy deletion and a version check so that cancelled or superseded tickets are never served.

Chapter Flow

Assignments contains the preview, connected lab, and homework.

Glossary

#

Term

Explanation

1

Hash function

A method that maps a key to an integer hash code used to choose a storage position.

2

Hash code

The integer a key’s hash function produces; it may be negative and is not a unique identifier.

3

Bucket

One of m storage positions in a hash table, chosen from a hash code.

4

Bucket mapping

Converting a hash code into an index from 0 through m - 1, here by reinterpreting it as unsigned before the remainder.

5

Collision

Two different keys choosing the same bucket.

6

Separate chaining

A collision strategy that stores all entries for a bucket in a small list, or chain.

7

Chain

The list of entries sharing one bucket; lookups compare actual keys along it.

8

Open addressing

A collision strategy that stores entries directly in the table and probes other slots when one is taken.

9

Linear probing

Trying the chosen slot, then the following slots with wraparound, until the key or a free slot is found.

10

Tombstone

A marker for a deleted slot in open addressing through which a lookup must keep probing.

11

Load factor

The number of entries divided by the number of buckets, written α = n / m.

12

Rehashing

Recomputing every entry’s bucket after the bucket count changes.

13

Expected cost

The average work under well-distributed hashes and bounded load, O(1 + α) for chaining.

14

Key equality policy

The rule that decides whether two keys match, supplied once as a comparer and used by every participating collection.

15

Ordinal comparison

String comparison by character code, with or without case folding, that ignores culture rules.

16

Hash and equality agreement

The contract that equal keys under the chosen policy must produce equal hash codes.

17

Immutable key

A key whose equality-determining fields never change while it is stored, so its bucket stays valid.

18

Dictionary

A collection that associates exactly one value with each distinct key.

19

Add

A dictionary method that inserts a new key and throws if the key already exists.

20

Indexer assignment

Writing dict[key] = value, which inserts a new key or replaces the existing value.

21

TryGetValue

A lookup that reports whether a key exists without treating a missing key as a stored default value.

22

Set

A collection of distinct keys that answers membership but not how many times a key was added.

23

HashSet

C#’s hash-based set; Add returns false when the key is already present.

24

Frequency dictionary

A dictionary from key to count, used when repeated submissions carry information.

25

Union

All keys that appear in either set.

26

Intersection

Only the keys that appear in both sets.

27

Set difference

Keys in the first set that are absent from the second; the direction changes the answer.

28

Reconciliation

Comparing two sources to report shared, missing, and extra IDs.

29

Enumeration order

The order a hash collection yields its items, which is not a sorting contract.

30

Index

A collection kept alongside the main records to answer one kind of question quickly.

31

Authoritative record

The collection, here the dictionary, whose contents decide whether an item is still active.

32

Lazy deletion

Leaving a stale queue entry in place and skipping it when it reaches the front.

33

Stale entry

A queue entry whose ticket was cancelled or changed after it was enqueued.

34

Version

A generation number stored with a record so an old queue entry for a reused ID can be recognized and skipped.

35

Workload

The set of operations an application needs, with their frequencies and update pattern.

36

Symmetric difference

Membership present in exactly one of two sets under the agreed equality policy.

Lecture Slides

Chapter 19 Slides