Intellia Academy

Video lesson

Voronoi Villages Problem: Sort, Simplify, and Find the Smallest Neighborhood

The short answer

The Voronoi villages problem asks you to find the smallest Voronoi region on a number line. Sort the coordinates first, skip the two endpoints because they extend to infinity, then apply one formula: (right neighbour − left neighbour) ÷ 2. Overall time complexity is O(N log N).

Watch the video

The Voronoi villages problem is a classic competitive-programming challenge that turns a real-world idea — every house connects to its nearest cell tower — into a clean algorithmic puzzle on a one-dimensional number line. Nail the three key ideas below and you can solve it in under twenty lines of code.

What Is the Voronoi Villages Problem?

The Voronoi villages problem is a programming task where N villages sit at integer coordinates on a straight road, each village “owns” every point on the road closer to it than to any other village, and your job is to find the size of the smallest such ownership region. A Voronoi diagram is the general 2-D version of this partitioning idea; the 1-D version reduces each region to a simple interval whose boundaries are the midpoints between consecutive villages.

In the canonical version of the problem, five villages sit at coordinates 16, 0, 10, 4, and 15. Coordinates can range from −1,000,000,000 to +1,000,000,000. Your program must output the smallest region size with exactly one decimal place.

Two properties make 1-D Voronoi elegant:

  • Every interior village owns the interval from its left midpoint to its right midpoint.
  • The two endpoint villages own semi-infinite rays, so their regions are always infinite and never the answer.

Why Does Naive Array Mapping Fail on the Voronoi Villages Problem?

A naïve approach to the Voronoi villages problem — allocating one array slot per integer coordinate — crashes immediately because the coordinate range spans two billion positions, which exceeds typical memory limits. When a problem allows coordinates up to ±10⁹, allocating an array of that size will throw a memory limit exceeded error before your logic even runs.

The fix is coordinate compression: store only the values you are actually given. For five villages you need an array of length five, not two billion. This keeps memory O(N) regardless of how spread out the coordinates are. It is the same principle that makes a stack data structure powerful — you work only with the data in front of you, not with empty space you will never touch.

How Does Sorting Transform the Voronoi Villages Problem?

Sorting the input coordinates is the single most important step in the Voronoi villages problem because it converts a chaotic list of positions into an ordered sequence where every village is guaranteed to be adjacent to its true geometric neighbours. Without sorting, a loop over the array would compare non-adjacent villages and produce nonsense midpoints.

Applied to the example:

  1. Raw input: 16, 0, 10, 4, 15
  2. After sorting: 0, 4, 10, 15, 16

Now village 4 sits between 0 and 10, exactly where it belongs on the number line. A single pass from index 1 to index N−2 (skipping the two endpoints) is all you need. The sort costs O(N log N); the subsequent linear scan costs O(N). The sort dominates, so overall complexity is O(N log N).

What Is the Optimised Formula for Each Village’s Region Size?

For any interior village in the sorted array, its Voronoi region size equals half the distance between its right neighbour and its left neighbour, expressed as: size = (right − left) / 2. This single formula replaces the two-step calculation of finding each midpoint separately and then subtracting them.

Here is why the simplification works. The naïve approach computes:

  • Left midpoint: (current + left) / 2
  • Right midpoint: (right + current) / 2
  • Region size: right midpoint − left midpoint

Expand that last step algebraically:

(right + current) / 2 − (current + left) / 2
= (right + current − current − left) / 2
= (right − left) / 2

The village’s own coordinate cancels out perfectly. The formula jumps straight from the left neighbour to the right neighbour, skipping the middle value entirely. This reduces the number of additions and divisions inside your loop — a small but satisfying win.

How Do You Apply the Formula to the Example Coordinates?

Applying the formula to each interior village in the sorted array 0, 4, 10, 15, 16 gives three region sizes, and the smallest is your answer. Walking through each calculation makes the pattern concrete.

Village (current) Left neighbour Right neighbour Calculation Region size
4 0 10 (10 − 0) / 2 5.0
10 4 15 (15 − 4) / 2 5.5
15 10 16 (16 − 10) / 2 3.0

Running minimum after each step: 5.0, still 5.0, then 3.0. The answer is 3.0.

