Full answer
The problem
"Find drivers within 2 km" over millions of moving points cannot compute the distance to every point. A spatial index groups points into cells, so a query reads only the cells that overlap the search circle, then filters by exact distance.
Geohash
Split the world in half by longitude (left or right, one bit), then by latitude (bottom or top, one bit), and repeat, interleaving bits. Every 5 bits become one base32 character. A 6-character geohash is a cell of about 1.2 km by 0.6 km.
BASE32 = "0123456789bcdefghjkmnpqrstuvwxyz"
def geohash(lat, lng, precision=6):
"""Interleave longitude and latitude bits, 5 bits per base32 character."""
lat_rng, lng_rng = [-90.0, 90.0], [-180.0, 180.0]
bits, even, out, ch, n = 0, True, [], 0, 0
while len(out) < precision:
rng, val = (lng_rng, lng) if even else (lat_rng, lat)
mid = (rng[0] + rng[1]) / 2
if val >= mid:
ch = (ch << 1) | 1
rng[0] = mid
else:
ch <<= 1
rng[1] = mid
even, n = not even, n + 1
if n == 5:
out.append(BASE32[ch])
ch, n = 0, 0
return "".join(out)
if __name__ == "__main__":
assert geohash(57.64911, 10.40744, 11) == "u4pruydqqvj" # published reference value
a = geohash(12.9716, 77.5946) # Bengaluru centre
b = geohash(12.9750, 77.5990) # about 600 m away
c = geohash(28.6139, 77.2090) # New Delhi
assert a[:5] == b[:5] and a[:2] != c[:2]
print("ok:", a, b, c)Save as geohash.py and run python3 geohash.py (Python 3.13.5).
Strengths: one string column with a normal B-tree index; prefix queries are range scans. Weaknesses: cells are rectangles whose size depends on latitude, and two points next to each other across a cell edge can have very different hashes, so queries must include the 8 neighbouring cells.
Quadtree
Start with one square; when a node holds more than a set number of points (say 100), split it into four children. Dense city centres end up with tiny cells and oceans with huge ones, so each leaf has a similar load. Usually kept in memory and rebuilt or updated as points move; a good fit for uneven, mostly static data such as business listings.
S2 and H3
- S2 projects the earth onto the six faces of a cube and orders cells along a Hilbert curve, which keeps nearby cells close in ID order. Cells have 31 levels and cover any region with a small set of cell ID ranges. Used for region coverage and indexing in large map systems.
- H3 divides the earth into hexagons at 16 resolutions. Every hexagon has six neighbours at the same distance, which suits movement, demand heat maps and pricing zones (as in ride-hailing).
Choosing
- Need it inside an existing SQL or key-value store: geohash.
- Very uneven density, in memory: quadtree.
- Global coverage, polygons, precise covering: S2.
- Neighbour analysis, aggregation by area, smooth movement: H3.
In every case the query pattern is the same: pick a resolution near the search radius, collect candidate cells, fetch points, filter by exact distance.
By level
Fresher: Explain that the map is divided into named squares and nearby points share most of the name. A fresher should know to check neighbouring squares too.
Mid: Compare geohash and quadtrees on density and storage, and describe the candidate-then-filter query. Pick a resolution from the search radius.
Senior: Discuss S2 coverings and H3 hexagon properties, moving-object updates, polygon queries and when each system fits. Expect awareness of edge effects at every level.
Key points
- All methods turn locations into cells so nearby queries read a few cells
- Geohash: interleaved bits, shared prefix means nearby, needs neighbour cells
- Quadtree adapts cell size to density
- S2 uses cube faces and a Hilbert curve; H3 uses hexagons
- Always finish with an exact distance filter
Common mistakes
- Assuming a shared geohash prefix is the only way points can be close
- Forgetting the 8 neighbour cells
- Using one fixed resolution for dense and empty areas
- Skipping the exact distance check
Follow-ups
- How would you index moving drivers that update every 4 seconds?
- Why do hexagons help for heat maps?
- How do you search within a polygon such as a city boundary?
Tips
- Explain geohash by halving the map
- Give one reason to pick each method
- State the query pattern in three steps
Evaluation rubric
- Correct explanation of geohash
- Understands neighbours and edge effects
- Compares quadtrees, S2 and H3 sensibly
- Clear selection criteria