{"id":10077,"date":"2025-09-18T14:17:39","date_gmt":"2025-09-18T08:47:39","guid":{"rendered":"https:\/\/namastedev.com\/blog\/?p=10077"},"modified":"2025-09-19T20:27:02","modified_gmt":"2025-09-19T14:57:02","slug":"insert-interval","status":"publish","type":"post","link":"https:\/\/namastedev.com\/blog\/insert-interval\/","title":{"rendered":"Insert Interval"},"content":{"rendered":"\n<!-- Insert_6 -->\n<!-- PrismJS for Syntax Highlighting -->\n<link href=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/themes\/prism-tomorrow.min.css\" rel=\"stylesheet\">\n<script src=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/prism.min.js\"><\/script>\n<script src=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/plugins\/autoloader\/prism-autoloader.min.js\"><\/script>\n\n<style>\n.wp_blog_theme {\n  --primary: #E58C32;\n  --secondary: #030302;\n  --light-bg: #fef9f4;\n  --text-dark: #2d2d2d;\n  --tab-radius: 12px;\n  --shadow: 0 4px 12px rgba(0, 0, 0, 0.08);\n  --code-bg: #001f3f;\n  --code-text: #d4f1ff;\n}\n\n.wp_blog_container {\n  font-family: 'Segoe UI', sans-serif;\n  background: var(--light-bg);\n  margin: 0;\n  padding: 0;\n  color: var(--text-dark);\n}\n\n\/* Heading *\/\n.wp_blog_main-heading {\n  text-align: center;\n  font-size: 2.4rem;\n  color: var(--primary);\n  margin-top: 2.5rem;\n  font-weight: bold;\n}\n\n\/* Explanation Card *\/\n.wp_blog_explanation,\n.wp_blog_code-tabs-container {\n  max-width: 940px;\n  margin: 2rem auto;\n  padding: 2rem;\n  background: white;\n  border-radius: var(--tab-radius);\n  box-shadow: var(--shadow);\n}\n\n\/* Text and Visuals *\/\n.wp_blog_explanation h2 {\n  font-size: 1.4rem;\n  color: var(--primary);\n  margin-bottom: 0.5rem;\n}\n\n.wp_blog_explanation p,\n.wp_blog_explanation li {\n  font-size: 1.05rem;\n  line-height: 1.7;\n  margin: 0.5rem 0;\n}\n\n.wp_blog_explanation code {\n  background: #fef9f4;   \/* light bg instead of dark blue *\/\n  color: #E58C32;        \/* brand orange *\/\n  padding: 3px 6px;\n  border-radius: 4px;\n  font-family: 'Courier New', monospace;\n  font-weight: 600;      \/* optional, makes it pop *\/\n}\n\n.wp_blog_explanation img {\n  max-width: 100%;\n  border-radius: var(--tab-radius);\n  margin-top: 1rem;\n  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);\n}\n\n\/* Tab Buttons *\/\n.wp_blog_code-tabs-header {\n  display: flex;\n  flex-wrap: wrap;\n  gap: 0.5rem;\n  margin-bottom: 1rem;\n}\n\n.wp_blog_code-tab-button {\n  padding: 0.6rem 1.2rem;\n  border: 1px solid var(--primary);\n  background: white;\n  color: var(--primary);\n  border-radius: 50px;\n  font-weight: 600;\n  cursor: pointer;\n  transition: all 0.3s ease;\n}\n\n.wp_blog_code-tab-button:hover {\n  background: var(--secondary);\n}\n\n.wp_blog_code-tab-button.active {\n  background: var(--primary);\n  color: white;\n}\n\n\/* Code Content *\/\n.wp_blog_code-tab-content {\n  display: none;\n  background: var(--code-bg);\n  border-radius: var(--tab-radius);\n}\n\n.wp_blog_code-tab-content.active {\n  display: block;\n}\n\n.wp_blog_code-tab-content pre {\n  margin: 0;\n  padding: 1.5rem;\n  font-size: 1rem;\n  overflow-x: auto;\n  background: var(--code-bg);\n  border-radius: var(--tab-radius);\n  color: var(--code-text);\n}\n\n\/* Dark mode variables *\/\n.wp_blog_theme.dark-mode {\n  --light-bg: #121212;\n  --text-dark: #f5f5f5;\n  --shadow: 0 4px 12px rgba(255, 255, 255, 0.08);\n  --code-bg: #1e1e1e;\n  --code-text: #c5f0ff;\n}\n\n.wp_blog_theme.dark-mode .wp_blog_explanation {\n  background: #1e1e1e;\n}\n\n\/* Dark mode code highlight *\/\n.wp_blog_theme.dark-mode .wp_blog_explanation code {\n  background: #333;\n  color: #ffd27f;\n}\n\n.wp_blog_theme {\n  position: relative; \/* makes it the reference for absolute children *\/\n}\n\n.wp_blog_toggle-btn {\n  position: absolute;\n  top: 1rem;\n  right: 1rem;\n  z-index: 9999;\n  padding: 0.5rem 0.8rem;\n  border-radius: 10%;\n  background: var(--primary);\n  color: white;\n  font-weight: bold;\n  cursor: pointer;\n  border: none;\n  box-shadow: var(--shadow);\n  transition: background 0.3s, transform 0.2s;\n}\n\n.wp_blog_toggle-btn:hover {\n  background: #cc772e;\n}\n\n.wp_blog_theme.dark-mode .wp_blog_code-tabs-container {\n  background: #1e1e1e;\n}\n<\/style>\n\n<div class=\"wp_blog_container wp_blog_theme\">\n  <button id=\"blogNotesThemeToggle\" class=\"wp_blog_toggle-btn\">\ud83c\udf19<\/button>\n  <h1 class=\"wp_blog_main-heading\"><\/h1>\n\n  <div class=\"wp_blog_explanation\">\n    <h2>Problem Statement:<\/h2>\n    <p>\n        You are given an array of non-overlapping intervals <code>intervals<\/code> where <code>intervals[i] = [start<sub>i<\/sub>, end<sub>i<\/sub>]<\/code> represent the start and the end of the ith interval and intervals is sorted in ascending order by <code>start<sub>i<\/sub><\/code>. You are also given an interval <code>newInterval = [start, end]<\/code> that represents the start and end of another interval.\n    <\/p>\n\n    <p>\n        Insert <code>newInterval<\/code> into <code>intervals<\/code> such that <code>intervals<\/code> is still sorted in ascending order by <code>start<sub>i<\/sub><\/code> and <code>intervals<\/code> still does not have any overlapping intervals (merge overlapping intervals if necessary).\n    <\/p>\n\n    <p>\n        Return <code>intervals<\/code> after the insertion.\n    <\/p>\n\n    <p>\n        <strong>Note:<\/strong> that you don&#8217;t need to modify <code>intervals<\/code> in-place. You can make a new array and return it.\n    <\/p>\n    <h3>Example 1:<\/h2>\n    <p><strong>Input:<\/strong> intervals = [[1,3],[6,9]], newInterval = [2,5]\n<\/p>\n    <p><strong>Output:<\/strong> [[1,5],[6,9]]<\/p>\n    <p><strong>Explanation:<\/strong>\n        Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.\n        Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.\n        Total profit is 4 + 3 = 7.\n    <\/p>\n\n    <h3>Example 2:<\/h3>\n    <p><strong>Input: <\/strong>intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]<\/p>\n    <p><strong>Output: <\/strong>[[1,2],[3,10],[12,16]]<\/p>\n    <p><strong>Explanation: <\/strong>\n        Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10].\n    <\/p>\n\n    <h3>Constraints<\/h3>\n    <ul>\n        <li><code>0 <= intervals.length <= 3 * 10<sup>4<\/sup><\/code><\/li>\n        <li><code>intervals[i].length == 2<\/code><\/li>\n        <li><code>0 <= start<sub>i<\/sub> <= end<sub>i<\/sub> <= 10<sup>5<\/sup><\/code><\/li>\n        <li><code>intervals<\/code> is sorted by <code>start<sub>i<\/sub> in <strong>ascending<\/strong> order.<\/code><\/li>\n        <li><code>newInterval.length == 2<\/code><\/li>\n        <li><code>0 <= start <= end <= 10<sup>5<\/sup><\/code><\/li>\n    <\/ul>\n<h2>Approach:<\/h2>\n   <ul>\n        <li><code>Add intervals before x<\/code> Push all <code>intervals<\/code> ending before x starts (i.e., arr[i][1] < x[0]).<\/li>\n        <li>Merge overlapping intervals with x: While intervals overlap <code>(arr[i][0] <= x[1])<\/code>, expand x by updating:<\/li>\n        <code>\n            <ul>\n                <li>x[0] = min(x[0], arr[i][0])<\/li>\n                <li>x[1] = max(x[1], arr[i][1])<\/li>\n            <\/ul>\n        <\/code>\n        <li><code>Insert<\/code> merged interval x: Push the merged interval into result.<\/li>\n        <li>Add remaining intervals: Push all <code>intervals<\/code> that come after x.<\/li>\n<\/ul>\n\n    <h2>Time & Space Complexity:<\/h2>\n    <p><strong>Time Complexity:<\/strong> <code>O(n)<\/code><\/p>\n    <p><strong>Space Complexity:<\/strong> <code>O(n)<\/code><\/p>\n\nInput: arr = [[1,3],[6,9]], x = [2,5]\n<h2>Dry Run<\/h2> <div style=\"background: var(--light-bg); border-left: 4px solid var(--primary); padding: 1rem; border-radius: var(--tab-radius); margin: 1rem 0; color: var(--text-dark);\"> \n    \n    <p><strong>Input:<\/strong> <code>arr = [[1,3],[6,9]], x = [2,5]<\/code><\/p> \n    <pre style=\"white-space: pre-wrap; background: var(--code-bg); padding: 1rem; border-radius: 8px; overflow-x: auto; color: var(--code-text);\">\nStep 0: Start  \n  - Function: insert(arr, x)  \n  - arr = [[1,3], [6,9]]  \n  - x   = [2,5]  \n  - n   = arr.length = 2  \n  - ans = []  \n  - i   = 0  \n\nStep 1: First while loop \u2192 while (i < n &#038;&#038; arr[i][1] < x[0])  \n  - arr[0][1] = 3, x[0] = 2  \n  - Check: 3 < 2 ? \u2192 false  \n\u2192 Exit first while (no intervals added)  \n\nState after Step 1:  \n  - ans = []  \n  - i   = 0  \n  - x   = [2,5]  \n\nStep 2: Second while loop \u2192 while (i < n &#038;&#038; arr[i][0] <= x[1])  \n  Iteration 1 (i = 0):  \n    - arr[0] = [1,3]  \n    - Check: 1 <= 5 ? \u2192 true (overlap)  \n    - Update x:  \n        x[0] = min(2,1) = 1  \n        x[1] = max(5,3) = 5  \n    - New x = [1,5]  \n    - i = 1  \n\n  Iteration 2 (i = 1):  \n    - arr[1][0] = 6, x[1] = 5  \n    - Check: 6 <= 5 ? \u2192 false  \n\u2192 Exit second while  \n\nState after Step 2:  \n  - ans = []  \n  - i   = 1  \n  - x   = [1,5]  \n\nStep 3: Push merged x  \n  - ans.push(x) \u2192 ans = [[1,5]]  \n\nStep 4: Third while loop \u2192 while (i < n)  \n  Iteration 1 (i = 1):  \n    - ans.push(arr[1]) \u2192 ans = [[1,5], [6,9]]  \n    - i = 2  \n\n  i = 2 == n \u2192 loop ends  \n\nStep 5: End  \n  - Final ans = [[1,5], [6,9]]  \n\nExplanation:  \n  - Interval [1,3] overlapped with x = [2,5], merged into [1,5].  \n  - Interval [6,9] didn\u2019t overlap, so kept as is.          \n        <\/pre> <p><strong>Output:<\/strong> <code>[[1,5],[6,9]]<\/code><\/p> <\/div>\n\n<\/div>\n  <div class=\"wp_blog_code-tabs-container\">\n    <div class=\"wp_blog_code-tabs-header\">\n      <button class=\"wp_blog_code-tab-button active\" data-lang=\"js\">JavaScript<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"py\">Python<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"java\">Java<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"cpp\">C++<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"c\">C<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"cs\">C#<\/button>\n    <\/div>\n\n    <div class=\"wp_blog_code-tab-content active\" data-lang=\"js\">\n      <pre><code class=\"language-javascript\">\nvar insert = function(arr, x) {\n    let n = arr.length;\n    let ans = [];\n\n    let i = 0;\n    while(i < n &#038;&#038; arr[i][1] < x[0]) {\n        ans.push(arr[i]);\n        ++i;\n    } \n\n    while(i < n &#038;&#038; arr[i][0] <= x[1]){\n        x[0] = Math.min(x[0], arr[i][0]);\n        x[1] = Math.max(x[1], arr[i][1]);\n        ++i;\n    }\n    ans.push(x);\n\n    while(i < n){\n        ans.push(arr[i]);\n        ++i;\n    }\n    return ans;\n};\n<\/code><\/pre>\n    <\/div>\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"py\">\n      <pre><code class=\"language-python\">\ndef insert(arr, x):\n    \"\"\"\n    arr: list of [start, end], sorted and non-overlapping\n    x: [start, end]\n    returns: new list of intervals after inserting x\n    \"\"\"\n    n = len(arr)\n    ans = []\n    i = 0\n    while i < n and arr[i][1] < x[0]:\n        ans.append(arr[i])\n        i += 1\n    while i < n and arr[i][0] <= x[1]:\n        x[0] = min(x[0], arr[i][0])\n        x[1] = max(x[1], arr[i][1])\n        i += 1\n    ans.append(x)\n    while i < n:\n        ans.append(arr[i])\n        i += 1\n    return ans\n      <\/code><\/pre>\n    <\/div>\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"java\">\n      <pre><code class=\"language-java\">\nimport java.util.*;\npublic class Intervals {\n    public static List<int[]> insert(List<int[]> arr, int[] x) {\n        int n = arr.size();\n        List<int[]> ans = new ArrayList<>();\n        int i = 0;\n        while (i < n &#038;&#038; arr.get(i)[1] < x[0]) {\n            ans.add(arr.get(i));\n            ++i;\n        }\n        while (i < n &#038;&#038; arr.get(i)[0] <= x[1]) {\n            x[0] = Math.min(x[0], arr.get(i)[0]);\n            x[1] = Math.max(x[1], arr.get(i)[1]);\n            ++i;\n        }\n        ans.add(new int[]{x[0], x[1]});\n        while (i < n) {\n            ans.add(arr.get(i));\n            ++i;\n        }\n        return ans;\n    }\n}\n    <\/code><\/pre>\n    <\/div>\n\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"cpp\">\n      <pre><code class=\"language-cpp\">\n#include &lt;vector&gt;\n#include &lt;algorithm&gt;\nusing namespace std;\n\nvector<vector<int>> insertInterval(const vector<vector<int>>& arr, vector<int> x) {\n    int n = arr.size();\n    vector<vector<int>> ans;\n    int i = 0;\n    while (i < n &#038;&#038; arr[i][1] < x[0]) {\n        ans.push_back(arr[i]);\n        ++i;\n    }\n    while (i < n &#038;&#038; arr[i][0] <= x[1]) {\n        x[0] = min(x[0], arr[i][0]);\n        x[1] = max(x[1], arr[i][1]);\n        ++i;\n    }\n    ans.push_back(x);\n    while (i < n) {\n        ans.push_back(arr[i]);\n        ++i;\n    }\n    return ans;\n}\n<\/code><\/pre>\n    <\/div>\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"c\">\n      <pre><code class=\"language-c\">\n#include &lt;stdlib.h&gt;\n#include &lt;stdio.h&gt;\ntypedef struct {\n    int start;\n    int end;\n} Interval;\n\/\/ arr: pointer to an array of Interval of length n\n\/\/ x: interval to insert\n\/\/ returns: newly allocated array of Interval; out_len set to resulting length\nInterval* insertInterval(const Interval* arr, int n, Interval x, int* out_len) {\n    \/\/ allocate space for at most n+1 intervals\n    Interval* ans = (Interval*)malloc((n + 1) * sizeof(Interval));\n    int idx = 0;\n    int i = 0;\n    while (i < n &#038;&#038; arr[i].end < x.start) {\n        ans[idx++] = arr[i];\n        ++i;\n    }\n    while (i < n &#038;&#038; arr[i].start <= x.end) {\n        if (arr[i].start < x.start) x.start = arr[i].start;\n        if (arr[i].end > x.end)   x.end = arr[i].end;\n        ++i;\n    }\n    ans[idx++] = x;\n    while (i < n) {\n        ans[idx++] = arr[i];\n        ++i;\n    }\n    ans = (Interval*)realloc(ans, idx * sizeof(Interval));\n    *out_len = idx;\n    return ans;\n}\n    <\/code><\/pre>\n    <\/div>\n\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"cs\">\n      <pre><code class=\"language-csharp\">\nusing System;\nusing System.Collections.Generic;\npublic class Intervals {\n    \/\/ arr: List<int[]> where each int[] is {start, end}\n    public static List<int[]> Insert(List<int[]> arr, int[] x) {\n        int n = arr.Count;\n        List<int[]> ans = new List<int[]>();\n        int i = 0;\n        while (i < n &#038;&#038; arr[i][1] < x[0]) {\n            ans.Add(arr[i]);\n            ++i;\n        }\n        while (i < n &#038;&#038; arr[i][0] <= x[1]) {\n            x[0] = Math.Min(x[0], arr[i][0]);\n            x[1] = Math.Max(x[1], arr[i][1]);\n            ++i;\n        }\n        ans.Add(new int[]{x[0], x[1]});\n        while (i < n) {\n            ans.Add(arr[i]);\n            ++i;\n        }\n        return ans;\n    }\n}\n      <\/code><\/pre>\n    <\/div>\n  <\/div>\n<\/div>\n\n<script>\ndocument.addEventListener(\"DOMContentLoaded\", () => {\n  const buttons = document.querySelectorAll(\".wp_blog_code-tab-button\");\n  const contents = document.querySelectorAll(\".wp_blog_code-tab-content\");\n\n  buttons.forEach((button) => {\n    button.addEventListener(\"click\", () => {\n      const lang = button.getAttribute(\"data-lang\");\n\n      buttons.forEach((btn) => btn.classList.remove(\"active\"));\n      contents.forEach((content) => content.classList.remove(\"active\"));\n\n      button.classList.add(\"active\");\n      document\n        .querySelector(`.wp_blog_code-tab-content[data-lang=\"${lang}\"]`)\n        .classList.add(\"active\");\n    });\n  });\n\n  const themeToggle = document.getElementById(\"blogNotesThemeToggle\");\n  const themeContainer = document.querySelector(\".wp_blog_theme\");\n\n  themeToggle.addEventListener(\"click\", () => {\n    themeContainer.classList.toggle(\"dark-mode\");\n    themeToggle.textContent =\n      themeContainer.classList.contains(\"dark-mode\") ? \"\u2600\ufe0f\" : \"\ud83c\udf19\";\n  });\n});\n<\/script>\n","protected":false},"excerpt":{"rendered":"<p>\ud83c\udf19 Problem Statement: You are given an array of non-overlapping intervals intervals where intervals[i] = [starti, endi] represent the start and the end of the ith interval and intervals is sorted in ascending order by starti. You are also given an interval newInterval = [start, end] that represents the start and end of another interval.<\/p>\n","protected":false},"author":108,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[210,322,260,176,175,211,811,810,174,172,173],"tags":[],"class_list":{"0":"post-10077","1":"post","2":"type-post","3":"status-publish","4":"format-standard","6":"category-algorithms","7":"category-algorithms-and-data-structures","8":"category-c-c-plus-plus","9":"category-csharp","10":"category-cplusplus","11":"category-data-structures","12":"category-data-structures-and-algorithms","13":"category-dsa","14":"category-java","15":"category-javascript","16":"category-python"},"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/10077","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/users\/108"}],"replies":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/comments?post=10077"}],"version-history":[{"count":2,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/10077\/revisions"}],"predecessor-version":[{"id":10082,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/10077\/revisions\/10082"}],"wp:attachment":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/media?parent=10077"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/categories?post=10077"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/tags?post=10077"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}