SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
  • Geohash
  • Quad Trees
  • R-Trees
  • S2 and H3
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Advanced Data Topics/Geospatial Structures

Quad Trees

Split the map into four squares again and again, only where there are many points.

⏱ 12 min readIntermediateInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

A quad tree is a tree that splits a map into four equal squares, and then splits any square that is too crowded into four smaller squares, again and again.

  • Crowded places (a big city) get many small squares. Empty places (the sea) stay as one big square.
  • To find points in an area, you skip every square that does not touch it and look only inside the squares that do.
  • It is great for points that move or change, because a point can be added or removed without rebuilding everything.

02Concept: What is it?

Imagine a square map with lots of dots on it. A fixed grid (like graph paper) wastes effort: in a city, one grid square holds thousands of dots, while in a desert thousands of squares are empty. A quad tree fixes this by making the squares adapt to the data.

The rule is simple. Each square (a node) can hold a small number of points, called its capacity, for example 4. When a fifth point arrives, the square splits into four equal quarters (top-left, top-right, bottom-left, bottom-right), and its points move into the right quarters. If a quarter is still too crowded, it splits again.

One square splits into four
⬜1 square5 points, too many
→↓split
🔲4 squareseach gets a few
→↓still crowded? split again
🧩Small squaresonly where needed
Only the crowded square keeps splitting. The others stay big.

To search, you start at the top and ask each square: “do you touch my search box?” If not, the whole square (and everything inside it) is skipped. If yes, go into its four children. At the bottom you check the few points inside.

🧠Quad = four
The name comes from four children per node. The 3D version has eight children and is called an octree.

03Real-Life Example

🍵Zooming Into a Big City Map
Think of a paper atlas. The first page shows the whole country on one page. Pages for big cities show them in much more detail, because there is so much to show. The empty desert stays on one page with almost nothing. To find a street, you flip to the right page quickly and never open the pages for other places. A quad tree works the same way: more detail only where there is more to show.
Atlas
Quad tree
The whole-country page
The root square
A more detailed page for a big city
A node that split into four children
A desert that stays on one page
A leaf square that never split
Ignoring pages for faraway places
Skipping squares that miss the search box
At most N places on a page
Node capacity
A stopping rule for how detailed pages get
A maximum depth
Searching a quad tree
🔍Search box
→↓touches root?
⬜Root
→↓which of 4 children touch?
🔲1 or 2 childrenothers skipped
→↓check the few points
📍Results

04Why Do We Need It?

🎯Adapts to the data
Dense areas get fine detail, empty areas cost almost nothing.
⚡Fast area search
Whole squares that miss the search box are skipped in one step.
🔄Easy updates
Adding or removing one point touches only a few squares, so it suits moving objects.
🧠Simple idea
Four children, one capacity rule, and a depth limit. Easy to code and explain.
🧮Nearest neighbour
Visit the closest squares first and stop once nothing closer can exist.
💾Saves memory
No need to store a huge grid of empty cells.
A quad tree gives more detail only where the data is crowded, so searches skip most of the map.

05Where Do We Use It?

🗺️Maps and nearby search
Find points of interest in the visible part of the map.
🎮Games
Find which objects could collide, without checking every pair.
🖼️Images
Compress or process images by splitting flat areas into big blocks.
🚕Moving objects
Cars or drivers that change place often, in memory.
🌡️Heat maps
Group many points into bigger squares when zoomed out.
🛰️Spatial databases
Some systems index space with quad-tree-like structures, often on top of cell keys.

06Types / Parts / How It Works

How a quad tree is built

Insert a point
Before
⬜Leaf4 points (full)
↓insert a 5th
After
⬜Node (no points)
NW2
NE0
SW2
SE1
Full leaf Inner node Leaf with points
Walk down to the right leaf. If it is full, split it and move its points into the new children.

Kinds of quad trees

KindWhat it splitsUsed for
Point-region (PR) quad treeAlways at the middle of the squarePoints, such as places and drivers. This is the one in the visualizer.
Point quad treeAt the position of a pointPoints; the shape of the tree depends on insert order
Region quad treeA grid of values, split until each part is the sameImages and raster maps
OctreeA cube into 8 cubes3D space

Quad tree vs a fixed grid

Fixed grid: empty cells storeda cell for every tiny square, even empty ones
Quad tree: nodes storedonly where there are points
VisualizerQuad tree: split where it is crowded, skip where it is notSwitch between crowded and evenly spread points. Lower the capacity and watch squares split. Move the green search box and compare the points checked against a full scan.
Where are the points?

Green box = your search. Cyan squares = looked inside. Green dots = found. Crowded areas get small squares, empty areas stay as one big square.

Squares in tree
77
58 leaves, depth 5
Squares visited
34
Points checked
29
of 60 (scan checks all)
Found
27
A big search box touches many squares, so 29 of 60 points were checked. The tree helps most when the search area is small.

A real point-region quad tree: a square splits into 4 equal squares when it holds too many points. To match the finest square of this tree everywhere, a fixed grid would need 1,024 cells. The point sets are fixed (made with a seeded generator), so every visit shows the same data.

07How to Use It / Steps / Implementation

