글 목록으로

해시테이블 자료구조 이론

원문 보기
#이론#자료구조#해시테이블

해시 테이블의 기본 개념과 해싱, 슬롯, 로드 팩터를 정리하고, 해시 충돌 해결 방식인 오픈 어드레싱과 체이닝의 동작 원리 및 JavaScript 구현 예제를 살펴봅니다.

해시 테이블이란?

  • 배열과 해시 함수를 사용하여 Map을 구현한 자료구조
  • 일반적으로 상수 시간에 데이터에 접근할 수 있어 빠르다.

용어

해싱
: 임의의 크기를 가진 데이터를 고정된 크기의 값으로 변환하는 과정을 말하며, 이러한 역할을 하는 함수를 해시 함수(Hash Function)라고 한다.

  • 임의의 크기를 가진 타입의 데이터를 고정된 크기를 가진 타입의 데이터로 변환하는 함수

ex)
-> 나눗셈을 이용한 해시
-> encode를 이용해 데이터를 바이트 형태로 변환하는 해시 등이 있다.

슬롯
: 해시 테이블에서 하나의 데이터를 저장할 수 있는 공간을 의미한다. 해시 충돌이 발생하면 충돌 처리 방식에 따라 다른 슬롯을 탐색하거나, 동일한 버킷에 여러 값을 저장한다.

로드 팩터
: 해시 테이블에서 전체 버킷 수에 비해 원소가 얼마나 저장되어 있는지를 나타내는 비율이다.
해시 테이블의 충돌을 줄이고 성능을 높이기 위해 고려해야 하는 중요한 요소이다.

전체 원소의 개수를 전체 버킷 수로 나눈 값이다.

원소의 개수 / 전체 버킷 수

로드 팩터 비율에 따라 해시 함수나 테이블 크기의 조정 여부를 결정한다.
오픈 어드레싱 방식에서는 로드 팩터가 1을 넘을 수 없으며, 일정 수준 이상 증가하면 테이블 크기를 확장하는 것이 일반적이다.

(1) 키가 해시 함수를 통과한다.
(2) 해시 함수의 결괏값을 기준으로 버킷에 데이터가 저장된다.


해시 함수에서 발생할 수 있는 문제

  • 이상적인 경우 해시 테이블은 높은 검색 효율을 가진다.
  • 그러나 서로 다른 데이터를 항상 서로 다른 해시값으로 변환하는 것은 이론적으로 불가능하다.
  • 따라서 서로 다른 키가 같은 해시값을 가지는 해시 충돌이 발생할 수 있다.

해결 방법은?

오픈 어드레싱(Open Addressing)

: 해시 충돌이 발생했을 때, 다른 빈 슬롯을 탐색하여 데이터를 저장하는 오픈 어드레싱 기법이 존재한다.

Map을 사용하지 않는 오픈 어드레싱 방식(선형 탐사)

  • 해시 함수(_hash): 주어진 키를 해시 테이블 크기 내의 인덱스로 변환한다.
  • 선형 탐사(_probe): 해시 충돌이 발생했을 때 다음 인덱스를 계산한다.
  • set(key, value): 키-값 쌍을 저장한다. 충돌이 발생하면 선형 탐사를 통해 빈 슬롯을 찾는다.
  • get(key): 주어진 키에 해당하는 값을 가져온다. 충돌이 발생한 경우 올바른 키를 찾을 때까지 선형 탐사를 수행한다.
  • remove(key): 주어진 키에 해당하는 값을 삭제한다. 삭제된 슬롯에는 탐색 흐름이 끊기지 않도록 삭제 표시를 남긴다.
class HashTable {
    constructor(size = 50) {
        // 해시 테이블의 크기를 설정하고 초기화합니다.
        this.table = new Array(size);
        this.size = size;

        // 삭제된 슬롯을 구분하기 위한 값입니다.
        this.DELETED = Symbol("DELETED");
    }

