Mastery Points
0

Character Frequency maps in dsa

Context & Logic

Character frequency involves counting how many times each character appears in a string. This is usually done using a Hash Map or an object in JavaScript.

Example

function getFrequency(str) {
    const freq = {};
    for (let char of str) {
        freq[char] = (freq[char] || 0) + 1;
    }
    return freq;
}
// getFrequency("hello") -> { h: 1, e: 1, l: 2, o: 1 }

Step-by-Step Logic

1

Initialize an empty frequency object.

2

Loop through each character of the string.

3

Check if the character exists as a key in the object.

4

If it exists, increment its value; if not, initialize it to 1.

Complexity Metrics

Time Efficiency

O(n)

Memory Footprint

O(k) where k is the character set size