Building and using one

  1. 1
    Start with one square
    The root covers the whole area you care about. Choose a capacity (for example 4 to 16 points).
  2. 2
    Insert a point
    Go down from the root, choosing the child square that contains the point, until you reach a leaf.
  3. 3
    Split when full
    If the leaf now holds more than the capacity, make four children and move the points into them.
  4. 4
    Set a depth limit
    Stop splitting at some depth. Otherwise many points at the same spot would split forever.
  5. 5
    Search a box
    Visit the root. For each node that touches the box, go into its children. Skip the rest.
  6. 6
    Check the points in the leaves
    Test each point in the visited leaves against the box (or the circle), and return those inside.
  7. 7
    Delete or move a point
    Remove it from its leaf. If four sibling leaves become small enough, you can merge them back into one.
💡Keep it in memory
A quad tree is a pointer-based structure, so it is easiest as an in-memory index. For data on disk, systems usually turn squares into keys (like geohash or S2 cells) and use a normal index.
⚠️Many points in the same spot
If hundreds of points share the same coordinates, splitting never separates them. A depth limit (or a rule to allow a bigger leaf) prevents endless splitting.

08Key Terms to Know

TermMeaning in easy words
NodeOne square in the tree
RootThe top square that covers everything
LeafA square that has not split and holds the points
Child / quadrantOne of the four equal parts of a square (NW, NE, SW, SE)
CapacityHow many points a leaf may hold before it splits
DepthHow many splits you passed from the root
Max depthA limit that stops splitting
Range queryFind every point inside a box or circle
Nearest neighbourFind the point closest to a given spot
OctreeThe 3D version, with 8 children per node
PruningSkipping a square because it cannot contain a result

09Pros, Cons and Trade-offs

✅ Pros
  • Adapts to uneven data
  • Fast area search by skipping squares
  • Easy inserts and deletes
  • Simple to understand and code
  • Works for images and 3D (octree) too
⚠️ Cons
  • Can become deep and unbalanced for clustered data
  • Pointer-heavy, so awkward to store on disk
  • Many points at one spot need a depth limit
  • A shape that crosses a boundary is awkward (use an R-tree)
  • Needs rebuilding or tuning if the data drifts a lot

Trade-offs

ChoiceWe gainWe lose
Small capacityFewer points to check per leafA deeper tree with more nodes
Large capacityA small, shallow treeMore points to check in each leaf
High max depthVery fine detail in dense spotsMore memory, risk of long chains
Low max depthBounded size and speedCrowded leaves that are slow to scan
Quad treeAdapts to the data, supports updatesHard to keep on disk
Geohash / fixed gridEasy to store and shardDoes not adapt: busy cells stay busy

10Common Problems and Mistakes

Common mistakes

  1. No depth limit. Duplicate points cause endless splitting and a stack overflow.
  2. Boundary bugs. A point exactly on an edge must go to exactly one child. Pick a rule (for example, “left and top edges belong to the lower child”) and keep it.
  3. Searching a circle with only squares. Use the bounding square to prune, then check the real distance.
  4. Never merging after deletes. The tree keeps tiny empty squares that waste memory and time.
  5. Using it for big shapes. Roads and regions crossing many squares get stored many times. An R-tree fits better.
  6. Moving objects with constant rebuilds. Update the tree in place instead of rebuilding it each tick.

Things to watch

🌳Skewed tree
All points in one corner make a deep, thin branch. Check the depth.
🔁Update cost
Many moving points mean many small tree changes. Batch them if you can.
💽Persistence
Saving a pointer tree to disk is hard. Rebuild on start or use cell keys.
🧵Concurrency
Many threads changing the tree need locks or per-node protection.

11Real-World Examples

🎮Game engines
Quad trees (and octrees in 3D) help find nearby objects for collision checks.
🗺️Map viewers
Show only the points inside the visible map and group dots when zoomed out.
🖼️Image processing
A region quad tree stores flat areas as a single block.
🚕Ride matching in memory
A service can keep nearby drivers in an in-memory tree to find close ones fast.
🌌Physics simulations
Tree structures group faraway bodies to speed up calculations.
🧭Spatial index ideas
Cell-key systems (geohash, S2) follow the same 'split into four' thinking.
📝Note
Which structure a given product uses internally changes between versions. Treat these as typical uses of the idea.
Mini case: show shops on a map
📱Map screenvisible box
→↓range query
🌳Quad treeprune squares
→↓few leaves
🏪Shops in view
Only squares touching the screen are opened.

12Related Topics to Read Next

Geohash→

A grid made from a string, with cells that do not adapt to the data.

R-Trees→

A tree of boxes, better for shapes and for disk storage.

S2 and H3→

Cell systems for the whole Earth, based on repeated splitting.

Indexing→

A spatial index is another way to avoid scanning everything.

B-Trees and B+ Trees→

The disk-friendly tree used for normal columns.

Partitioning→

Splitting space into regions is a form of partitioning.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔What: a tree that splits a square into 4 when it holds too many points.
  • ✔Adapts: dense areas get small squares, empty areas stay big.
  • ✔Search: skip every square that misses the search box, check points in the rest.
  • ✔Knobs: capacity (when to split) and max depth (when to stop).
  • ✔Good for: in-memory points, moving objects, games, map views.
  • ✔Weak at: storing on disk, big shapes across boundaries, heavily clustered data.
  • ✔3D: the same idea with 8 children is an octree.
  • ✔One line: “Keep zooming in, but only where the crowd is.”
← Previous
Geohash
Next →
R-Trees