As we can just guess how your input data looks like, I ask you gently to post some code. There are a few points that come to mind when reading your description of the problem at hand, but speculating may lead to misunderstandings and inefficiency in providing useful hints that support your solution.