Hash Tables, Heaps, and Priority Structures · Hashing

Hash Table

Hash tables support fast average-case lookup by turning keys into array positions and resolving collisions carefully.

Student Focus

We connect hash tables to everyday map and set use before discussing implementation internals.

Guided Lesson Notes

Understanding Hash Table

Hash Table focuses on fast lookup, priority selection, and the difference between average-case access and ordered removal. Hash tables support fast average-case lookup by turning keys into array positions and resolving collisions carefully.

The mental model is this: separate the key or priority from the stored value; the structure exists to answer one operation very quickly. That picture matters because it tells the student what information is available immediately and what must be searched, stored, or recomputed.

The core invariant is that a hash table must send equal keys to the same place, while a heap must keep every parent no worse than its children. If a solution cannot state that rule, the code may still run on a sample input but fail on edge cases.

A strong implementation usually uses maps, sets, counters, priority queues, comparators, heapify steps, and careful handling of collisions or ties. The goal is not just to memorize an API; the goal is to know why each operation is allowed and what it costs.

In competitive programming, Hash Table tends to appear when the problem asks for frequencies, duplicates, top-k values, smallest available item, repeated minimum merge, or dynamic priorities. Spotting that signal is often the difference between a nested-loop solution and an efficient one.

Visual Model

A small picture for Hash Table

Hash Table View

0: lime
1: empty
2: pear -> plum
3: apple

Heap View

2479121520

Key Ideas

  • Hash functions and equality
  • Collision strategies
  • Load factor and resizing

Practice Prompts

  • Build a frequency map for words in text.
  • Trace separate chaining after several insertions.

Vocabulary

Terms students should be able to say clearly

Key

The value used to find or group data in a hash table.

Collision

Two keys landing in the same hash-table location.

Load factor

How full a hash table is relative to its capacity.

Priority

The ordering rule used by a priority queue or heap.

Heap property

The parent-child ordering rule maintained by a heap.

Amortized cost

Average cost over many operations, including occasional expensive cleanup.

Worked Example

Worked example: tracing Hash Table

Use a tiny input and focus on hash functions and equality. The goal is to see how the topic changes state before scaling it to a full problem.

  1. 1Write a small input where Hash Table is clearly useful.
  2. 2Label the part of the input related to Hash functions and equality.
  3. 3Perform one operation and explain which invariant is still true afterward.
  4. 4Run a second operation that touches an edge case, such as an empty side, duplicate value, boundary index, disconnected vertex, or tie.
  5. 5Finish by saying which operation dominates the runtime and why.

Complexity Check

Costs students should be able to explain

OperationTypical CostReason
Hash lookupAverage O(1)Good hashing makes key lookup nearly constant on typical inputs.
Heap insert/removeO(log n)A heap restores its invariant along one root-to-leaf path.
Build from all valuesO(n) to O(n log n)The cost depends on whether heapify or repeated insertion is used.

Common Mistakes

What to watch while practicing

  • Coding before drawing the structure or state changes.
  • Forgetting the invariant that makes the algorithm correct.
  • Testing only the sample input and skipping boundary cases.
  • Giving Big-O without explaining which operation dominates the work.

Interview-Style Coding Problem

Hash Table interview problem: Longest Consecutive Sequence

Interview medium

Problem

Given an unsorted array, find the length of the longest run of consecutive integer values.

Input

The first line contains n. The second line contains n integers.

Output

Print the length of the longest consecutive run.

Sample Input

6
100 4 200 1 3 2

Sample Output

4

Why the sample works

The values 1, 2, 3, and 4 form the longest consecutive run.

Approach

  1. 1Put all values into a hash set.
  2. 2Only start counting from a value if value - 1 is not present.
  3. 3Walk forward while consecutive values exist.
  4. 4Each value is part of at most one walk.

O(n) expected time and O(n) extra space.

Java Solution

import java.util.*;

public class Main {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    Set<Integer> values = new HashSet<>();
    for (int i = 0; i < n; i++) values.add(sc.nextInt());

    int best = 0;
    for (int x : values) {
      if (!values.contains(x - 1)) {
        int length = 1;
        while (values.contains(x + length)) {
          length++;
        }
        best = Math.max(best, length);
      }
    }

    System.out.println(best);
  }
}

Python Solution

n = int(input())
values = set(map(int, input().split()))

best = 0
for x in values:
    if x - 1 not in values:
        length = 1
        while x + length in values:
            length += 1
        best = max(best, length)

print(best)

Practice Challenge

Make the idea your own

Create a two-minute explanation of Hash Table: define it, trace one example, name one edge case, and give the runtime of the main operation.

Tutoring Connection

Turn the topic into usable problem-solving skill

Students can use this page before a lesson, after a difficult homework assignment, or while preparing for AP Computer Science A extensions, Advanced Topics in CS, USACO growth, or a college data structures course.