forked from sastava007/Tech-Interview-Preparation
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReorganize String.cpp
More file actions
54 lines (42 loc) · 1.94 KB
/
Reorganize String.cpp
File metadata and controls
54 lines (42 loc) · 1.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/* Greedy Approach is to find the most frequently occuring character, and seperate them with the second most frequently occuring character. And if we can do that, then it will gurantee us that no
two similar characters are adjacent. So we basically need a DS, that allow us to know that this is the most frequently occuring character, this is the second most frequently character which
indicates toward max_heap.
Similar to Schedule Task problem
TC: O(NLogA) where N is length of string, and A is size of alphabet set. If A is fixed like for lower/upper case then TC = O(N)
Space: O(A) or O(1)
Ex: "aabbcc" O/P = "cbacba" or "abcabc" or any possible valid
*/
class Solution
{
public:
string reorganizeString(string s)
{
unordered_map<char, int> m;
for(char c: s)
m[c]++;
priority_queue<pair<int, char>> q;
for(auto it: m)
q.push({it.second, it.first});
string result="";
while(q.size()>1) //here we're checking for size>1, unlike typical >0 becz we've to extract pop() two elements from top
{
auto current = q.top();
q.pop();
result += string(1, current.second);
auto next = q.top();
q.pop();
result += string(1,next.second);
if(current.first>1) // if we have more instances of character, then enqueue them again in max_heap
q.push({current.first-1, current.second});
if(next.first>1)
q.push({next.first-1, next.second});
}
if(!q.empty()) //if we'are left with 1 character, and it has more than 1 instances then there's no way to seperate it, so return ""
{
if(q.top().first>1)
return "";
result += string(1, q.top().second);
}
return result;
}
};