Skip to content

Commit 3196603

Browse files
committed
O(n) time and O(1) using Greedy Approach and Max Heap.
1 parent ea98986 commit 3196603

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
"""
2+
Given a non-empty string s and an integer k, rearrange the string such that the same characters are at least distance k from each other.
3+
4+
All input strings are given in lowercase letters. If it is not possible to rearrange the string, return an empty string "".
5+
6+
Example 1:
7+
8+
Input: s = "aabbcc", k = 3
9+
Output: "abcabc"
10+
Explanation: The same letters are at least distance 3 from each other.
11+
Example 2:
12+
13+
Input: s = "aaabc", k = 3
14+
Output: ""
15+
Explanation: It is not possible to rearrange the string.
16+
Example 3:
17+
18+
Input: s = "aaadbbcc", k = 2
19+
Output: "abacabcd"
20+
Explanation: The same letters are at least distance 2 from each other.
21+
"""
22+
import operator
23+
class Solution:
24+
def rearrangeString(self, s: str, k: int) -> str:
25+
if not k:
26+
return s
27+
count = collections.Counter(s)
28+
max_freq = 0
29+
result = []
30+
for key,val in count.items():
31+
max_freq = max(val,max_freq)
32+
"""
33+
len(count) > 1 for case s = 'a' , k = 2
34+
"""
35+
if (max_freq)*(k-1) >= len(s) and len(count) > 1:
36+
return ""
37+
charFreq = [(-v,k) for k,v in count.items()]
38+
heapq.heapify(charFreq)
39+
while charFreq:
40+
temp,count1 = [],0
41+
for i in range(k):
42+
if charFreq:
43+
item = heapq.heappop(charFreq)
44+
result.append(item[1])
45+
count1 +=1
46+
if item[0] < -1:
47+
temp.append((item[0]+1,item[1]))
48+
if count1 < k and temp: # if count < k then there are still some chars left to arrange and makes impossible for us to arrange all characters.
49+
return ""
50+
for item in temp:
51+
heapq.heappush(charFreq,item)
52+
return ''.join(result)

0 commit comments

Comments
 (0)