Hash Map / Dictionary
hash-map
Data Structures
Hash Map (Dictionary) Basics
Two Sum is the canonical example: scan the array once, and for every number `x` ask the data structure whether you have already seen `target - x`. With a list that is `O(n^2)`. With a **Hash Map**, the lookup becomes a single function call and the whole algorithm collapses to `O(n)`. This lesson covers the key-value abstraction, the intuition behind a hash function (a key gets converted to a bucket index by an integer-valued function), what a collision is, and how `get`, `set`, `delete`, and `has` behave in JavaScript's `Map` and Python's `dict`. You will also meet two recurring patterns: counting frequencies and bucketing/grouping by a derived key, both of which appear in dozens of interview problems and real applications such as analytics, caching, and indexing. In **Arrays & Strings**, you saw that searching an unsorted array is `O(n)` because every position is equally plausible. A hash map turns that linear scan into an arithmetic computation that points directly at the right slot, which is the entire reason hash-based lookups dominate practical software. With key-based lookup in hand, **Set Basics** specializes the same machinery to a single question: have I seen this value before?
Not Started
0%
LRU Cache (Hash Map + DLL)
Hold a fixed number of recently used items, evict the least-recently-touched one when you run out of room, and answer both `get(key)` and `put(key, value)` in `O(1)`. No single primitive does that: a hash map gives `O(1)` lookup but no recency order, and a doubly linked list gives `O(1)` recency moves but no key index. The classical **LRU Cache** wires the two together so each compensates for what the other lacks. This lesson designs the composite from scratch: a hash map that points keys to DLL nodes, and a doubly linked list that orders nodes by recency with most-recent at the head and least-recent at the tail. You will trace `get` and `put` through both structures, handle the capacity-of-one and update-existing-key edge cases, and see why this design appears in browser caches, database query caches, OS page replacement, and CDNs. In **Hash Map (Dictionary) Basics**, you used a hash map for `O(1)` lookup by key. **Doubly Linked List** added the `prev` pointer that makes mid-list deletion `O(1)` once you hold the node, plus the sentinel pattern that erases null checks at the boundaries; both are load-bearing here. The LRU pattern (one structure for indexing, another for ordering, kept consistent on every operation) is the gateway to a wider family of composite designs covered in later lessons.
Not Started
0%
Trie (Prefix Tree)
Type the letters `a-p-p` into a search box and the autocomplete dropdown produces `apple`, `application`, `apply`, and `appoint` before you finish the next keystroke. The data structure doing that work is a **Trie** (or prefix tree), where every stored word is a path from root to a marked node and every shared prefix is shared in memory exactly once. This lesson covers the trie node layout (a `children` map plus an `isEndOfWord` flag), `insert`, `search`, and `startsWith` operations that all run in `O(m)` for a query of length `m` (independent of how many words the trie holds), and a `delete` that has to be careful not to break paths used by other words. You will also analyze the space behavior, including when a trie wins over a hash set (prefix queries, lexicographic enumeration) and when it loses (memory-tight workloads with no prefix structure to exploit). In **Hash Map (Dictionary) Basics**, you used hashing to answer 'have I seen this exact key' in `O(1)`; a trie answers a strictly richer question (any prefix lookup) by trading `O(1)` exact-match for `O(m)` traversal. **Trees: Binary Tree Fundamentals** introduced the recursive child-pointer pattern, and a trie generalizes it from two children per node to one child per alphabet symbol. With a trie in your toolkit, the curriculum moves on to graph and hash extensions that solve a different family of problems built on the same node-and-edge thinking.
Not Started
0%
Algorithms
Hashing Techniques
Two Sum was a hard problem in 2010. With a hash map it becomes a six-line interview warm-up: walk the array once, and for each value `x` ask whether `target - x` is already in the map. The same shape, single-pass plus complement lookup, solves "first duplicate," "contains nearby duplicate," "longest substring without repeats," and an entire family of trade-space-for-time problems. **Hashing Techniques** catalogs those patterns. You will work through frequency counting (most/least frequent element, group anagrams via sorted-key trick), the two-sum complement template and its three-sum / four-sum extensions, existence checking and duplicate detection, index mapping where you store positions alongside values, and a first conceptual look at rolling hashes that prepare you for Rabin-Karp later. The lesson also discusses when a hash map is overkill versus when it is the obviously correct tool. In **Hash Map (Dictionary) Basics**, you saw how hashing achieves expected `O(1)` insertion and lookup. This lesson is where that constant-time primitive turns into algorithmic leverage: brute-force `O(n^2)` scans collapse into a single pass that uses the map as an oracle. From here you move into the paid track with **Sorting (Advanced)**, which trades hash-map lookups for divide-and-conquer to break the `O(n^2)` sorting barrier.
Not Started
0%
Practice Problems
Contains Duplicate II
Check if an array contains two distinct indices with the same value whose absolute difference is at most k.
Happy Number
Determine if a number is happy by repeatedly replacing it with the sum of the squares of its digits until it reaches 1 or enters a cycle.
Isomorphic Strings
Determine if two strings are isomorphic, where each character in one string can be mapped to exactly one character in the other.
Majority Element
Given an array, find the element that appears more than half the time using Boyer-Moore Voting.
Next Greater Element I
Given two arrays where nums1 is a subset of nums2, find the next greater element in nums2 for each element in nums1.
Ransom Note
Determine if a ransom note can be constructed from the characters available in a magazine string.
Two Sum
Given an array of integers and a target, return the indices of the two numbers that add up to the target.
Valid Anagram
Given two strings, determine if one is an anagram of the other by comparing character frequencies.
Word Pattern
Check if a string of words follows the same pattern as a given pattern string, using a bijective character-to-word mapping.
Max Points on a Line
Given an array of points on a 2D plane, find the maximum number of points that lie on the same straight line.
Minimum Window Substring
Find the smallest substring of s that contains all characters of t, including duplicates.
Substring with Concatenation of All Words
Find all starting indices where a concatenation of all given words (each of equal length) forms a substring.
Accounts Merge
Given a list of accounts where each account has a name and emails, merge accounts that share a common email address.
Clone Graph
Given a reference to a node in a connected undirected graph, return a deep copy (clone) of the entire graph.
Copy List with Random Pointer
Create a deep copy of a linked list where each node has a next pointer and a random pointer that can point to any node in the list or null.
Design Twitter
Design a simplified Twitter with post, follow/unfollow, and a news feed that merges recent tweets from followed users using a heap.
Detect Squares
Design a data structure that supports adding points on a 2D plane and counting the number of ways to form axis-aligned squares with a given query point as one corner.
Evaluate Division
Given equations like a/b = k, answer queries asking for the result of x/y using graph traversal on a weighted directed graph.
Find All Anagrams in a String
Find all start indices where an anagram of pattern p occurs in string s.
Group Anagrams
Group an array of strings so that anagrams appear together, using a hash map with sorted-character keys.
Hand of Straights
Given an array of integers and a group size, determine if the array can be rearranged into groups where each group consists of consecutive integers of the given size.
Insert Delete GetRandom O(1)
Design a data structure that supports insert, remove, and getRandom in average O(1) time using a hash map paired with a dynamic array.
Integer to Roman
Convert an integer to its Roman numeral representation using a greedy approach with a value-symbol mapping.
Longest Consecutive Sequence
Find the length of the longest consecutive element sequence in an unsorted array in O(n) time using a hash set.
Longest Repeating Character Replacement
Find the length of the longest substring containing the same letter after performing at most k character replacements.
Longest Substring Without Repeating Characters
Find the length of the longest substring without repeating characters using the sliding window technique.
LRU Cache
Design a data structure that follows the Least Recently Used (LRU) cache constraints, supporting get and put operations in O(1) time.
Partition Labels
Given a string, partition it into as many parts as possible so that each letter appears in at most one part, and return a list of the sizes of these parts.
Permutation in String
Given two strings, determine if one string's permutation is a substring of the other.
Roman to Integer
Convert a Roman numeral string to an integer by mapping symbols to values and handling subtractive notation.
Set Matrix Zeroes
Given an m x n integer matrix, if an element is 0, set its entire row and column to 0 using constant extra space.
Subarray Sum Equals K
Count the total number of contiguous subarrays whose sum equals k using a prefix sum hash map technique.
Time Based Key-Value Store
Design a key-value store that can store multiple values for the same key at different timestamps and retrieve the value at a given timestamp using binary search.
Top K Frequent Elements
Find the k most frequent elements in an array using a hash map for counting and bucket sort for efficient selection.
Valid Sudoku
Determine if a 9x9 Sudoku board is valid by checking rows, columns, and 3x3 sub-boxes for duplicate digits using hash sets.
Word Break
Given a string and a dictionary of words, determine if the string can be segmented into a space-separated sequence of dictionary words.
Code Snippets
std::unordered_map Quick Reference
`std::unordered_map` is the default hash table in C++: average O(1) insert, lookup, and erase. This snippet covers insertion, the right way to test for membership without inserting a default, iteration, and structured bindings (C++17) for clean key/value loops. Use it whenever you need a dictionary; reach for `std::map` only when you need keys in sorted order.
Array Equality and Duplicate Detection
Three related questions on arrays: are these two arrays equal in content, does this array have any duplicates at all, and how do I dedupe a list of objects by some key. Each one has a clean linear-time answer once you know which JS collection to lean on (`Set` for primitives, `Map` for keyed objects). The naive `O(n^2)` versions are fine for tiny arrays but show up in code reviews on anything bigger.
Question Banks
Array Cross-Reference and Lookup Challenges
Six lookup-and-filter drills: id-to-id matching with Sets, random sampling without duplicates, valid-only filtering, numeric-only extraction, value-by-row matching, and rest-parameter multipliers.
Array Sorting and Grouping Challenges
Six sorting/grouping problems: dynamic key sort, multi-key sort, top-N average, date sort, top-N max preserving identity, group-by, and id-driven custom ordering.
JavaScript Group Students by ID: Two Approaches Quiz
Two seeded approaches to group an array of student records by id (reduce + dict and the `in` operator), plus two companions on Map and Object.groupBy.
JavaScript Character Occurrence Count: Three Approaches Quiz
Count how often each unique character from a needle string appears in a haystack, three ways (Set + per-char count, dict tally, regex match per char), plus two companions on case folding and a single-pass tally.
JavaScript Array Occurrences Count: Two Approaches Quiz
Tally how many times each value appears in an array, two ways (reduce + dict and Map-based counter), plus two companions on Object.create(null) safety and case-insensitive string tallies.
JavaScript String Duplicate Finder: Two Approaches Quiz
Tally character frequencies in a string two ways (explicit loop + counter dict and reduce one-liner), plus two companions on Unicode-aware iteration and duplicates-only filtering.
JavaScript Grouped Scores Filter: Two Approaches Quiz
Filter a grouped scores object so each row keeps only requested keys, solved two ways (Object.entries + map and a for-in loop), plus companions on Map output and key-rename mapping.
JavaScript Pair-Sum Finder: Two Approaches Quiz
Two seeded ways to test whether two numbers in an array add up to a target (nested loop and Set complement), plus two companions on time complexity and on returning the actual pair instead of a boolean.
JavaScript Group By ID with Average Score: Two Approaches Quiz
Two seeded ways to group records by id and compute each group's average (bucket-then-divide vs running sum + count), plus two companions on min/max per group and on memory trade-offs at scale.
Community
Design HashMap
Implement a HashMap from scratch using a fixed bucket array with separate chaining; support put / get / remove on integer keys.
Hash Tables: The Most Useful Data Structure
Why hash tables earn their reputation, where collisions and load factor actually bite, and the language-specific quirks (JS Map vs Object, Python dict, Java HashMap) that change the game.
Dedupe by Key With Last-Write-Wins (JS)
dedupeBy(rows, 'id') is the function I copy into every ETL script. Last-write-wins is the right policy 90% of the time; this version also exposes a configurable resolver for the other 10%.
Core Data Structures Warmup
Two quick whiteboard questions on array vs linked list complexity and hash-map two-sum. Five minutes each.
Top K Frequent Elements
Return the k most frequent elements in O(n) time using bucket sort by frequency. A staple of mid-level interview rotations.
Valid Anagram
Decide whether two strings are anagrams of each other in O(n) using a frequency map.
LRU Cache From Scratch in 50 Lines
A working LRU cache built from a hash map plus a doubly linked list, the part interview answers leave out (concurrency, eviction callbacks, byte budgets), and when LRU is the wrong eviction policy.