Notice that village 15 sits very close to its right neighbour 16 (gap of only 1) but far from its left neighbour 10 (gap of 6). The tightly packed pair on the right squeezes the region down to 3.0, making 15 the bottleneck.

Why Does Output Formatting Matter in the Voronoi Villages Problem?

Even a mathematically correct answer will be marked wrong in competitive programming if it is not formatted exactly as the problem specifies, and the Voronoi villages problem typically requires exactly one decimal place — so the integer result 3 must be printed as 3.0, not 3 or 3.00. Competitive judges use automated string comparison; a missing decimal point fails every test case.

In Python, use print(f"{answer:.1f}"). In C++, use cout << fixed << setprecision(1) << answer;. This is not pedantry — it is a skill. In our experience teaching competitive programming at Intellia Academy, formatting errors account for a surprising share of preventable wrong-answer verdicts on otherwise perfect solutions.

Formatting discipline applies far beyond this one problem. If you are building broader algorithmic reasoning skills, the Bebras Challenge computational thinking contest is a great place to sharpen attention to precise output constraints.

What Are the Connections to Broader Math and Computer Science Concepts?

The Voronoi villages problem sits at the intersection of computational geometry, sorting algorithms, and algebraic simplification — skills that appear across many academic competitions. Understanding it deeply links to several other ideas worth exploring.

Coordinate compression is a technique used whenever problem constraints give large coordinate ranges but small input sizes. It recurs in range-query problems, sweep-line algorithms, and 2-D grid problems.

Algebraic cancellation — the step where the current village’s coordinate disappeared — is an example of simplifying an expression before coding it. This habit saves bugs and speeds up loops. It parallels the logic of mathematical proofs using necessary vs sufficient conditions, where stripping away redundant structure reveals a cleaner argument.

Infinity as a sentinel is the idea that endpoint regions extend forever, making them automatically ineligible as the minimum. This is a special case of using domain knowledge to prune a search space — a technique central to branch-and-bound and many greedy algorithms.

O(N log N) sorting dominance is a pattern that repeats across problems: when a linear scan follows a sort, the sort always sets the overall complexity ceiling. Recognising this lets you make quick time-complexity claims in competition write-ups.

If you enjoy problems that find hidden structure inside large data sets, you will also appreciate how Ramsey theory guarantees that order always emerges from apparent chaos — a philosophical cousin of the Voronoi idea that structure falls out of proximity relationships.

For students aiming at broader olympiad success, Intellia Academy’s full course catalogue covers computational geometry, algorithms, and contest strategy across disciplines. You can also explore our Olympiad programs for structured paths from beginner to competition-ready.

Full Solution Summary for the Voronoi Villages Problem

Here is the complete algorithm in plain English, ready to translate into any language:

  1. Read the N village coordinates into an array.
  2. Sort the array in ascending order — O(N log N).
  3. Loop from index 1 to N−2 (skip first and last).
  4. Compute size = (arr[i+1] − arr[i−1]) / 2.0.
  5. Track the running minimum across all computed sizes.
  6. Print the minimum with exactly one decimal place.

For the example input (16, 0, 10, 4, 15) the correct output is 3.0.

One edge-case to consider: if N equals 2, there are no interior villages. Both villages are endpoints. Depending on the problem’s guarantee, you may need to handle this separately — check the constraints carefully before submitting.

The CSES Problem Set contains many 1-D geometry and sorting problems that build the same intuitions. Working through them systematically is one of the best ways to internalise the pattern.

Frequently Asked Questions About the Voronoi Villages Problem

Why are the two endpoint villages always skipped?

The leftmost and rightmost villages after sorting have no neighbour on one side, so their Voronoi region extends to negative or positive infinity. An infinite region can never be the smallest, so skipping them is always safe. Trying to calculate a midpoint for a missing neighbour would also cause an array out-of-bounds error.

Does the formula work if two villages share the same coordinate?

If two villages share a coordinate, after sorting they are adjacent with a gap of zero. The formula gives (next − previous) / 2 where the gap between the duplicate pair is 0, yielding a region size of 0.0. Whether that is valid depends on the problem’s input constraints; most versions guarantee distinct coordinates, so check before assuming.

