Frame · dsa / ai-algorithms / 07-navigable-small-world-graph-search.jsJavaScript
Navigable Small World Graph Search (Single-Layer HNSW)
Use the tabs to read the prompt, implementation, and tests separately. Syntax uses Shiki; tests can be executed on the server with node --test.
Same file as in the repo · ~20s timeout
From file header (JSDoc)
Navigable Small World Graph Search (Single-Layer HNSW)
Problem: Vector databases avoid brute-force scans with proximity graphs.
Build a single-layer navigable small world (the bottom layer of HNSW):
- `buildNSW(points, M)` inserts points in order; each new point is linked
bidirectionally to its M nearest already-inserted points (Euclidean).
- `searchNSW(graph, points, query, k, ef)` runs best-first beam search from
entry node 0, keeping the `ef` closest nodes found so far, and stops when
the closest unexpanded candidate is farther than the worst kept result.
Return the ids (indices) of the k closest found, nearest first.
Constraints:
- 1 <= points.length <= 10^5, 1 <= M, 1 <= k <= ef
Example:
points = 6x6 integer grid where id = x * 6 + y, M = 4,
query = [3.1, 3.2], k = 3, ef = 10
-> [21, 22, 27] i.e. (3,3), (3,4), (4,3), the same as brute force
Approach: Graph construction here uses an exact scan for clarity (real
HNSW reuses the search itself). Search keeps a min-ordered candidate
frontier and a max-bounded result set of size ef, plus a visited set.
Build O(n^2 log M) as written; search is roughly O(ef * M * log ef) node
visits in practice instead of O(n). Space O(n * M).
@param {number[][]} points
@param {number} M
@returns {number[][]} adjacency lists