דילוג לתוכן הראשי
64

Insert Interval

בינוניintervals

הקוד שלכם עדיין לא נשמר: רענון או יציאה מהדף מאפסים אותו. שמירת התקדמות תגיע יחד עם חשבונות משתמשים.

התרגיל הזה משתמש ב:Intervalsקראו את המדריך למתחילים

נתונה לכם רשימה של אינטרוולים לא חופפים intervals, ממוינת לפי התחלה, ועוד אינטרוול אחד newInterval.

הכניסו את newInterval כך שהרשימה תישאר ממוינת ולא חופפת, ומזגו אותו עם כל אינטרוול שהוא חופף או נוגע בו. החזירו את הרשימה שמתקבלת.

הבנת הבעיה

  • אינטרוול [start, end] הוא טווח של מספרים מ-start עד end.
  • מיזוג (merge) של שני אינטרוולים חופפים אומר להחליף אותם באינטרוול אחד שמכסה את שניהם: [1, 3] ו-[2, 5] הופכים ל-[1, 5].
  • בבעיה הזו, גם אינטרוולים שנוגעים (כמו [1, 5] ו-[5, 7]) ממוזגים.
  • רשימת הקלט כבר ממוינת ואין בה חפיפות. רק newInterval יכול לגרום לחפיפות.

דוגמה 1

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

[2, 5] חופף ל-[1, 3], אז הם ממוזגים ל-[1, 5].

דוגמה 2

text
Input:  intervals = [[1, 2], [3, 5], [6, 7], [8, 10], [12, 16]], newInterval = [4, 8]
Output: [[1, 2], [3, 10], [12, 16]]

[4, 8] חופף ל-[3, 5], ל-[6, 7] ונוגע ב-[8, 10]: כל הארבעה ממוזגים ל-[3, 10].

דוגמה 3

text
Input:  intervals = [], newInterval = [5, 7]
Output: [[5, 7]]

אילוצים

  • 0 <= intervals.length <= 10^4
  • 0 <= start <= end <= 10^5

רמזים

