Files
leetcode/apps/docs/content/(01-linear-structures)/hash-table/index.mdx
T

49 lines
2.2 KiB
Plaintext

---
title: Hash Table
description: 'A key maps to a value in constant time, which removes the need for a full scan.'
hidden: true
---
## Hash Tables
Sometimes when programming, we need a data structure that maps an arbitrary data type to another arbitrary data type, like an array with non-integer indices. For example, a phone book that allows lookup by a person's name requires such data type.
A **hash table** (or a hash map) is one way of representing this data structure. The idea of hash table is this:
Data is stored in a fix-sized array, where each data value has an unique index. When we add a new `(key, value)` pair to the array, we use a hash function to generate a hash value within the range of the array with the `key`. We then store the data `value` at the index indicated by the generated hash value. Later, when we retrieve the data with the `key` from the hash table, we hash the `key` again and look up the data in the array with the corresponding index. Since the hash function always returns the same hash values with the same input, we will always find the correct item in that index.
<Frame caption="Hash Table Operations">
<img src="../../../public/hash-table-operations.svg" alt="Hash Table Operations" />
</Frame>
## Efficiency
Assuming the hash function uses constant time, the average time complexity is `O(n / k)` for each insertion/access operation on the table, where `n` is the number of entries in the hash table and `k` is the array size of the table. This assumes the hash function distributes keys uniformly across the `k` buckets, so each bucket holds about `n / k` entries on average.
**Frequency Counting**
```python
def get_counter(arr: list[int]) -> dict[int, int]:
# initialize a hash map to store each number and its count
counter: dict[int, int] = {}
for num in arr:
# check if num is a key in the hash map
if num in counter:
# update the count of num to increase by 1
counter[num] += 1
else:
# set the count of num to 1
counter[num] = 1
return counter
```
::: tip[Python provides a built-in `collections.Counter` class]
```python
from collections import Counter
fq = Counter(arr)
```
:::