Skip to the code
cf.
+25 XP

#582 Merge Highlighted Text Ranges

medium

A document editor stores each highlight as [start, end], the first and last character index it covers (both included). Users can highlight the same text more than once, so the ranges overlap and come in any order.

Write mergeHighlights(ranges) that joins every group of ranges that overlap or share a character index into one range, and returns the joined ranges sorted by start. Ranges that only sit next to each other without sharing an index, like [1, 3] and [4, 6], stay separate, because the editor draws them as two highlights.

Example 1

Input: ranges = [[8,10],[1,3],[2,6],[15,18]]
Output: [[1,6],[8,10],[15,18]]

[1, 3] and [2, 6] overlap and become [1, 6].

Example 2

Input: ranges = [[1,4],[4,5]]
Output: [[1,5]]

They share character 4.

Constraints

  • 0 <= ranges.length <= 100000
  • 0 <= start <= end <= 10^6
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).