Character Frequency Counting in DSA Java - Time & Space Complexity
Counting how often each character appears in a string helps us understand the cost of this task.
We want to know how the time needed grows as the string gets longer.
Analyze the time complexity of the following code snippet.
public Map<Character, Integer> countFrequency(String text) {
Map<Character, Integer> freqMap = new HashMap<>();
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
freqMap.put(c, freqMap.getOrDefault(c, 0) + 1);
}
return freqMap;
}
This code counts how many times each character appears in the given string.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each character in the string once.
- How many times: Exactly once for each character, so as many times as the string length.
As the string gets longer, the number of steps grows directly with its length.
| 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 the input size.
Time Complexity: O(n)
This means the time needed grows directly in proportion to the string length.
[X] Wrong: "Since we use a map inside the loop, the time is O(n²)."
[OK] Correct: Each map operation (get/put) is on average constant time, so it does not multiply the loop steps.
Understanding this helps you explain how simple loops and data structures work together efficiently in real tasks.
"What if we used a sorted map instead of a hash map? How would the time complexity change?"
Practice
Solution
Step 1: Understand the purpose of frequency counting
Frequency counting means counting how many times each character appears in a string.Step 2: Identify what frequency counting returns
It returns a count for each character, not the length or position.Final Answer:
How many times each character appears in the string -> Option CQuick Check:
Frequency counting = character counts [OK]
- Confusing frequency with string length
- Thinking frequency gives character positions
- Assuming frequency returns only unique characters
Solution
Step 1: Identify data structure needs
We need to map each character to its count, so a key-value pair structure is needed.Step 2: Choose the correct Java collection
HashMap stores characters as keys and their counts as values.Final Answer:
HashMap -> Option AQuick Check:
Map characters to counts = HashMap [OK]
- Using ArrayList which doesn't map keys to values
- Choosing LinkedList which is a list, not a map
- Using Stack which is for LIFO, not frequency counting
String s = "hello";
Map freq = new HashMap<>();
for (char c : s.toCharArray()) {
freq.put(c, freq.getOrDefault(c, 0) + 1);
}
System.out.println(freq);Solution
Step 1: Count characters in "hello"
Characters: h(1), e(1), l(2), o(1).Step 2: Check code logic for counting
Code uses getOrDefault to add 1 to existing count or start at 0, correctly counting frequencies.Final Answer:
{h=1, e=1, l=2, o=1} -> Option BQuick Check:
Count 'l' twice, others once = {h=1, e=1, l=2, o=1} [OK]
- Counting 'l' only once
- Confusing getOrDefault usage
- Expecting syntax error incorrectly
String s = "test";
Map freq = new HashMap<>();
for (int i = 0; i <= s.length(); i++) {
char c = s.charAt(i);
freq.put(c, freq.getOrDefault(c, 0) + 1);
}Solution
Step 1: Analyze loop condition
Loop uses i <= s.length(), but valid indices are 0 to s.length()-1.Step 2: Identify error consequence
Accessing s.charAt(s.length()) causes IndexOutOfBoundsException at runtime.Final Answer:
Using <= in loop causes IndexOutOfBoundsException -> Option AQuick Check:
Loop index must be less than length [OK]
- Thinking HashMap can't store Character keys
- Assuming getOrDefault is unavailable
- Believing charAt doesn't exist for String
Solution
Step 1: Understand case-insensitive counting
To treat 'A' and 'a' the same, convert all characters to one case.Step 2: Choose best method
Converting entire string to lowercase before counting ensures all letters are uniform.Final Answer:
Convert string to lowercase before counting frequencies -> Option DQuick Check:
Uniform case simplifies frequency counting [OK]
- Counting uppercase and lowercase separately
- Using TreeMap which doesn't solve case issue
- Ignoring uppercase letters incorrectly
Ready to prove it?
Pass the test and this pattern moves unknown
