What's more efficient for counting, Arrays or Hashmap(or Set)

Viewed 58

Assume we're asked to count and print the occurrences of each character in a given String. For simplicity, the string has just lowercase letters. I wrote these 2 functions and I want to know which one is more efficient/preferable in Java.

Function 1:

private void countAndPrintArray1(String str){
        int[] a = new int[26];
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            int index = c - 'a';
            a[index] = a[index] + 1;
        }

        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            int freq = a[c -'a'];
            System.out.println(c+" -> "+ freq);
        }
    }

Function 2:

    private void countAndPrintArray2(String str){
        Map<Character, Integer> map = new HashMap<>();

        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            int freq = map.getOrDefault(c, 0) + 1;
            map.put(c, freq);
        }

        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            int freq = map.get(c);
            System.out.println(c+" -> "+ freq);
        }
    }
1 Answers

Comparing the two approaches based on their performances, both of the algorithms run in O(n) time complexity where n is the size of the string provided. Also, the space complexity is O(1) in both cases. Talking about the preference, it depends on the developer and the team which is developing the product. Though the HashMap approach seems to be more elite and clean (again developer opinion).

Related