Friday, June 3, 2011

WAP to Print Disjoint Set with Associated Property In Set

Given a set of overlapping intervals of the form (start, end), each of which is associated with a property (say S), print a sequence of disjoint intervals with all properties current valid in that interval. eg. (1, 3, S0) (2, 3, S1) (2, 4, S2) yields (1,2, S0), (2, 3, S0 + S1 + S2), (3,4,S2) as the disjoint intervals.Also, code a solution to the above problem.

Algorithm

1. make a list from all mins and maxes from the given intervals
2. sort the list and remove duplicates from the list by making it set (as no duplicate)
3. construct intervals from every two consecutive numbers from the list and check
whether this interval is included by the original set of intervals or not
if yes then keep adding interval with associated property else
else create new interval & repeat until we are out of set

Data Structure used: Set,HashSet,ArrayList,Array

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;

class Interval {

class Set {
Integer maximum;
Integer minimum;
String attribute;

Set(Integer minimum, Integer maximum, String attribute) {
this.minimum = minimum;
this.maximum = maximum;
this.attribute = attribute;
}
}

private void getInterval(HashSet uniqueList, Set [] intervals) {
int start =0, end = 0;
ArrayList output = new ArrayList ();
Iterator iterator = uniqueList.iterator();
start =-1;
while(iterator.hasNext()) {
end = iterator.next();
Set temp = new Set(start, end, " ");
for(int i=0;i if(temp.minimum >= intervals[i].minimum &&
temp.maximum <= intervals[i].maximum) {
if(temp.attribute.equals(" ")) {
temp.attribute = intervals[i].attribute;
} else {
temp.attribute += ", " + intervals[i].attribute;
}
}
else if(intervals[i].minimum > end) {
break;
}
}
if(!temp.attribute.equals(" "))
output.add(temp);
start = end;
}
for(int i=0;i Set temp = output.get(i);
System.out.println("( " + temp.minimum + " " + temp.maximum +
" " + temp.attribute + " )" );
}
}

public static void main(String[] args) throws NumberFormatException, IOException
{
BufferedReader br =
new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
Set [] intervals = new Set[n];
Interval interval = new Interval();
for(int i=0;i intervals [i]= interval.new Set(Integer.parseInt(br.readLine()),
Integer.parseInt(br.readLine()), br.readLine());
ArrayList list = new ArrayList();
for(int i=0;i list.add(intervals[i].minimum);
list.add(intervals[i].maximum);
}
Collections.sort(list);
HashSet uniqueList = new HashSet(list);
interval.getInterval(uniqueList, intervals);
}

}

Coded
Review Needed
Time Complexity O(N^2)
Space Complexity O(1)
Run Here http://ideone.com/QJIqx

No comments :