Skip to content

Commit 55c387f

Browse files
add Intervals solution
1 parent caf8c01 commit 55c387f

File tree

1 file changed

+89
-0
lines changed

1 file changed

+89
-0
lines changed

medium300/Intervals.java

+89
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
package medium300;
2+
3+
import java.util.ArrayList;
4+
import java.util.Comparator;
5+
import java.util.List;
6+
7+
public class Intervals {
8+
9+
class Interval {
10+
long left, right;
11+
12+
public Interval(long left, long right) {
13+
this.left = left;
14+
this.right = right;
15+
}
16+
17+
long getLeft() {
18+
return left;
19+
}
20+
}
21+
22+
public String smallest(String intervals) {
23+
24+
String[] ivals = intervals.split(",");
25+
List<Interval> list = new ArrayList<>();
26+
for (String x : ivals) {
27+
String[] in = x.split("-");
28+
list.add(new Interval(Long.parseLong(in[0]), Long.parseLong(in[1])));
29+
}
30+
31+
while (true) {
32+
boolean change = false;
33+
// System.out.println("New iteration");
34+
for (int i = 0; i < list.size(); i++) {
35+
Interval el = list.get(i);
36+
37+
for (int j = 0; j < list.size(); j++) {
38+
if (i == j)
39+
continue;
40+
else {
41+
Interval el2 = list.get(j);
42+
43+
if (el.right < el2.left - 1 || el.left > el2.right + 1) {
44+
// System.out.println(el.left + "-" + el.right + " is completely outside of " +
45+
// el2.left+"-"+el2.right);
46+
continue;
47+
} else if (el.left <= el2.left && el.right >= el2.right) {
48+
// System.out.println(el.left + "-" + el.right + " contains " +
49+
// el2.left+"-"+el2.right);
50+
list.remove(el2);
51+
change = true;
52+
break;
53+
} else {
54+
// System.out.println(el.left + "-" + el.right + " concatenated with " +
55+
// el2.left+"-"+el2.right);
56+
list.remove(el);
57+
list.remove(el2);
58+
list.add(new Interval(Math.min(el.left, el2.left), Math.max(el.right, el2.right)));
59+
change = true;
60+
break;
61+
}
62+
}
63+
}
64+
}
65+
66+
if (!change)
67+
break;
68+
}
69+
70+
list.sort(Comparator.comparing(Interval::getLeft));
71+
StringBuilder sb = new StringBuilder();
72+
73+
for (int i = 0; i < list.size(); i++) {
74+
Interval el = list.get(i);
75+
sb.append(el.left).append("-").append(el.right);
76+
if (i != list.size() - 1)
77+
sb.append(",");
78+
}
79+
80+
return sb.toString();
81+
}
82+
83+
public static void main(String[] args) {
84+
Intervals i = new Intervals();
85+
System.out.println(i.smallest("2-4,5-5,6-8"));
86+
System.out
87+
.println(i.smallest("327802850-593687580,288675425-410271975,386737447-388754878,96575567-222789979"));
88+
}
89+
}

0 commit comments

Comments
 (0)