← Accenture bank

Accenture · Question 9 · Arrays

Insert Interval

ArraysC++code⏱ O(n)💾 O(n)
Service-based

Problem

Insert a new interval into a sorted list of non - overlapping intervals and merge if necessary.

Approach

Add intervals before new interval, merge overlapping, add remaining intervals.

Time O(n)Space O(n)

How it works

  1. 1Copy intervals fully before the new one.
  2. 2Merge every overlap into it.
  3. 3Append it and the rest.

Sample input / output

Input:
intervals = [[1, 3], [6, 9]], newInterval = [2, 5]
Output:
[[1, 5], [6, 9]]

Constraints

0 <= intervals.length <= 10^4; non-overlapping sorted input.

Solution — read it, then walk it

Time O(n)Space O(n)Loops 1Branches 1Returns 1source · C++
Scroll sideways for wide charts — the view follows the active step.
↻ repeatSTARTinclude <iostream>include <vector>include <algorithm>using namespace stdvector<vector<int>>insert(vector<vector<int>>&intervals, vector<int>…DEFINE printMat(constvector<vector<int>>& m)cout << "["for (size_t i = 0; i <m.size(); ++i)if (i) cout << ", "cout << "[" << m[i][0] <<", " << m[i][1] << "]"cout << "]" << endlDEFINE main()vector<vector<int>>intervals = {{1, 3}, {6,9}}vector<int> ni = {2, 5}printMat(insert(intervals,ni))RETURN 0END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/17

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits