Skip to content

Commit 1551b8f

Browse files
authored
Add line sweep algorithm (#4157)
1 parent 1dc3886 commit 1551b8f

File tree

2 files changed

+80
-0
lines changed

2 files changed

+80
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package com.thealgorithms.others;
2+
import java.util.Arrays;
3+
import java.util.Comparator;
4+
5+
/* Line Sweep algorithm can be used to solve range problems by first sorting the list of ranges
6+
* by the start value of the range in non-decreasing order and doing a "sweep" through the number
7+
* line(x-axis) by incrementing the start point by 1 and decrementing the end point+1 by 1 on the
8+
* number line.
9+
* An overlapping range is defined as (StartA <= EndB) AND (EndA >= StartB)
10+
* References
11+
* https://en.wikipedia.org/wiki/Sweep_line_algorithm
12+
* https://en.wikipedia.org/wiki/De_Morgan%27s_laws>
13+
*/
14+
public class LineSweep {
15+
16+
/** Find Maximum end point
17+
* param = ranges : Array of range[start,end]
18+
* return Maximum Endpoint
19+
*/
20+
public static int FindMaximumEndPoint (int[][]ranges){
21+
Arrays.sort(ranges, Comparator.comparingInt(a->a[1]));
22+
return ranges[ranges.length-1][1];
23+
}
24+
25+
/** Find if any ranges overlap
26+
* param = ranges : Array of range[start,end]
27+
* return true if overlap exists false otherwise.
28+
*/
29+
public static boolean isOverlap(int[][] ranges) {
30+
31+
int maximumEndPoint = FindMaximumEndPoint(ranges);
32+
Arrays.sort(ranges, Comparator.comparingInt(a->a[0]));
33+
int[] numberLine = new int[maximumEndPoint+2];
34+
for (int[] range : ranges) {
35+
36+
int start = range[0];
37+
int end = range[1];
38+
39+
numberLine[start] += 1;
40+
numberLine[end+1] -= 1;
41+
}
42+
43+
int current = 0;
44+
int overlaps = 0;
45+
for (int num : numberLine) {
46+
current += num;
47+
overlaps = Math.max(overlaps, current);
48+
}
49+
return overlaps >1 ;
50+
}
51+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package com.thealgorithms.others;
2+
import static org.junit.jupiter.api.Assertions.*;
3+
import org.junit.jupiter.api.Test;
4+
public class LineSweepTest {
5+
6+
7+
@Test
8+
void testForOverlap(){
9+
int[][]arr = {{0,10},{7,20},{15,24}};
10+
assertTrue(LineSweep.isOverlap(arr));
11+
}
12+
13+
@Test
14+
void testForNoOverlap(){
15+
int[][]arr = {{0,10},{11,20},{21,24}};
16+
assertFalse(LineSweep.isOverlap(arr));
17+
}
18+
@Test
19+
void testForOverlapWhenEndAEqualsStartBAndViceVersa(){
20+
int[][]arr = {{0,10},{10,20},{21,24}};
21+
assertTrue(LineSweep.isOverlap(arr));
22+
}
23+
@Test
24+
void testForMaximumEndPoint(){
25+
int[][]arr = {{10,20},{1,100},{14,16},{1,8}};
26+
assertEquals(100,LineSweep.FindMaximumEndPoint(arr));
27+
}
28+
29+
}

0 commit comments

Comments
 (0)