I'm not quite clear at what the goal is, but perhaps something like a Segment Tree data structure might help?