There is a string of up to 10^5 A..Z characters. The task is to rearrange it so that none of the characters forms a row. For multiple solutions the one that comes first alphabetically is correct. And it has to be done in reasonable time, of course.
So I tried two approaches and one of them rearranges correctly but very inefficiently, and the other one has broken logic, I guess.
Slow approach.
Incorrect approach (doesn't always give the alphabetically first answer)
I am really stuck and can't think of anything else here.
Examples:
"HHABC" -> "ABHCH";
"CBAXXXX" -> "XAXBXCX";
"AAABBBCCCCCCCDDDDD" -> "ABABACBCDCDCDCDCDC";
Here is the model solution algorithm in details. I think I am not allowed to post the actual code, so it's like this:
It is much shorter and simpler than the mess I wrote eventually (although it worked fine, and thank you very much for the help).
Good point Paul R. If you have your histogram with the number of occurrences of each element, you could then sort those buckets by number of occurrences from high to low. As long as the number of occurrences in one bucket is not greater than the number of buckets, you should be able to form a viable string. Starting with the largest buckets, loop through each occurrence in the next largest bucket down to the smaller buckets.
For example, AAAAABBCRRSTT
AAAAA BB C RR S TT -> AAAAA BB RR TT C S
ABARATACASBRT
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With