    // 해시 함수: 주어진 키를 해시 테이블의 인덱스로 변환합니다.
    _hash(key) {
        let hash = 0;

        for (let i = 0; i < key.length; i++) {
            hash += key.charCodeAt(i);
        }

        return hash % this.size;
    }

    // 선형 탐사 함수: 최초 인덱스를 기준으로 다음 인덱스를 계산합니다.
    _probe(startIndex, step) {
        return (startIndex + step) % this.size;
    }

    // 키-값 쌍을 해시 테이블에 저장하는 함수
    set(key, value) {
        const startIndex = this._hash(key);
        let firstDeletedIndex = -1;

        for (let step = 0; step < this.size; step++) {
            const index = this._probe(startIndex, step);
            const entry = this.table[index];

            // 삭제된 슬롯의 위치를 기억합니다.
            if (entry === this.DELETED) {
                if (firstDeletedIndex === -1) {
                    firstDeletedIndex = index;
                }
                continue;
            }

            // 빈 슬롯을 찾으면 데이터를 저장합니다.
            if (entry === undefined) {
                const targetIndex =
                    firstDeletedIndex !== -1 ? firstDeletedIndex : index;

                this.table[targetIndex] = [key, value];
                return;
            }

            // 같은 키가 있으면 값을 업데이트합니다.
            if (entry[0] === key) {
                this.table[index] = [key, value];
                return;
            }
        }

        // 삭제된 슬롯이 있다면 해당 위치를 재사용합니다.
        if (firstDeletedIndex !== -1) {
            this.table[firstDeletedIndex] = [key, value];
            return;
        }

        throw new Error("해시 테이블에 빈 슬롯이 없습니다.");
    }

    // 주어진 키에 해당하는 값을 가져오는 함수
    get(key) {
        const startIndex = this._hash(key);

        for (let step = 0; step < this.size; step++) {
            const index = this._probe(startIndex, step);
            const entry = this.table[index];

            // 한 번도 사용되지 않은 빈 슬롯을 만나면 탐색을 종료합니다.
            if (entry === undefined) {
                return undefined;
            }

            // 삭제된 슬롯은 건너뜁니다.
            if (entry === this.DELETED) {
                continue;
            }

            if (entry[0] === key) {
                return entry[1];
            }
        }

        return undefined;
    }

    // 주어진 키에 해당하는 값을 삭제하는 함수
    remove(key) {
        const startIndex = this._hash(key);

        for (let step = 0; step < this.size; step++) {
            const index = this._probe(startIndex, step);
            const entry = this.table[index];

            // 한 번도 사용되지 않은 빈 슬롯을 만나면 키가 존재하지 않습니다.
            if (entry === undefined) {
                return false;
            }

            // 삭제된 슬롯은 건너뜁니다.
            if (entry === this.DELETED) {
                continue;
            }

            if (entry[0] === key) {
                this.table[index] = this.DELETED;
                return true;
            }
        }

        return false;
    }
}

Map을 사용한 오픈 어드레싱 방식

class HashTable {
    constructor(size = 50) {
        // 해시 테이블을 Map으로 생성하고 초기화합니다.
        this.table = new Map();
        this.size = size;

        // 삭제된 슬롯의 인덱스를 저장합니다.
        this.deletedIndexes = new Set();
    }

    // 해시 함수: 주어진 키를 해시 테이블의 인덱스로 변환합니다.
    _hash(key) {
        let hash = 0;

        for (let i = 0; i < key.length; i++) {
            hash += key.charCodeAt(i);
        }

        return hash % this.size;
    }

    // 선형 탐사 함수: 최초 인덱스를 기준으로 다음 인덱스를 계산합니다.
    _probe(startIndex, step) {
        return (startIndex + step) % this.size;
    }

