Back to track
#46 Medium Intermediate

Merge Intervals

Open the editor

Problem

Merge overlapping intervals.

Constraints

1 <= N <= 200000

Hints

  1. 1

    Sort by start

  2. 2

    Scan and merge

Worked solution

Reference solution

One correct implementation. Alternative approaches that satisfy the constraints are equally valid — the reviewer judges behaviour, not style.

#include <bits/stdc++.h>
using namespace std;

int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);

  int n; cin >> n;
  vector<pair<int,int>> intervals(n);
  for (int i = 0; i < n; i++) cin >> intervals[i].first >> intervals[i].second;
  sort(intervals.begin(), intervals.end());
  vector<pair<int,int>> merged;
  for (auto& in : intervals) {
    if (merged.empty() || merged.back().second < in.first) merged.push_back(in);
    else merged.back().second = max(merged.back().second, in.second);
  }
  for (auto& p : merged) cout << p.first << " " << p.second << '\n';
  return 0;
}

© 2026 ChitChat