Wednesday, October 21, 2020

Heap + greedy algorithm: 358 Rearrange string k distance

 Here is the gist. 


Case study 

Work on string "aaadbbcc" and distance k = 2. 

First of all, count characters in the string and save them into an array with size 256. 

Next it is to work on greedy algorithm design, the character with most occurrences will be selected first, and then continue to iterate all other characters. One of ideas is to use maximum heap, so that 'a' with occurrence 3 will be selected first, and it will be removed from maximum heap as well. 

One thing is to design k distance away. I stumbled on this requirement for long time, after I studied the code written in Java and then wrote one using C#. It becomes very clear that it can be done quick and easy. Add a double linked list using C# LinkedList acting as a Queue, when the size is k, then first character in the queue should be added back to maximum heap. 

I also think about maximum heap, should I limit the heap size to k, or I can add all characters in the heap instead. Actually most of important is to add character with occurrence back to maximum heap. Since total distinct characters are 256, it is no problem to load all of them in heap one time at the beginning. 


No comments:

Post a Comment