    // 키-값 쌍을 해시 테이블에 저장하는 함수
    set(key, value) {
        const startIndex = this._hash(key);
        let firstDeletedIndex = -1;

        for (let step = 0; step < this.size; step++) {
            const index = this._probe(startIndex, step);

            if (this.deletedIndexes.has(index)) {
                if (firstDeletedIndex === -1) {
                    firstDeletedIndex = index;
                }
                continue;
            }

            if (!this.table.has(index)) {
                const targetIndex =
                    firstDeletedIndex !== -1 ? firstDeletedIndex : index;

                this.table.set(targetIndex, [key, value]);
                this.deletedIndexes.delete(targetIndex);
                return;
            }

            if (this.table.get(index)[0] === key) {
                this.table.set(index, [key, value]);
                return;
            }
        }

        if (firstDeletedIndex !== -1) {
            this.table.set(firstDeletedIndex, [key, value]);
            this.deletedIndexes.delete(firstDeletedIndex);
            return;
        }

        throw new Error("해시 테이블에 빈 슬롯이 없습니다.");
    }

    // 주어진 키에 해당하는 값을 가져오는 함수
    get(key) {
        const startIndex = this._hash(key);

        for (let step = 0; step < this.size; step++) {
            const index = this._probe(startIndex, step);

            if (this.deletedIndexes.has(index)) {
                continue;
            }

            if (!this.table.has(index)) {
                return undefined;
            }

            if (this.table.get(index)[0] === key) {
                return this.table.get(index)[1];
            }
        }

        return undefined;
    }

    // 주어진 키에 해당하는 값을 삭제하는 함수
    remove(key) {
        const startIndex = this._hash(key);

        for (let step = 0; step < this.size; step++) {
            const index = this._probe(startIndex, step);

            if (this.deletedIndexes.has(index)) {
                continue;
            }

            if (!this.table.has(index)) {
                return false;
            }

            if (this.table.get(index)[0] === key) {
                this.table.delete(index);
                this.deletedIndexes.add(index);
                return true;
            }
        }

        return false;
    }
}

체이닝(Chaining)

  • 서로 다른 키에서 동일한 해시값이 나온 경우, 하나의 버킷에 여러 키-값 쌍을 연결하여 충돌을 해결하는 방식이다.
  • 체이닝 방식에서는 하나의 버킷에 여러 원소를 저장할 수 있으므로 로드 팩터가 1을 초과할 수 있다. 다만 특정 버킷에 원소가 과도하게 집중되면 탐색 성능이 선형적으로 저하될 수 있다.

JS 해시 테이블 체이닝 코드

class HashTable {
    constructor(size = 50) {
        this.table = new Array(size);
        this.size = size;
    }

    // 해시 함수: 문자열을 해시 테이블 크기 내의 인덱스로 변환합니다.
    _hash(key) {
        let hash = 0;

        for (let i = 0; i < key.length; i++) {
            hash += key.charCodeAt(i);
        }

        return hash % this.size;
    }

    // 값을 설정하는 함수
    set(key, value) {
        const index = this._hash(key);

        if (!this.table[index]) {
            this.table[index] = [];
        }

        // 같은 키가 있으면 값을 업데이트하고, 없으면 새로 추가합니다.
        for (let i = 0; i < this.table[index].length; i++) {
            if (this.table[index][i][0] === key) {
                this.table[index][i][1] = value;
                return;
            }
        }

        this.table[index].push([key, value]);
    }

    // 값을 가져오는 함수
    get(key) {
        const index = this._hash(key);

        if (!this.table[index]) {
            return undefined;
        }

        for (let i = 0; i < this.table[index].length; i++) {
            if (this.table[index][i][0] === key) {
                return this.table[index][i][1];
            }
        }

        return undefined;
    }

    // 값을 삭제하는 함수
    remove(key) {
        const index = this._hash(key);

        if (!this.table[index]) {
            return false;
        }

        for (let i = 0; i < this.table[index].length; i++) {
            if (this.table[index][i][0] === key) {
                this.table[index].splice(i, 1);

                // 버킷이 비었다면 배열 자체를 제거합니다.
                if (this.table[index].length === 0) {
                    this.table[index] = undefined;
                }

                return true;
            }
        }

        return false;
    }
}

// 사용 예시
const hashTable = new HashTable();