java
22 lines · 7 steps
Merging overlapping intervals in Java
Sort intervals by start, then sweep once, extending or opening ranges as you go.
Explained by
highlit
1public List<int[]> merge(int[][] intervals) {
2 if (intervals.length == 0) {
3 return new ArrayList<>();
4 }
5
6 Arrays.sort(intervals, Comparator.comparingInt(interval -> interval[0]));
7
8 List<int[]> merged = new ArrayList<>();
9 int[] current = intervals[0].clone();
10 merged.add(current);
11
12 for (int[] interval : intervals) {
13 if (interval[0] <= current[1]) {
14 current[1] = Math.max(current[1], interval[1]);
15 } else {
16 current = interval.clone();
17 merged.add(current);
18 }
19 }
20
21 return merged;
22}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Sorting by start makes overlaps detectable with a single left-to-right pass.
- 2Overlap means the next start is within the current range's end, so extend rather than append.
- 3Cloning the interval you add lets you mutate the running range without corrupting the input.
Related explainers
php
<?php class NameParser {
Parsing a full name into components in PHP
string-parsing
arrays
normalization
Intermediate
8 steps
java
@Component @Converter public class EncryptedStringConverter implements AttributeConverter<String, String> {
Transparent column encryption in Spring & JPA
encryption
aes-gcm
jpa-converter
Advanced
10 steps
java
package com.acme.billing.config; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.ConfigurationProperties;
Feature-flagged beans with Spring @ConditionalOnProperty
feature-flags
conditional-beans
strategy-pattern
Intermediate
5 steps
java
public static Map<String, String> parseCookieHeader(String header) { Map<String, String> cookies = new LinkedHashMap<>(); if (header == null || header.isBlank()) { return cookies;
Parsing an HTTP Cookie header in Java
string-parsing
http
url-decoding
Intermediate
6 steps
java
public class TimedSocketReader { private static final int READ_TIMEOUT_MS = 5_000; private static final int CONNECT_TIMEOUT_MS = 3_000;
Reading a socket with connect and read timeouts
sockets
timeouts
io
Intermediate
8 steps
python
import re from functools import total_ordering from typing import Optional
Parsing and comparing semantic versions
regex
operator-overloading
sorting
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/merging-overlapping-intervals-in-java-explained-java-c606/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.