In a recent interview I was asked to write the below program. Find out the character whose frequency is minimum in the given String ? So I tried by iterating through the string
Having to iterate through the HashMap is not necessarily bad. That will only be O(h)
where h
is the HashMap's length--the number of unique characters--which in this case will always be less than or equal to n
. For the example "aaabbc"
, h = 3
for the three unique characters. But, since h
is strictly less than the number of possible characters: 255, it is constant. So, your big-oh will be O(n+h)
which is actually O(n)
since h
is constant. I don't know of any algorithm that could get a better big-oh, you could try to have a bunch of java specific optimizations, but that said here is a simple algorithm I wrote that finds the char
with the lowest frequency. It returns "c"
from the input "aaabbc"
.
import java.util.HashMap;
import java.util.Map;
public class StackOverflowQuestion {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("" + findLowestFrequency("aaabbc"));
}
public static char findLowestFrequency(String input) {
Map map = new HashMap();
for (char c : input.toCharArray())
if (map.containsKey(c))
map.put(c, map.get(c) + 1);
else
map.put(c, 0);
char rarest = map.keySet().iterator().next();
for (char c : map.keySet())
if (map.get(c) < map.get(rarest))
rarest = c;
return rarest;
}
}