Rocket Academy Bootcamp
  • 🚀Welcome to Bootcamp!
  • 🛠️Logistics
    • Course Schedules
    • Course Methodology
    • Required Software
    • LinkedIn Education Badge
  • 📚General Reference
    • Naming, Casing, and Commenting Conventions
    • VS Code Tips
    • Recommended Resources
  • 🪨0: Foundations
    • 0.1: Command Line
    • 0.2: Git
      • 0.2.1: Branches
    • 0.3: GitHub
      • 0.3.1: Pull Requests
    • 0.4: JavaScript
      • 0.4.1: ES6
      • 0.4.2: Common Syntax
      • 0.4.3: Reference vs Value
      • 0.4.4: Classes
      • 0.4.5: Destructuring and Spread Operator
      • 0.4.6: Promises
        • 0.4.6.1: Async Await
    • 0.5: Node.js
      • 0.5.1: Node Modules
      • 0.5.2: NPM
      • 0.5.3: Nodemon
  • 🖼️1: Frontend
    • 1.1: HTML
    • 1.2: CSS
      • 1.2.1: Layout
    • 1.3: React
      • Styling in ReactJs
      • Using Styling Libraries with React
      • React Deployment
    • 1.E: Exercises
      • 1.E.1: Recipe Site
      • 1.E.2: Portfolio Page
      • 1.E.3: World Clock
      • 1.E.4: High Card
      • 1.E.5: Guess The Word
    • 1.P: Frontend App
  • 🏭2: Full Stack
    • 2.1: Internet 101
      • 2.1.1: Chrome DevTools Network Panel
      • 2.1.2: HTTP Requests and Responses
    • 2.2: Advanced React
      • 2.2.1: AJAX
      • 2.2.2: React Router
      • 2.2.3: useContext
      • 2.2.4: useReducer
      • 2.2.5: Environmental Variables
      • 2.2.6: React useMemo - useCallback
    • 2.3: Firebase
      • 2.3.1: Firebase Realtime Database
      • 2.3.2: Firebase Storage
      • 2.3.3: Firebase Authentication
      • 2.3.4: Firebase Hosting
      • 2.3.5: Firebase Techniques
    • 2.E: Exercises
      • 2.E.1: Weather App
      • 2.E.2: Instagram Chat
      • 2.E.3: Instagram Posts
      • 2.E.4: Instagram Auth
      • 2.E.5: Instagram Routes
    • 2.P: Full-Stack App (Firebase)
  • 🤖3: Backend
    • 3.1: Express.js
      • 3.1.1 : MVC
    • 3.2: SQL
      • 3.2.1: SQL 1-M Relationships
      • 3.2.2: SQL M-M Relationships
      • 3.2.3: SQL Schema Design
      • 3.2.4: Advanced SQL Concepts
      • 3.2.5: SQL - Express
      • 3.2.6: DBeaver
    • 3.3: Sequelize
      • 3.3.1: Sequelize One-To-Many (1-M) Relationships
      • 3.3.2: Sequelize Many-To-Many (M-M) Relationships
      • 3.3.3: Advanced Sequelize Concepts
      • 3.3.4 Database Design
    • 3.4: Authentication
      • 3.4.1: JWT App
    • 3.5: Application Deployment
    • 3.E: Exercises
      • 3.E.1: Bigfoot JSON
      • 3.E.2: Bigfoot SQL
      • 3.E.3: Bigfoot SQL 1-M
      • 3.E.4: Bigfoot SQL M-M
      • 3.E.5: Carousell Schema Design
      • 3.E.6: Carousell Auth
    • 3.P: Full-Stack App (Express)
  • 🏞️4: Capstone
    • 4.1: Testing
      • 4.1.1: Frontend React Testing
      • 4.1.2: Backend Expressjs Testing
    • 4.2: Continuous Integration
      • 4.2.1 Continuous Deployment (Fly.io)
      • 4.2.2: Circle Ci
    • 4.3: TypeScript
    • 4.4: Security
    • 4.5: ChatGPT for SWE
    • 4.6: Soft Skills for SWE
    • 4.P: Capstone
  • 🧮Algorithms
    • A.1: Data Structures
      • A.1.1: Arrays
        • A.1.1.1: Binary Search
        • A.1.1.2: Sliding Windows
      • A.1.2: Hash Tables
      • A.1.3: Stacks
      • A.1.4: Queues
      • A.1.5: Linked Lists
      • A.1.6: Trees
      • A.1.7: Graphs
      • A.1.8: Heaps
    • A.2: Complexity Analysis
    • A.3: Object-Oriented Programming
    • A.4: Recursion
    • A.5: Dynamic Programming
    • A.6: Bit Manipulation
    • A.7: Python
  • 💼Interview Prep
    • IP.1: Job Application Strategy
    • IP.2: Resume
    • IP.3: Portfolio
