Home/Labs/S2 Hilbert Cell Lookup
All 280 Labs
INTERACTIVE LAB🗺️

S2 Hilbert Cell Lookup Lab (Interactive)

Sweep S2 levels to watch Hilbert locality shrink region queries to a few covering cells. Quantize the Earth onto six cube faces with a Hilbert curve: pick a cell level, measure cell area, compare the covering-cell range scan against an O(N) haversine sweep of every POI.

Google S2 Hilbert Cell Lab

Pick an S2 level (0-30) and a search radius to see a 2D circle collapse into a handful of 1D 64-bit B-Tree range scans.

Cell edge length563 m
Total cells at this level1.61e+9
Covering ranges for the circle44 uint64 BETWEEN spans
Candidate rows fetched27,865 of 800,000
Naive ST_DWithin trig scan240 ms (O(N) acos per row)
S2 + B-Tree range scan5.97 ms
Speedup40x
Hilbert locality turns the 2 km circle into 44 uint64 BETWEEN ranges: 27,865 candidate rows fetched from the B-Tree in ~5.97 ms instead of a 240 ms trig scan over 800K drivers. 40x faster.

How It Works Under the Hood

Google Maps, Pokémon GO, and Uber need "what is near me" answered in single-digit milliseconds across billions of indexed points. S2 projects the sphere onto a cube, unfolds each face with a Hilbert space-filling curve, and numbers cells so that geographic proximity maps to numeric contiguity. Each level quarters cell area from roughly 7,800 square kilometers at level 0, and a region query becomes a handful of covering-cell intervals scanned as sorted ranges instead of computing distance to every candidate.

Core Architectural Principles

  • Hilbert ordering: 1-D interval locality mirrors 2-D geographic proximity, turning radius queries into range scans.
  • Level geometry: 6 faces times 4^level cells, with average edge length halving per level — choose the cell that matches query precision.
  • Covering decomposition: a circle becomes a minimal set of cell intervals, compared here against a brute-force haversine scan of the fleet.
Interview Round Script

For geospatial design, rank your options and defend one: "Quad-trees are unbounded in depth, geohash has meridian and seam problems, so I pick S2 or H3." Then justify with numbers: level-13 S2 cells are soccer-pitch sized, and proximity becomes sorted-interval lookups you can push into any key-value store. Naming the trade by name is what separates senior from mid-level answers.

Key Trade-Offs

Space-filling curve indices give O(1) cell mapping and range-scan locality but pay projection distortion near cube faces and cell-boundary edge cases.

Related Curriculum Chapter

Google Maps & Uber: Geohashing, S2 Geometry, & Quad-Trees

Read Full Chapter Blueprint

Explore More Interactive Labs

View All 280 Labs