Home › Company-wise questions › Microsoft › Merge Intervals ← Microsoft bank
Microsoft · Question 52 · Arrays
Merge Intervals Arrays Java code ⏱ O(nlogn) 💾 O(n)
Product-based Published and maintained by DSA-topics · Last updated 30 November 2026 · Report an error
About this bank These are classic technical-interview concepts compiled from publicly circulated company-wise question sets, rewritten with original explanations and compiler-ready solutions for educational practice; inclusion does not imply endorsement by the company. Spotted an error? Tell us .
Problem Merge all overlapping intervals.
Approach Sort by start; extend the last merged interval on overlap.
Time O(nlogn)Space O(n)
How it works 1 Sort intervals by start. 2 Overlap extends the last merged interval. 3 Otherwise start a new interval. Sample input / output Input:
4
1 3
2 6
8 10
15 18
Output:
[[1, 6], [8, 10], [15, 18]] Constraints 1 <= intervals.length <= 10^4.
Solution — read it, then walk it Flowchart Pseudocode
Time O(nlogn)Space O(n)Loops 2Branches 2Returns 1source · Java
Scroll sideways for wide charts — the view follows the active step. ⤢ Expand
yes no ↻ repeat START import java.util.* DEFINE class Main DEFINE static int[][] merge(int[][] intervals) Arrays.sort(intervals, (a, b) -> a[0] - b[0]) List<int[]> res = new ArrayList<>() for (int[] interval : intervals) if (res.isEmpty() || res.get(res.size() - 1)[1] < interval[0]) res.add(interval) ELSE res.get(res.size() - 1)[1] = Math.max(res.get(res.size(… RETURN res.toArray(new int[res.size()][]) DEFINE static void main(String[] args) java.util.Scanner sc = new java.util.Scanner(System.in) DEFINE n = sc.nextInt() DEFINE [][] intervals = new int[n][2] for (int i = 0; i < n; i++) { intervals[i][0] = sc.nextInt()… System.out.println(Arrays.deepToString(merge(intervals))) END start / end statement condition loop returns definition← Q51 · Merge Sorted Array Q53 · Kth Largest Element in an Array → Solution code Core logic highlighted in green
Language Python Javasource C++ C Core logic Full code Copy
Recommended resources Affiliate links · may earn us a commission
Classic DSA interview books The reference books interviewers themselves learned from — great next to the visualizers. See the books → Structured coding courses Video courses that pair well with visual practice — pick one language and go deep. Browse courses → Cloud hosting for side projects Ship the portfolio project that gets you hired — free credits for new accounts. Claim credits →