I have a string s
of length n
. What is the most efficient data structure / algorithm to use for finding the most frequent character in range i..j
?
The string doesn't change over time, I just need to repeat queries that ask for the most frequent char among s[i]
, s[i + 1]
, ... , s[j]
.
assuming the string is constant, and different
i
andj
will be passed to query occurences.If you want to minimize processing time you can make a
and keep a
std::list<occurences>
for each character. for fast searching you can keeppositions
ordered.and if you want to minimize memory you can just keep an incrementing integer and loop through
i
..j
Do a single iteration over the array and for each position remember how many occurances of each character are there up to that position. So something like this:
for index 0:
for index 1:
for index 2:
And so on. For index 6:
After you compute this array you can get the number of occurances of a given letter in an interval (i, j) in constant time - simply compute
count[j] - count[i-1]
(careful here fori = 0
!).So for each query you will have to iterate over all letters not over all characters in the interval and thus instead of iterating over 10^6 characters you will only pass over at most 128(assuming you only have ASCII symbols).
A drawback - you need more memory, depending on the size of the alphabet you are using.
You need to specify your algorithmic requirements in terms of space and time complexity.
If you insist on
O(1)
space complexity, just sorting (e.g. using lexicographic ordering of bits if there is no natural comparison operator available) and counting the number of occurances of the highest element will give youO(N log N)
time complexity.If you insist on
O(N)
time complexity, use @Luchian Grigore 's solution which also takesO(N)
space complexity (well,O(K)
forK
-letter alphabet).An array in which you hold the number of occurences of each character. You increase the respective value while iterating throught the string once. While doing this, you can remember the current max in the array; alternitively, look for the highest value in the array at the end.
Pseudocode
If you wish to get efficient results on intervals, you can build an integral distribution vector at each index of your sequence. Then by subtracting integral distributions at j+1 and i you can obtain the distribution at the interval from s[i],s[i+1],...,s[j].
Some pseudocode in Python follows. I assume your characters are chars, hence 256 distribution entries.
after each access of string call freq()
to get the most frequent char call the
string.charAt(arrCount.max())