From 684161e60868936b58a8b9c532d054387b924c6b Mon Sep 17 00:00:00 2001 From: Disha Thakurata <146114938+dishathakurata@users.noreply.github.com> Date: Mon, 9 Dec 2024 22:00:41 +0530 Subject: [PATCH] Create Insert interval --- Insert interval | 67 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 Insert interval diff --git a/Insert interval b/Insert interval new file mode 100644 index 0000000..bfcdb34 --- /dev/null +++ b/Insert interval @@ -0,0 +1,67 @@ +//Insert interval + +import java.io.*; +import java.lang.*; +import java.math.*; +import java.util.*; + +class GFG { + public static void main(String[] args) throws IOException { + Scanner sc = new Scanner(System.in); + int T = sc.nextInt(); + + while(T-- > 0) { + int n = sc.nextInt(); + int a[][] = new int[n][2]; + + for(int i = 0; i < n; i++) { + a[i][0] = sc.nextInt(); + a[i][1] = sc.nextInt(); + } + + int h[] = new int[2]; + h[0] = sc.nextInt(); + h[1] = sc.nextInt(); + Solution obj = new Solution(); + ArrayList ans = obj.insertInterval(a, h); + + System.out.print("["); + for(int i = 0; i < ans.size(); i++) { + System.out.print("["); + System.out.print(ans.get(i)[0] + "," + ans.get(i)[1]); + System.out.print("]"); + if (i != ans.size() - 1) System.out.print(","); + } + System.out.println("]"); + System.out.println("~"); + } + } +} + +class Solution { + static ArrayList insertInterval(int[][] intervals, int[] newInterval) { + ArrayList res = new ArrayList<>(); + int i = 0; + int n = intervals.length; + + while(i < n && intervals[i][1] < newInterval[0]) { + res.add(intervals[i]); + i++; + } + + 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++; + } + + res.add(newInterval); + + while(i < n) { + res.add(intervals[i]); + i++; + } + + return res; + } +}