[ there is a test cases failing as was pointed in the comments]
So take care of the same if referring my answer
I see, but it doesn't seem to work if you have 'a'->4, 'b'->2, and 'c'->1. Because the first step is "abc", leaving 'a'->3 'b'->1. But there is an answer: "ababaca". – user3386109
Case 1 : Build the basic algorithm
use a hashmap (key being the character and its occurance being the value) to count the occurances. This will give us buckets like if we have "cbaaba" will give 3 buckets with 'c' with value 1, 'a' with value 3 and 'b' with value 2.
Sort the buckets based on the occurances with element with most occurancr first.
so now we have
'a' -> 3 , 'b' -> 2 , 'c' -> 1
- Get the element from max occurance bucket, decrease its count by 1 in map and put it in result array. Follow this for subsequent occuance buckets based on the sorted occurance buckets.
result array will start with taking one each from 3 buckets in sorted fashion.
"abc" and now we have our buckets as 'a'->2 , 'b'-> 1 and 'c'-> 0
next we again try to get elemet each from sorted buckets (ignoring the buckets with 0 elements)
"abcab" now our buckets state become as : 'a'-> 1 , 'b'- > 0 and 'c'-> 0
next as above we proceed to have our result as
=> "abcaba".
Case 2 : if string is like "aaaabbbcccdd"
We will have buckets as
'a'--> 4
'b'--> 3
'c'--> 3
'd'--> 2
Here we have bucket of b and c having same size. When ever such situation occurs we have to perform an operation of JoinBuckets, It will join 'b' and 'c' in single bucket and 'bc' will be considered as a single element.
Now our buckets will be
'a'--> 4
'bc'--> 3
'd'--> 2
Now proceeding ahead in same manner as done in case 1, we try to build the result
=>result = "abcd"
'a'--> 3
'bc'--> 2
'd'--> 1
=>result = "abcdabcd"
'a'--> 2
'bc'--> 1
'd'--> 0
=>result = "abcdabcdabc"
'a'--> 1
'bc'--> 0
'd'--> 0
=>Final Result = "abcdabcdabca"