Efficient way to find Frequency of a character in a String in java : O(n)

前端 未结 5 539
野的像风
野的像风 2021-02-03 09:48

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

5条回答
  •  时光取名叫无心
    2021-02-03 10:51

    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;
    
    }
    
    }
    

提交回复
热议问题