Skip to content

Commit

Permalink
Insert Interval
Browse files Browse the repository at this point in the history
  • Loading branch information
TonyKim9401 committed Oct 24, 2024
1 parent 094e739 commit b8b8ed5
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions insert-interval/TonyKim9401.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// TC: O(n)
// must retrieve all elements
// SC: O(n)
// need the same size of memory space in the worst case
class Solution {
public int[][] insert(int[][] intervals, int[] newInterval) {
List<int[]> output = new ArrayList<>();

int i = 0;
int n = intervals.length;

while (i < n && intervals[i][1] < newInterval[0]) {
output.add(intervals[i]);
i += 1;
}

while (i < n && intervals[i][0] <= newInterval[1]) {
newInterval[0] = Math.min(newInterval[0], intervals[i][0]);
newInterval[1] = Math.max(newInterval[1], intervals[i][1]);
i += 1;
}

output.add(newInterval);

while (i < n) {
output.add(intervals[i]);
i += 1;
}

return output.toArray(new int[output.size()][]);
}
}

0 comments on commit b8b8ed5

Please sign in to comment.