Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit c295d58

Browse files
Create OverlappingIntervalsSubOptimal.java
1 parent 4b644e2 commit c295d58

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
/*
2+
An interval is a pair of values that represents all numbers between those two.
3+
4+
5+
You are given N intervals. You need to print the farthest located interval distance that are non overlapping. If there is no non-overlapping pair of intervals present, return -1
6+
7+
8+
Note: Distance between two intervals is defined by the absolute difference between the end point of the left interval and start point of the right interval.
9+
10+
11+
A distance of 0 means that they’re NOT overlapping. For instance, [1, 3] and [3, 4] are not considered overlapping.
12+
13+
Input format
14+
There are N+1 lines of input
15+
16+
First line contains a single integer N. Next N lines will contain two integers, l and r, representing the start and end point of the interval respectively.
17+
18+
Output format
19+
Print the farthest distance or -1 if no overlapping intervals are present.
20+
21+
Sample Input 1
22+
3
23+
24+
1 2
25+
26+
3 5
27+
28+
6 7
29+
30+
Sample Output 1
31+
4
32+
33+
Explanation
34+
The pair of intervals [1,2] & [6,7] are farthest. And the distance between them will be 6 - 2 = 4
35+
36+
Constraints
37+
1<=N<=10^5
38+
39+
1<=l<=r<=10^6
40+
*/
41+
42+
import java.util.*;
43+
class OverlappingIntervalsSubOptimal {
44+
public static void main(String args[]) {
45+
Scanner sc = new Scanner(System.in);
46+
int n = sc.nextInt();
47+
ArrayList<ArrayList<Integer>> intervals = new ArrayList<ArrayList<Integer>>(n);
48+
for (int i = 0; i < n; i++) {
49+
int x = sc.nextInt();
50+
int y = sc.nextInt();
51+
intervals.add(new ArrayList<Integer>(Arrays.asList(x, y)));
52+
}
53+
int result = overlappingIntervals(n, intervals);
54+
System.out.println(result);
55+
}
56+
static int overlappingIntervals(int n, ArrayList<ArrayList<Integer>> intervals) {
57+
58+
Collections.sort(intervals, (i1, i2) -> {
59+
if( (i1.get(0) - i2.get(0) ) != 0 ){
60+
return i1.get(0) - i2.get(0);
61+
} else {
62+
return i1.get(1) - i2.get(1);
63+
}
64+
});
65+
66+
if(intervals.get(intervals.size()-1).get(0) >= intervals.get(0).get(1) )
67+
return intervals.get(intervals.size()-1).get(0) - intervals.get(0).get(1);
68+
else return -1;
69+
}
70+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /