Frequency Counter Pattern Using Hash Map in DSA Typescript - Time & Space Complexity
We want to understand how fast we can count how many times each item appears in a list using a hash map.
How does the time needed grow as the list gets bigger?
Analyze the time complexity of the following code snippet.
function frequencyCounter(arr: number[]): Record {
const freqMap: Record = {};
for (const num of arr) {
freqMap[num] = (freqMap[num] || 0) + 1;
}
return freqMap;
}
This code counts how many times each number appears in the array and stores the counts in a hash map.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each element of the array once.
- How many times: Exactly once for each item in the array (n times).
As the array gets bigger, the number of steps grows directly with the number of items.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 steps |
| 100 | About 100 steps |
| 1000 | About 1000 steps |
Pattern observation: The work grows in a straight line with input size; doubling input doubles work.
Time Complexity: O(n)
This means the time to count frequencies grows directly with the number of items in the array.
[X] Wrong: "Using a hash map makes counting frequencies take constant time no matter the array size."
[OK] Correct: While each insertion or update in the hash map is fast, you still have to look at every item in the array, so time grows with the array size.
Counting frequencies efficiently is a common skill that shows you understand how to use hash maps to speed up problems that need counting or matching.
"What if the input array was already sorted? How would that change the time complexity of counting frequencies?"
Practice
Solution
Step 1: Understand frequency counting
The frequency counter pattern counts occurrences of each item in a collection.Step 2: Recognize hash map usage
A hash map stores each item as a key and its count as the value for quick lookup.Final Answer:
To count how many times each item appears in a collection -> Option BQuick Check:
Frequency counter = count items [OK]
- Confusing frequency counting with sorting
- Thinking it removes duplicates instead of counting
- Assuming it reverses arrays
Solution
Step 1: Identify correct hash map initialization
In TypeScript, an object with string keys and number values is used for frequency counting.Step 2: Check each option
const freq: Record = {}; uses Record = {} which is correct. Others are array, set, or number, which are incorrect for frequency counting.Final Answer:
const freq: Record = {}; -> Option CQuick Check:
Empty object for frequency map [OK]
- Using array or set instead of object
- Initializing frequency counter as a number
- Not specifying key-value structure
const arr = ['a', 'b', 'a', 'c', 'b', 'a'];
const freq: Record = {};
for (const char of arr) {
freq[char] = (freq[char] || 0) + 1;
}
console.log(freq);Solution
Step 1: Loop through array and count frequencies
Each character's count is incremented in freq. 'a' appears 3 times, 'b' 2 times, 'c' 1 time.Step 2: Output the freq object
console.log prints the object with counts: {"a": 3, "b": 2, "c": 1}.Final Answer:
{"a": 3, "b": 2, "c": 1} -> Option AQuick Check:
Count each char correctly [OK]
- Printing array instead of object
- Not initializing counts to zero
- Trying to iterate freq as array
const str = "hello";
const freq: Record = {};
for (let i = 0; i <= str.length; i++) {
const char = str[i];
freq[char] = (freq[char] || 0) + 1;
}
console.log(freq);Solution
Step 1: Check loop boundary
The loop runs from i = 0 to i <= str.length, which accesses str[str.length] (undefined).Step 2: Fix loop condition
Change condition to i < str.length to avoid accessing undefined character.Final Answer:
Loop condition should be i < str.length, not i <= str.length -> Option DQuick Check:
Loop index must be less than length [OK]
- Using <= instead of < in loop condition
- Initializing freq as array instead of object
- Declaring variables outside loop unnecessarily
arr1 and arr2, which TypeScript function correctly uses the frequency counter pattern to check if arr2 contains the squares of all elements in arr1 with the same frequency?Solution
Step 1: Build frequency maps for both arrays
freq1 counts elements in arr1, freq2 counts elements in arr2.Step 2: Check if freq2 has squares of keys in freq1 with same counts
Loop over freq1 keys, verify freq2 has key squared with equal frequency.Step 3: Return true if all match, else false
If any mismatch found, return false; otherwise, return true.Final Answer:
Function in Option A correctly implements frequency counter for squares check -> Option AQuick Check:
Compare frequencies of numbers and their squares [OK]
- Not comparing frequencies, only presence
- Checking squares incorrectly (num * num vs key squared)
- Ignoring frequency counts in second array
Ready to prove it?
Pass the test and this pattern moves unknown