What programming language is best for this problem?

Any language with a built-in sort works. Python’s sorted() and formatted print make it the fastest to write. C++ is preferable when tight time limits apply because its std::sort has lower constant factors. Java works fine with Arrays.sort(). The algorithm itself is language-agnostic — the logic is identical in all three.

Sources

Key takeaways
  • Coordinate compression stores only the given village positions, avoiding the memory crash that comes from allocating an array across a two-billion-integer range.
  • Sorting the coordinates in ascending order is mandatory before any distance calculation; it ensures each village is adjacent to its true geometric neighbours in the array.
  • The key formula simplifies to (right neighbour − left neighbour) / 2 because the current village's coordinate cancels algebraically, removing a redundant arithmetic step inside the loop.
  • The two endpoint villages after sorting always own infinite regions and are never the minimum, so they can be safely skipped without any comparison.
  • Output must be printed with exactly one decimal place (e.g. 3.0, not 3) because competitive judges use exact string matching and a missing decimal fails every test case.
Full video transcript

Look at a map of cell towers. Every house connects to the tower that is physically closest to it. When these physical coverage zones collide, they create rigid mathematical boundaries, called a Voronoi diagram. Today, we are going to solve the classic Voronoi villages programming problem by taking this exact geometric structure and placing it on a one-dimensional straight horizontal road.

The problem gives us a road where five villages are located at specific coordinates: 16, 0, 10, 4, and 15. Our goal is to find the smallest neighborhood size among them. The prompt states these coordinates can fall anywhere from negative 1 billion to positive 1 billion. If you try to map this by creating an array with 2 billion empty slots, your program will crash instantly with a memory limit exceeded error. We only need to store the five specific coordinates provided. By ignoring the empty space on the road, we keep our memory footprint small and our logic focused.

Looking at this diagram, notice the villages on the extreme left and extreme right. There is nothing blocking them on the outside. Their coverage neighborhoods project entirely to infinity. Since our objective is to find the absolute smallest neighborhood, an infinite territory will never be the correct answer. We can safely write off the outer edges and focus our calculations purely on the inner villages.

Our raw data arrives out of order. A loop run now calculates distances between non-neighbors. But whenever handling one-dimensional spatial data, your first step is sorting. The villages snap into ascending order: 0, 4, 10, 15, 16. Now perfectly sandwiched between actual neighbors. With one standard sorting function, the spatial search becomes a linear traversal through an array.

Let's calculate the size for village 4. The standard approach finds the left and right midpoints and subtracts them, yielding 5.0. Now look at these three formulas. Can you combine them algebraically to remove the redundant variable? By combining fractions, we merge the calculations into a single equation. The positive and negative versions of the current village's coordinate perfectly cancel each other out. The process collapses into one elegant formula: the right neighbor minus the left neighbor divided by 2.

Removing the current village from its own calculation reduces the computational work needed inside your loop. Applying our optimized formula to village 10, the logic jumps straight from 4 to 15. 11 divided by 2 is 5.5. Since 5.5 is larger than our current minimum of 5.0, we move to the next village. We test our final village at 15. The right neighbor 16 minus the left neighbor 10 is 6. Divided by 2, we get 3.0. Since 3.0 is smaller than our previous 5.0, the scoreboard updates to our new minimum.

Let's formalize the efficiency. Traversing the array takes O(N) time, but the initial sorting step takes O(N log N). Because the sort is the most intensive operation, our overall time complexity is O(N log N).

Competitive judges are strict about output formatting. Even if your math results in a perfect integer, like 3, the solution will fail if it does not provide exactly one decimal place, 3.0. Solving these challenges comes down to spatial intuition, algebraic simplification, and strict adherence to technical formatting.

IA

Intellia Team

Intellia Team · Intellia Academy

Intellia Team at Intellia Academy — instructors and former olympiad medalists who teach this track and mark real contest papers. All articles

Concepts and lessons, wherever you learn

Deep dives on YouTube, quick concepts on Instagram and X, longer conversations on the podcast.

Subscribe on YouTube

Try a free lesson

No credit card required.

Start free lesson
Scroll to Top