Logic for grouping the Histogram