Have you thought of using sets or multisets?