# Merge Overlapping Intervals

* N, 1

```jsx
function mergeOverlappingIntervals(arr) {
  const answer = [];

  arr.sort((a, b) => a[0] - b[0]);

  let range = arr[0];
  for (let i = 1; i < arr.length; i++) {
    const [x1, x2] = range;
    const [y1, y2] = arr[i];

    // -----
    //        ------
    if (x2 < y1) {
      answer.push(range);
      range = arr[i];
      continue;
    }

    // -----
    //  ---
    //     -----
    //   -----
    if (x1 <= y1 && x2 >= y1) {
      range = [x1, Math.max(x2, y2)];
    }
    
  }

  // push last range
  answer.push(range);
  
  return answer;
}

// Do not edit the line below.
exports.mergeOverlappingIntervals = mergeOverlappingIntervals;
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://algorithm.prettylog.com/algorithm-problems/algoexpert/medium/merge-overlapping-intervals.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
