Google Interview - Rearrange a string so that all same characters become d dista

Given a string and a positive integer d. Some characters may be repeated in the given string. Rearrange characters of the given string such that the same characters become d distance away from each other. Note that there can be many possible rearrangements, the output should be one of the possible rearrangements. If no such arrangement is possible, that should also be reported.
Expected time complexity is O(n) where n is length of input string.

Solution: The idea is to count frequencies of all characters and consider the most frequent character first and place all occurrences of it as close as possible. After the most frequent character is placed, repeat the same process for remaining characters.

1) Let the given string be str and size of string be n

2) Traverse str, store all characters and their frequencies in a Max Heap MH. The value of frequency decides the order in MH, i.e., the most frequent character is at the root of MH.

3) Make all characters of str as ‘\0′.

4) Do following while MH is not empty.
…a) Extract the Most frequent character. Let the extracted character be x and its frequency be f.
…b) Find the first available position in str, i.e., find the first ‘\0′ in str.
…c) Let the first position be p. Fill x at p, p+d,.. p+(f-1)d

Examples:
Input:  "abb", d = 2
Output: "bab"

Input:  "aacbbc", d = 3
Output: "abcabc"

Input: "geeksforgeeks", d = 3
Output: egkegkesfesor

Input:  "aaa",  d = 2
Output: Cannot be rearranged
public static String rearrange(String str, int k) {
	Map<Character, Integer> map = new HashMap<>();
	char[] s = str.toCharArray();
	int n = s.length;
	for(int i=0; i<n; i++) {
		Integer cnt = map.get(s[i]);
		if(cnt == null) cnt = 0;
		map.put(s[i], cnt+1);
	}
	Queue<Character> queue = new PriorityQueue<>(map.size(), new Comparator<Character>(){
		public int compare(Character c1, Character c2) {
			return map.get(c2) - map.get(c1);
		}
	});
	queue.addAll(map.keySet());
	Arrays.fill(s, '\0');
	for(int i=0; i<map.size(); i++) {
		int p = i;
		while(s[p] != '\0') p++;
		char c = queue.poll();
		int cnt = map.get(c);
		for(int j=0; j<cnt; j++) {
			if(p >= n) return "Cannot be rearranged";
			s[p] = c;
			p += k;
		}
	}
	return new String(s);
}

Time Complexity: O(n+mlog(m)). Here n is the length of str, m is count of distinct characters in str[]. m is smaller than 256. So the time complexity can be considered as O(n).

Reference:

http://www.geeksforgeeks.org/rearrange-a-string-so-that-all-same-characters-become-at-least-d-distance-away/

猜你喜欢

转载自yuanhsh.iteye.com/blog/2231105