Count Frequency of Characters in a String

Problem

Count the frequency of each character in a string.

Input:  s = "aabbbc"
Output: {'a': 2, 'b': 3, 'c': 1}

Python Solution

def char_frequency(s):
    counts = {}
    for ch in s:
        counts[ch] = counts.get(ch, 0) + 1
    return counts

C++ Solution

unordered_map<char, int> charFrequency(string s) {
    unordered_map<char, int> counts;
    for (char ch : s) counts[ch]++;
    return counts;
}

Java Solution

class Solution {
    public Map<Character, Integer> charFrequency(String s) {
        Map<Character, Integer> counts = new HashMap<>();
        for (char ch : s.toCharArray()) {
            counts.put(ch, counts.getOrDefault(ch, 0) + 1);
        }
        return counts;
    }
}

Complexity

Time: O(n) — one pass over the string, one hash map update per character. Space: O(k) — where k is the number of distinct characters, at most the size of the alphabet used.

Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.