DOJ logoDOJ
Problems
Recently added problemsSaved problemsWorkbooks
CategoriesDLCContestsGroupsTeamsBoard
Ranking
Solved Problem RankingStreak rankingDOJ Power ranking
Status
Call for TasksLoginRegister
DOJ logoDOJ

Community online judge with OI-style subtask scoring, Elo ratings, and Discord account linking.

Problems
ProblemsCategories
Community
ContestsRankingBoardNoticesHost an external contestGuide
Account
LoginRegisterJudge Status
Policy
Terms of ServiceDLC RulesPrivacyAPI documentationLanguage runtimesContest rank rewardsRating and performance
© 2026 DOJ
All rights reserved
Editorial

Merging Intervals

Back to problem

Editorial

Suppose an interval is completely contained in another interval. For any third interval, replacing the contained interval by the containing interval cannot decrease the length of the union. Therefore, contained intervals can be removed when searching for an optimum.

Sort the intervals by increasing lll, and for equal lll by decreasing rrr. Scan from left to right and remove every interval whose rrr is not larger than the maximum rrr seen so far. Let the remaining intervals be

[l1,r1],[l2,r2],⋯ ,[lM,rM].[l_1,r_1],[l_2,r_2],\cdots,[l_M,r_M].[l1​,r1​],[l

Then

l1<l2<⋯<lM,r1<r2<⋯<rM.l_1<l_2<\cdots<l_M,\qquad r_1<r_2<\cdots<r_M.l1​<l2​<⋯<

Initialize the answer with the maximum length of any original interval. This also handles the case where every other interval is contained in one interval.

Now fix the right interval jjj. Maintain with a two-pointer scan the boundary between earlier intervals satisfying ri<ljr_i<l_jri​<lj​ and those satisfying ri≥ljr_i\geq l_j.

If ri<ljr_i<l_jri​<lj​, interval iii is disjoint from interval jjj, so the union length is

(ri−li)+(rj−lj).(r_i-l_i)+(r_j-l_j).(ri​−li​)+(r

With a prefix maximum of interval lengths, the best value of this form is available immediately.

If ri≥ljr_i\geq l_jri​≥lj​, the two intervals overlap or touch. Since the right endpoints of the remaining intervals are strictly increasing, ri<rjr_i<r_jr, so their union is

[li,rj].[l_i,r_j].[li​,rj​].

Thus, among all such iii, the best choice is the earliest one, which has the smallest lil_ili​.

Sorting takes O(Nlog⁡N)O(N\log N)O(NlogN) time, and the filtering, prefix preprocessing, and two-pointer scan take O(N)O(N)O(N) time. The total time complexity is O(Nlog⁡N)O(N\log N)O(NlogN).

Every interval lies inside [0,109][0,10^9][0,109], so the union of any two intervals also lies inside this range. Therefore, the answer is at most 10910^9109 and always fits in a signed 64-bit integer.

Solution written by GPT5.6

2
​
,
r2​
]
,
⋯
,
[
lM​
,
rM​
]
.
lM​
,
r1​
<
r2​<
⋯<
rM​.
ri​≥lj​
j
​
−
lj​).
i
​
<
rj​