`

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/

 

分享到:
评论

相关推荐

    QuickShift Redux - Rearrange Chrome Tabs-crx插件

    使用键盘快捷键轻松快速地重新排列选项卡。 QuickShift Redux是一个Chrome扩展程序,可让您轻松快捷地使用键盘快捷键重新排列标签页。 -在同一窗口内向左或向右移动选项卡-在新窗口中将选项卡取消停靠-在窗口之间...

    LeetCode最全代码

    Here is the classification of all `468` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. I'll keep updating for full summary and...

    XSLT Jumpstarter(Pragmatic,2015)

    Finally, a ground-up, quick-start approach to XSLT that teaches not just the language, but XML processing solutions. XSLT Jumpstarter approaches the subject like no other book, using examples that ...

    Rearrange-a-Room

    重新布置房间 网站总览 房间改造共享网站 网站主题 丰富回国时间 选择主题的原因 当前,出门旅行的限制比以前更多,例如远程工作。在这种情况下,我感到越来越多的人正在他们的家中寻找舒适的环境和空间。...

    Trajectory Generation and Control for Quadrotors

    Abstract This thesis presents contributions to the state-of-the-art in quadrotor control, payload transportation with ...quickly rearrange formations and avoid a small number of obstacles.

    C语言通用范例开发金典.part2.rar

    ∷相关函数:Rearrange函数 1.5.6 希尔排序 241 范例1-82 希尔排序 241 ∷相关函数:ShellSort函数 1.5.7 冒泡排序 243 范例1-83 冒泡排序 243 ∷相关函数:bubble_sort函数 1.5.8 一趟快速排序 246 范例1-...

    重新排列标签「Rearrange Tabs」-crx插件

    重新排列标签是一个小巧的谷歌浏览器扩展,允许用户 通过移动它们来重新排列窗口中标签的位置 围绕使用键盘快捷键。 将标签左移 Mac:Ctrl + Shift +向左 Windows:Shift + Alt +向左 向右移动标签 Mac:Ctrl + ...

    cpp-4.4.7-23.el6.x86-64.rpm

    and line control (if you use a program to combine or rearrange source files into an intermediate file which is then compiled, you can use line control to inform the compiler about where each source ...

    八数码问题 人工智能难题 九宫图

    功能: 1. 立刻判断是否有解 2. 对于所有有解的情况,只要对搜索的状态数的限 制适当放宽,总是能够找到解的 3. 支持随机初始状态和自给定初始状态 4. 支持游戏模式 呵呵 ... java rearrange.Rearrange fg

    BPBible学习圣经软件 python源码

    This means that a search can cross verse boundaries, giving a more natural search. It also supports regular expressions and phrases. Flexible layout BPBible lets you rearrange your layout, and ...

    Rearrange Tabs-crx插件

    重新排列标签页是一个很小的Google Chrome扩展程序,允许用户通过使用键盘快捷键在窗口中四处移动来重新排列标签页中的位置。 向左移动选定的选项卡Mac:Ctrl + Shift +向左的窗口:Shift + Alt +向左移动向右的Mac...

    BB Editor 12.5

    New editing commands “Columns” – Cut, copy, delete or rearrange columns easily delimited text files (CSV, TSV) without a spreadsheet or complicated regular expressions. FTP / SFTP browsers now have...

    Tab Rearranging-crx插件

    语言:English (United States) 允许您使用键盘快捷键重新排列标签。 此扩展名使您可以使用键盘...如果您发现与此有关的任何问题或有改进的想法,请在此处告诉我:https://github.com/chriskim06/tab-rearrange/issues

    URL Rearrange-crx插件

    语言:English 根据需要拆分和合并URL。 根据需要将分割和合并的URL复制到剪贴板。

    UG6.0快捷键大全

    MESSAGE Copies a feature so that it can be pasted either within the same part or to another. SYNONYMS duplicate, repeat HINT This command is available in history modeling mode. ACTIONS STANDARD ...

    PDF Tools 1.3

    It can encrypt, decrypt, join, split, rearrange, create and stamp a PDF file. For more information visit http://www.sheelapps.com/. PDFTools is developed using iText, a free Java-PDF library. iText...

    Macromedia Dreamweaver 8

    functions that Dreamweaver calls in order to implement its various objects, menus, floating panels, server behaviors, and so on, providing a simple example for each type. The book also describes the ...

    MMX_Setup_15_0_20_2385.zip

    Common tasks like Add a Field, Modify a Property and Rename Local are all invoked with just one keystroke. Advanced Code Sort and Rearrange features include: Rearrange members in Members view using...

Global site tag (gtag.js) - Google Analytics