diff --git a/src/main/java/com/thealgorithms/others/LineSweep.java b/src/main/java/com/thealgorithms/others/LineSweep.java new file mode 100644 index 000000000000..d2c1595e24e5 --- /dev/null +++ b/src/main/java/com/thealgorithms/others/LineSweep.java @@ -0,0 +1,41 @@ +package com.thealgorithms.others; +import java.util.Arrays; + +public class LineSweep { + + /** Line Sweep algorithm can be used to solve range problems by first sorting the list of ranges + * by the start value of the range in non-decreasing order and doing a "sweep" through the number + * line(x-axis) by incrementing the start point by 1 and decrementing end point by -1 on the + * number line. https://www.topcoder.com/thrive/articles/Line%20Sweep%20Algorithms + * / + + * Find if any ranges overlap + * param = ranges Array of range[start,end] + * param = maximum Maximum length of number line or largest "end" value + * return true if there overlap exists false + * otherwise. + */ + + public static boolean isOverlap(int[][] ranges,int maximum) { + + Arrays.sort(ranges, (a, b) -> (a[0] - b[0])); + int[] numberLine = new int[maximum+1]; + for (int[] range : ranges) { + + int start = range[0]; + int end = range[1]; + + numberLine[start] += 1; + numberLine[end] -= 1; + } + + int current = 0; + int overlaps = 0; + for (int num : numberLine) { + + current += num; + overlaps = Math.max(overlaps, current); + } + return overlaps >1 ; + } +} diff --git a/src/test/java/com/thealgorithms/others/LineSweepTest.java b/src/test/java/com/thealgorithms/others/LineSweepTest.java new file mode 100644 index 000000000000..152e399d6be5 --- /dev/null +++ b/src/test/java/com/thealgorithms/others/LineSweepTest.java @@ -0,0 +1,20 @@ +package com.thealgorithms.others; +import static org.junit.jupiter.api.Assertions.*; +import com.thealgorithms.others.LineSweep; +import org.junit.jupiter.api.Test; +public class LineSweepTest { + + + @Test + void testForOverlap(){ + int[][]arr = {{0,10},{7,20},{15,24}}; + assertTrue(LineSweep.isOverlap(arr,24)); + } + + @Test + void testForNoOverlap(){ + int[][]arr = {{0,10},{11,20},{21,24}}; + assertFalse(LineSweep.isOverlap(arr,24)); + } + +}