נתקעתם? פתחו רמז אחד בכל פעם. כל רמז מגלה קצת יותר מהקודם.

    הרעיון במשפט אחד

    עוברים פעם אחת על הרשימה הממוינת: מעתיקים את האינטרוולים שבאים לגמרי לפני החדש, בולעים את אלה שחופפים לו על ידי הרחבה שלו, מוסיפים אותו, ואז מעתיקים את השאר.

    הגישה הנאיבית

    מוסיפים את newInterval ומריצים את Merge Intervals: ממיינים וממזגים. זה נכון, אבל מיון עולה O(n log n), והרשימה כבר הייתה ממוינת. אפשר יותר טוב.

    התובנה המרכזית: שלוש קבוצות, לפי הסדר

    כיוון שהרשימה ממוינת ואין בה חפיפות, כל אינטרוול נופל לאחת משלוש קבוצות ביחס ל-newInterval, והקבוצות מופיעות בסדר הזה:

    1. לגמרי לפניו: האינטרוול נגמר לפני ש-newInterval מתחיל (end < newStart). מעתיקים אותו בלי שינוי.

    2. חופף לו: האינטרוול מתחיל לפני הסוף של newInterval או בדיוק בו (start <= newEnd). ממזגים אותו על ידי הרחבה של newInterval:

      • newStart = min(newStart, start)
      • newEnd = max(newEnd, end)

      כשהקבוצה הזו נגמרת, מוסיפים את newInterval המורחב פעם אחת.

    3. לגמרי אחריו: כל השאר. מעתיקים בלי שינוי.

    text
    number line:  1  2  3  4  5  6  7  8  9  10  11  12 ... 16
    existing:    [1-2] [3--5] [6-7] [8---10]       [12 ----- 16]
    new:                  [4---------8]
    result:      [1-2] [3--------------10]         [12 ----- 16]

    צעד אחר צעד

    intervals = [[1, 2], [3, 5], [6, 7], [8, 10], [12, 16]], newInterval = [4, 8]:

    אינטרוולבדיקהקבוצהnewInterval אחריהתוצאה עד עכשיו
    [1, 2]2 < 4: נגמר לפנילפני[4, 8][1, 2]
    [3, 5]3 <= 8: חופףמיזוג[3, 8][1, 2]
    [6, 7]6 <= 8: חופףמיזוג[3, 8][1, 2]
    [8, 10]8 <= 8: נוגעמיזוג[3, 10][1, 2]
    [12, 16]12 > 10: מפסיקים למזגאחרימוסיפים [3, 10][1, 2], [3, 10]
    מעתיקים את השאר[1, 2], [3, 10], [12, 16]

    הקוד

    הפתרון לדוגמה מופיע למטה, עם הערות על כל שורה חשובה.

    כמה זה מהיר?

    • זמן: O(n). מעבר אחד, בלי מיון.
    • זיכרון: O(n) לתוצאה.

    טעויות נפוצות

    • להשוות את הקצוות הלא נכונים. "לפני" אומר שהסוף של האינטרוול הקיים קטן מההתחלה החדשה; "חופף" אומר שההתחלה הקיימת היא לכל היותר הסוף החדש.
    • להוסיף את האינטרוול הממוזג בתוך הלולאה, פעם לכל חפיפה, במקום פעם אחת אחרי שלב המיזוג.
    • לשכוח את הרשימה הריקה, או אינטרוול חדש שהולך ממש בהתחלה או ממש בסוף. הלולאה בשלושה שלבים מטפלת בכל אלה אם כותבים אותה בזהירות.
    • לשנות את מערכי הקלט תוך כדי ההרחבה. הקוד משתמש במשתנים נפרדים start ו-end.

    להעמקה

    Merge Intervals פותרת את המקרה הכללי שבו הרשימה לא ממוינת. הבעיה הזו מראה כמה קלט שכבר ממוין עוזר: O(n) במקום O(n log n).

    פתרון לדוגמה

    js
    /**
     * @param {number[][]} intervals
     * @param {number[]} newInterval
     * @return {number[][]}
     */
    export default function insert(intervals, newInterval) {
      const result = []
      let [start, end] = newInterval // the new interval, widened as it swallows overlaps
      let i = 0
      // 1. Entirely before: ends before the new interval starts. Copy unchanged.
      while (i < intervals.length && intervals[i][1] < start) result.push(intervals[i++])
      // 2. Overlapping (or touching): starts at or before the new end. Widen to cover it.
      while (i < intervals.length && intervals[i][0] <= end) {
        start = Math.min(start, intervals[i][0])
        end = Math.max(end, intervals[i][1])
        i++
      }
      result.push([start, end]) // the merged interval, added once
      // 3. Entirely after: copy the rest unchanged.
      while (i < intervals.length) result.push(intervals[i++])
      return result
    }
    ts
    export default function insert(intervals: number[][], newInterval: number[]): number[][] {
      const result: number[][] = []
      let [start, end] = newInterval // the new interval, widened as it swallows overlaps
      let i = 0
      // 1. Entirely before: ends before the new interval starts. Copy unchanged.
      while (i < intervals.length && intervals[i][1] < start) result.push(intervals[i++])
      // 2. Overlapping (or touching): starts at or before the new end. Widen to cover it.
      while (i < intervals.length && intervals[i][0] <= end) {
        start = Math.min(start, intervals[i][0])
        end = Math.max(end, intervals[i][1])
        i++
      }
      result.push([start, end]) // the merged interval, added once
      // 3. Entirely after: copy the rest unchanged.
      while (i < intervals.length) result.push(intervals[i++])
      return result
    }
    python
    def insert(intervals: list[list[int]], new_interval: list[int]) -> list[list[int]]:
        result = []
        start, end = new_interval  # the new interval, widened as it swallows overlaps
        i = 0
        # 1. Entirely before: ends before the new interval starts. Copy unchanged.
        while i < len(intervals) and intervals[i][1] < start:
            result.append(intervals[i])
            i += 1
        # 2. Overlapping (or touching): starts at or before the new end. Widen to cover it.
        while i < len(intervals) and intervals[i][0] <= end:
            start = min(start, intervals[i][0])
            end = max(end, intervals[i][1])
            i += 1
        result.append([start, end])  # the merged interval, added once
        # 3. Entirely after: copy the rest unchanged.
        result.extend(intervals[i:])
        return result