Algorithms – How to Split and Sort Numbers into Three Equally Large Groups

algorithms

I have to write an algorithm to split/sort numbers into three groups to make them equally large.

To be more specific:

I have three groups, let's call them A, B and C. Then I have a lot of numbers. Each number has assigned a group to which it belongs, but the thing is, that one number could belong to one of two or one of three groups (to one of them, but we don't know exactly to which one).

Sample data:

Number | Group 
1      | A (this number HAVE TO be in group A) 
2      | A 
3      | B 
4      | C 
5      | AC (this number can be in group A or C) 
6      | BC (can be in group B or C) 
7      | A 
8      | B 
9      | ABC (can be in group A, B or C) 
... 

One of the correct results of this sample can be:

A: 1, 2, 7 
B: 3, 8, 9 
C: 4, 5, 6 

It doesn't matter which group is chosen if there were multiple groups assigned to one number (it would be best if it is chosen randomly). The goal is to split those numbers to make each group equally large (or as close to it as possible).

My question is: How would you write algorithm to achieve the desired result? Pseudo code or verbal description is enough.

Best Answer

Keep track of the size of each of the subgroups and when there's one that is ambiguous place it in the subgroup with the lowest current count.

If you want to go for even closer accuracy, place all singletons in their respective sub-groups (all non-ambiguous values). And then do a second pass for all that fit in 2 sub-groups, and a third for all that fit in 3 sub-groups, at most this would be an O(n^2) operation anyway, with the previous one running in O(n*log(n)) roughly. Just based off of what I'm seeing in my head.

If you split the main array into 3 sub-arrays with 1, 2, and 3 group values being in their own respective arrays (if space isn't an issue) you could perform the second in nearly O(n*log(n)).

Related Topic