Powered by GitBook
On this page
  • Learning Objectives
  • Introduction
  • Pros and cons of hash tables
  • How does a hash table work?
  • Common use case: frequency tally
  • Example 1: Determine most popular candidate
  • Example 2: Determine low-stock items
  • Exercises
  • Pre-Class
  • Part 1
  • Part 2
  • Part 3
  • More Comfortable
  1. Algorithms
  2. A.1: Data Structures

A.1.2: Hash Tables

Learning Objectives

  1. Understand pros and cons of using hash tables

  2. Understand how a hash table stores and retrieves values

  3. Understand how to use hash tables to solve algorithm problems that require calculating frequencies of elements in a collection

Introduction

A "hash table" is a data structure that stores key-value pairs with constant time (O(1)) lookup and insertion. It is also the computer science concept behind JavaScript objects. Every popular programming language has their own implementation of the hash table, such as Python Dictionaries and Java HashMaps.

We will use JS objects in a new way to solve algorithm problems. So far we have used JS objects primarily to store compound data such as playing cards, where it made sense to group card attributes such as name, rank and suit in a single data structure. We will now also use objects as frequency tallies.

Pros and cons of hash tables

Pros
Cons

O(1) lookup, insertion, deletion

O(n) space complexity

Generally the speed benefits of using a hash table outweigh the impact of additional space required, and when there is algorithmic benefit to using a hash table we should use it.

How does a hash table work?

Hash tables achieve O(1) lookup and insertion by "hashing" keys (typically strings) into array indexes with a constant-time "hash function", such that given a key it knows exactly where to retrieve or insert the relevant data and can access that data in constant time. Hash table implementations typically maintain a larger array size than number of key-value pairs to minimise "collisions" (multiple keys hashing to the same index) and maintain O(1) lookup and insertion.

Common use case: frequency tally

Example 1: Determine most popular candidate

Given 1000 votes, determine who is the winner

const candidates = ["sam", "perry", "eng liang"]
const votes = []

// Create a random sample of 1000 votes
for (let i = 0; i < 1000; i++) {
  votes.push(candidates[Math.floor(Math.random() * candidates.length)])
}
  
// Compile tally of how many votes each candidate received
const tally = {}
for (const candidate of votes) {
  if (candidate in tally) {
    tally[candidate] += 1
  } else {
    tally[candidate] = 1  
  }
}
  
// Determine who had most votes in the tally
// Initialise maxVotes to a minimum number
let maxVotes = 0;
let mostPopularCandidate;
Object.keys(tally).forEach((candidate) => {
  if (tally[candidate] > maxVotes) {
    maxVotes = tally[candidate];
    mostPopularCandidate = candidate;
  }
})

// mostPopularCandidate is the candidate with most votes in tally
console.log(`${mostPopularCandidate} wins!`);

Example 2: Determine low-stock items

Given a number of fruits in stock, determine which fruits are low-stock and need replenishment

// Generate fruits in a supermarket
fruitTypes = ["apple","pear","banana"]
fruitsInStore = []

// Create a random sample of 1000 fruits
for (let i = 0; i < 1000; i++) {
  fruitsInStore.push(fruitTypes[Math.floor(Math.random() * fruitTypes.length)])
}

// Compile tally of how many of each fruit is in store
const tally = {}
for (const fruit of fruitsInStore) {
  if (fruit in tally) {
    tally[fruit] += 1
  } else {
    tally[fruit] = 1  
  }
}

// Determine which fruits are low-stock
LOW_STOCK_THRESHOLD = 300;
lowStockFruits = []
Object.keys(tally).forEach((fruit) => {
  if (tally[fruit] < LOW_STOCK_THRESHOLD) {
    lowStockFruits.push(fruit)
  }
})

// Output fruits with stock below the low stock threshold
console.log(lowStockFruits);

Exercises

After attempting each problem, find solutions in the Leaderboard tab (HackerRank, may be on left side of page) or Solution or Discuss tabs (LeetCode) on that problem's page. If you get stuck for more than 15 minutes, review and understand the solutions and move on. Come back and re-attempt the problem after a few days.

Pre-Class

Part 1

Part 2

Part 3

More Comfortable

    1. Hint: Sort, track num smaller numbers for each number in hash table, use hash table to generate results array

    1. Hint: Sliding window?

    1. Hint: Sliding window?

    1. Hint: Fixed-size window with hash table of letter frequencies?

PreviousA.1.1.2: Sliding WindowsNextA.1.3: Stacks

Two Strings ()

Valid Anagram ()

N-Repeated Element in Size 2N Array ()

Sum of Unique Elements ()

Unique Number of Occurrences ()

Ransom Note ()

Maximum Number of Balloons ()

Uncommon Words from Two Sentences ()

Find Words That Can Be Formed By Characters ()

Intersection of Two Arrays II ()

Find Common Characters ()

How Many Numbers are Smaller than the Current Number ()

Sherlock and Anagrams ()

Longest Substring Without Repeating Characters ()

Permutation in String ()

🧮
HackerRank
LeetCode
LeetCode
LeetCode
LeetCode
HackerRank
LeetCode
LeetCode
LeetCode
LeetCode
LeetCode
LeetCode
HackerRank
LeetCode
LeetCode