Frequency Counter Pattern Using Hash Map in DSA Java - Time & Space Complexity
We want to understand how fast the frequency counter pattern runs when counting items.
How does the time needed grow as the list gets bigger?
Analyze the time complexity of the following code snippet.
public static Map<Integer, Integer> frequencyCounter(int[] arr) {
Map<Integer, Integer> freqMap = new HashMap<>();
for (int num : arr) {
freqMap.put(num, freqMap.getOrDefault(num, 0) + 1);
}
return freqMap;
}
This code counts how many times each number appears in the array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each element in the array once.
- How many times: Exactly once for each item in the input array.
As the array gets bigger, the code checks each number once and updates the count.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks and updates |
| 100 | About 100 checks and updates |
| 1000 | About 1000 checks and updates |
Pattern observation: The number of operations grows directly with the input size.
Time Complexity: O(n)
This means the time to count frequencies grows in a straight line with the number of items.
[X] Wrong: "Using a hash map makes the code slower because of extra lookups inside the loop."
[OK] Correct: Hash map lookups and updates happen in constant time on average, so they do not slow down the loop significantly.
Knowing how frequency counting works and its time cost helps you solve many problems efficiently.
"What if we used a nested loop to count frequencies instead of a hash map? How would the time complexity change?"
Practice
Solution
Step 1: Understand the role of a hash map
A hash map stores key-value pairs, allowing quick lookup and update of counts.Step 2: Apply to frequency counting
By using elements as keys and counts as values, it tracks how many times each element appears.Final Answer:
To count how many times each element appears in a collection -> Option AQuick Check:
Frequency counting = count elements [OK]
- Thinking hash map sorts elements
- Confusing frequency counting with removing duplicates
- Using hash map to reverse order
Solution
Step 1: Identify correct generic types for HashMap
Keys are characters, so use Character; values are counts, so use Integer.Step 2: Check syntax correctness
HashMap freq = new HashMap<>(); is valid Java syntax.Final Answer:
HashMap freq = new HashMap<>(); -> Option BQuick Check:
Correct generics and syntax = HashMap freq = new HashMap<>(); [OK]
- Using primitive types like int in generics
- Missing value type in HashMap declaration
- Incorrect generic syntax
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
String s = "banana";
HashMap freq = new HashMap<>();
for (char c : s.toCharArray()) {
freq.put(c, freq.getOrDefault(c, 0) + 1);
}
System.out.println(freq.get('a'));
}
}Solution
Step 1: Count occurrences of 'a' in "banana"
String "banana" has 'a' at positions 1, 3, and 5, total 3 times.Step 2: Check code logic for frequency counting
Code uses getOrDefault to count each character's frequency correctly.Final Answer:
3 -> Option DQuick Check:
Count of 'a' in "banana" = 3 [OK]
- Counting 'a' incorrectly as 2 or 1
- Confusing getOrDefault behavior
- Expecting null for existing keys
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
int[] nums = {1, 2, 2, 3};
HashMap freq = new HashMap<>();
for (int num : nums) {
freq.put(num, freq.get(num) + 1);
}
System.out.println(freq);
}
}Solution
Step 1: Analyze freq.get(num) usage inside loop
freq.get(num) returns null if key not present, so null + 1 causes NullPointerException.Step 2: Identify missing default value handling
Code should use freq.getOrDefault(num, 0) to avoid null on first occurrence.Final Answer:
Using freq.get(num) without checking if key exists causes NullPointerException -> Option AQuick Check:
NullPointerException due to missing default value [OK]
- Ignoring possibility of null from get()
- Thinking HashMap declaration is wrong
- Assuming printing freq causes error
arr1 and arr2, which Java code snippet correctly checks if arr2 contains the same frequency of elements as arr1 using the Frequency Counter Pattern?Solution
Step 1: Understand frequency counting for both arrays
Count frequencies of arr1 elements positively, then subtract frequencies for arr2 elements.Step 2: Verify all counts are zero
If all counts are zero, frequencies match; otherwise, they differ.Final Answer:
Code that increments for arr1, decrements for arr2, then checks zero counts -> Option CQuick Check:
Increment then decrement counts, check zero [OK]
- Checking sizes of two separate maps instead of contents
- Adding counts for both arrays instead of subtracting
- Checking map size instead of counts
Ready to prove it?
Pass the test and this pattern moves unknown
