|
| 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 | +} |
0 commit comments