AdSense

Monday, October 17, 2016

Rearrange String k Distance Apart

Given a non-empty string str and an integer k, rearrange the string such that the same characters are at least distance k from each other.
All input strings are given in lowercase letters. If it is not possible to rearrange the string, return an empty string"".
Example 1:
str = "aabbcc", k = 3

Result: "abcabc"

The same letters are at least distance 3 from each other.
Example 2:
str = "aaabc", k = 3 

Answer: ""

It is not possible to rearrange the string.
Example 3:
str = "aaadbbcc", k = 2

Answer: "abacabcd"

Another possible answer is: "abcabcda"

The same letters are at least distance 2 from each other.

Note: 2016-11-27
Why do we need to put sb.length() < s.length() in if condition?
Because if we reach the end of the string and i is less than 0, queue is guaranteed to be empty, and the code will falsely return empty string.

Using a greedy approach. Every time we add the character with the highest frequency to the string. If there is no k distinct characters left in the queue, we return "". For all characters that have remaining frequency larger than 0, we add them back to queue.

public String rerrange(String s, int k) {
        Map<character, integer> tempMap = new HashMap<>();
        for (char c : s.toCharArray()) {
            if (!tempMap.containsKey(c)) {
                tempMap.put(c, 1);
            } else {
                tempMap.put(c, tempMap.get(c) + 1);
            }
        }

        PriorityQueue<frequency> queue = new PriorityQueue<>();
        for (Map.Entry<character, integer> entry : tempMap.entrySet()) {
            queue.add(new Frequency(entry.getValue(), entry.getKey()));
        }

        StringBuilder sb = new StringBuilder();
        while (!queue.isEmpty()) {
            Queue<frequency> tempQueue = new LinkedList<>();
            for (int i = 0; i < k && sb.length() < s.length(); i++) {
                if (queue.isEmpty()) {
                    return "";
                }
                Frequency curr = queue.poll();
                sb.append(curr.c);
                curr.freq--;
                if (curr.freq > 0) {
                    tempQueue.add(curr);
                }
            }
            while (!tempQueue.isEmpty()) {
                queue.add(tempQueue.poll());
            }
        }
        return sb.toString();
    }

    private class Frequency implements Comparable<frequency> {
        int freq;
        char c;

        public Frequency(int freq, char c) {
            this.c = c;
            this.freq = freq;
        }

        @Override public int compareTo(Frequency o) {
            return o.freq - this.freq;
        }
    }


1 comment:

  1. The development of artificial intelligence (AI) has propelled more programming architects, information scientists, and different experts to investigate the plausibility of a vocation in machine learning. Notwithstanding, a few newcomers will in general spotlight a lot on hypothesis and insufficient on commonsense application. IEEE final year projects on machine learning In case you will succeed, you have to begin building machine learning projects in the near future.

    Projects assist you with improving your applied ML skills rapidly while allowing you to investigate an intriguing point. Furthermore, you can include projects into your portfolio, making it simpler to get a vocation, discover cool profession openings, and Final Year Project Centers in Chennai even arrange a more significant compensation.


    Data analytics is the study of dissecting crude data so as to make decisions about that data. Data analytics advances and procedures are generally utilized in business ventures to empower associations to settle on progressively Python Training in Chennai educated business choices. In the present worldwide commercial center, it isn't sufficient to assemble data and do the math; you should realize how to apply that data to genuine situations such that will affect conduct. In the program you will initially gain proficiency with the specialized skills, including R and Python dialects most usually utilized in data analytics programming and usage; Python Training in Chennai at that point center around the commonsense application, in view of genuine business issues in a scope of industry segments, for example, wellbeing, promoting and account.

    ReplyDelete