Merging Ranges In C
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Introduction
Merging ranges means combining intervals that overlap, and sometimes intervals that touch, into a smaller set of non-overlapping results. It is a standard algorithm problem because the right solution is simple once the data is sorted, but easy to get subtly wrong if edge cases are ignored.
The Core Idea
Suppose you start with these intervals:
The merged result is:
The usual algorithm is:
- sort by start value
- walk from left to right
- merge into the current interval when overlap exists
- otherwise start a new interval
Without sorting, you cannot reliably know whether the next interval should merge with the current one.
A Clean C++ Implementation
Here is a practical C++ version using a small struct and std::vector:
This code sorts a copy of the input, merges in one pass, and returns the result. The logic is easy to test because each interval is handled exactly once after sorting.
Decide Whether Touching Ranges Should Merge
One subtle design choice is whether adjacent ranges count as mergeable.
For example:
Do these stay separate, or should they become [1, 5] because they touch conceptually in your domain
The answer depends on the rules of the problem. The earlier condition:
merges only true overlap. If you want to merge touching integer ranges too, you might use:
That one-character change affects the meaning of the whole algorithm, so it should be deliberate.
Complexity
The time cost is dominated by sorting:
- sorting takes
O(n log n) - the merge scan takes
O(n)
So the total time is O(n log n), and the extra output storage is O(n) in the worst case if nothing merges.
That is already optimal for an unsorted input list in ordinary comparison-based code.
Why Sorting First Is Better Than Pairwise Checking
Beginners sometimes try every interval against every other interval. That approach becomes messy and inefficient because merging one pair can create new overlap with a third interval, which then forces another pass.
Sorting avoids that problem. Once intervals are ordered by start value, you only need to compare the current interval with the last merged result.
That is why this problem is really more about ordering than about clever nested conditionals.
Common Pitfalls
- Forgetting to sort first, which makes the one-pass merge logic unreliable.
- Using the wrong overlap rule for the domain, especially when touching ranges may or may not count as merged.
- Failing to update the merged end with
std::max, which can shrink a range incorrectly. - Not handling empty input before reading
ranges[0]. - Mutating the caller's original vector unexpectedly when the function should operate on a copy.
Summary
- Merging ranges is usually solved by sorting intervals and then scanning once from left to right.
- After sorting, each new range either extends the current merged interval or starts a new one.
- The overlap condition defines the business rule, especially for touching ranges.
- The standard solution runs in
O(n log n)time because sorting dominates. - Most bugs come from skipped sorting, wrong overlap logic, or weak edge-case handling.
Related reading
- Merging two sorted linked lists
- metaphone versus soundex versus NYSIIS
- Method to detect intersection between a rectangle and a polygon?
- Millions of 3D points How to find the 10 of them closest to a given point?
- Method to measure P-Scalability in Distributed Systems
- MethodImplAggressiveInlining - how aggressive is it?
- Modifying the Caffe C prediction code for multiple inputs
- modular multiplication of large numbers in c

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.