Skip to content

Instantly share code, notes, and snippets.

@sangupta
Created June 26, 2012 04:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sangupta/2993291 to your computer and use it in GitHub Desktop.
Save sangupta/2993291 to your computer and use it in GitHub Desktop.
Code to determine overlaps in set of data ranges
/**
Problem: Given a set of data ranges (i.e. 2-7, 5-9, 10-20), write a function to determine if there is any overlap within the set.
Write test cases. Which data structure would be best to represent the intervals.
Solution: I would prefer to use an array of size 2N and then iterate over it. Another
way is to work up using interval tree's but I think that may be an overkill considering
it used to check overlaps in multiple ranges and points.
*/
int[] array = new int[];
array[0] = 2;
array[1] = 7;
array[2] = 5;
array[3] = 9;
.
.
.
.
array[2n] = <some value>;
for(int i = 0; i < 2n; i += 2) {
for(int j = i + 2; j <2 n; j += 2) {
if(array[j] >= array[i] && array[j] <= array[i+1]) {
// the starting element is between the range
// there is an overlap
} else if(array[j+1] >= array[i] && array[j+1] <= array[i+1]) {
// the ending element is between the range
// there is an overlap
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment