| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | namespace LeetCode.Algorithms.InsertInterval; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class InsertIntervalIterative : IInsertInterval |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(n) |
| | 19 | | /// Space complexity - O(n) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="intervals"></param> |
| | 22 | | /// <param name="newInterval"></param> |
| | 23 | | /// <returns></returns> |
| | 24 | | public int[][] Insert(int[][] intervals, int[] newInterval) |
| 6 | 25 | | { |
| 6 | 26 | | var result = new List<int[]>(); |
| | 27 | |
|
| 6 | 28 | | var i = 0; |
| | 29 | |
|
| 9 | 30 | | while (i < intervals.Length && intervals[i][1] < newInterval[0]) |
| 3 | 31 | | { |
| 3 | 32 | | result.Add(intervals[i]); |
| 3 | 33 | | i++; |
| 3 | 34 | | } |
| | 35 | |
|
| 10 | 36 | | while (i < intervals.Length && intervals[i][0] <= newInterval[1]) |
| 4 | 37 | | { |
| 4 | 38 | | newInterval[0] = Math.Min(newInterval[0], intervals[i][0]); |
| 4 | 39 | | newInterval[1] = Math.Max(newInterval[1], intervals[i][1]); |
| 4 | 40 | | i++; |
| 4 | 41 | | } |
| | 42 | |
|
| 6 | 43 | | result.Add(newInterval); |
| | 44 | |
|
| 10 | 45 | | while (i < intervals.Length) |
| 4 | 46 | | { |
| 4 | 47 | | result.Add(intervals[i]); |
| 4 | 48 | | i++; |
| 4 | 49 | | } |
| | 50 | |
|
| 6 | 51 | | return [.. result]; |
| 6 | 52 | | } |
| | 53 | | } |