Optimized code for obtaining balanced data set