Hash Tables
Group by Key
Build buckets keyed by a shared field, preserving the first-seen key order.
Algorithm
Canonical pairs (a,1), (b,2), (a,3), (c,4), (b,5) print
{a: [1, 3], b: [2, 5], c: [4]}.
The replay uses the same input in every language, so this SQL DSA
implementation can be compared directly with the rest of the DSA track.
Basic Implementation
basic.sql
WITH pairs(ord, key, value) AS (
VALUES (1, 'a', 1), (2, 'b', 2), (3, 'a', 3), (4, 'c', 4), (5, 'b', 5)
),
grouped AS (
SELECT key, GROUP_CONCAT(value, ', ') AS values_text, MIN(ord) AS first_ord
FROM (SELECT * FROM pairs ORDER BY ord)
GROUP BY key
)
SELECT '{' || GROUP_CONCAT(key || ': [' || values_text || ']', ', ') || '}'
FROM (SELECT * FROM grouped ORDER BY first_ord);
Complexity
- Time: O(n) average
- Space: O(k + n) for buckets and values
Implementation notes
- Keep output formatting deterministic. Do not rely on unordered hash-map printing when the lesson needs cross-language comparison.
- The trace highlights the hash table state after each write.
bucket map
Each key owns a list. A new key creates a bucket; a repeated key appends to the existing bucket.