AlgoMaster Logo

R-Trees

Medium Priority18 min readUpdated October 25, 2026
AI Mock Interview

Practice this topic in a realistic system design interview

Premium Video

This video is available to premium subscribers only

Unlock Full Access

Spatial search gets harder when the objects are not just points. Restaurants may be points, but delivery zones are polygons, roads are lines, and buildings are shapes that cover an area. Checking every shape for every query does not scale.

An R-tree speeds this up by wrapping each shape in a rectangle and grouping nearby rectangles into larger ones. A search can then skip whole groups that are nowhere near the query.

In this chapter, we'll learn what an R-tree is, how it groups shapes into nested bounding rectangles, how it answers spatial queries, and why it is the index behind most spatial databases.

1. The Problem

Suppose you're building a food delivery app. Each restaurant has a delivery zone, which defines the area where it can deliver orders.

These zones are not necessarily circles. They can be irregular polygons that follow streets, rivers, and neighborhood boundaries.

When a customer opens the app, you need to figure out which restaurants can deliver to their location. In other words, which delivery zones contain the customer's location?

To answer this, we need to check whether the customer's location falls inside each polygon. This involves some geometric calculations, especially when polygons have hundreds of edges.

Now imagine you have 1 million restaurants, each with its own delivery zone. Checking the customer's location against every polygon for every request would be far too slow:

What we need is a way to quickly eliminate delivery zones that are nowhere near the customer, so we only check the ones that might actually contain their location.

2. Why Point Indexes Struggle with Shapes

Spatial indexing structures like Geohash and quadtrees work well for points. Each point falls into exactly one cell, so it's relatively easy to organize and search for.

But shapes are more complicated. A restaurant's delivery zone can cover a large area and span multiple cells.

  • Geohash: we might need to store the same zone in every cell it overlaps. A large delivery zone could overlap thousands of small cells, leading to a lot of duplicate data.
  • Quadtrees: they face a similar challenge. If a delivery zone crosses the boundary between two or more child nodes, it cannot fit neatly into a single node. We either have to store it in multiple nodes or keep it higher up in the tree, where more searches may need to check it.

So instead of dividing space into fixed regions, we need a structure that can efficiently organize objects based on their size and shape.

3. The Core Idea: Bounding Rectangles

Premium Content

This content is for premium members only.