This comment suggests that there is a O(n) alternative to my O(n log n) solution to this problem:
Given string str("helloWorld")
the expected output is:
l = 3
o = 2
My solution was to do this:
sort(begin(str), end(str));
for(auto start = adjacent_find(cbegin(str), cend(str)), finish = upper_bound(start, cend(str), *start); start != cend(str); start = adjacent_find(finish, cend(str)), finish = upper_bound(start, cend(str), *start)) {
cout << *start << " = " << distance(start, finish) << endl;
}
Which is obviously limited by the sorting of str
. I think this would require a bucket sort solution? Is there anything more clever that I'm missing?
unordered_multiset
which has quadratic construction time :( – Wangstd::unordered_map<char, int>
fits. – Edessaint storage[CHAR_MAX - CHAR_MIN + 1];
? – Pericopeunordered_multiset
will populate without the need for me to populate it separately, and since size isn't an issue here that seemed easier. – Wang- CHAR_MIN
thing. – Pericopestd::string
, it is fair to use an array of chars. – Brouwerstd::sort
by counting_sort. – Best