-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFirstKNonRepeatingChars.cpp
More file actions
71 lines (62 loc) · 2.05 KB
/
FirstKNonRepeatingChars.cpp
File metadata and controls
71 lines (62 loc) · 2.05 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
//
// Find first k non-repeating characters in a string in single traversal
// For example, if the string is ABCDBAGHCHFAC and K = 3, output would be D G F
// The idea is to traverse the string once and store two pieces of information in
// a map:
// a) Character count
// b) Index of first/last occurence of character
// We then traverse the map and look for characters with count = 1. Since we are
// interested in the first k characters (lower index values), we create a min heap
// and store the indices of the characters with count = 1. Size of the heap is "k"
// because we are only interested in those many characters. After the heap is populated,
// we compare the index of a newly found character with the top of the heap. if teh index is
// small (character appears ealier), we pop and push the new character
//
#include <iostream>
#include <queue>
#include <unordered_map>
#include <string>
struct ChardData {
int count;
int indx;
};
void printFirstKNonRepeatingChars(const std::string& str, int k)
{
std::unordered_map<char, ChardData> map;
std::priority_queue<int, std::vector<int>, std::greater<int>> pq;
for (int i = 0; i < str.length(); ++i)
{
map[str[i]].count++;
map[str[i]].indx = i;
}
for (const auto& iter : map)
{
int charCount = iter.second.count;
int startOrEndIndex = iter.second.indx;
if (charCount == 1) {
if (pq.size() < k)
{
pq.push(startOrEndIndex);
} else {
if (startOrEndIndex < pq.top())
{
pq.pop();
pq.push(startOrEndIndex);
}
}
}
}
std::cout << "The first " << k << " non repeating characters are :";
while (!pq.empty())
{
std::cout << " " << str[pq.top()];
pq.pop();
}
std::cout << std::endl;
}
int main(int argc, const char * argv[]) {
std::string str = "ABCDBAGHCHFAC";
int k = 3;
printFirstKNonRepeatingChars(str, k);
return 0;
}