Counter

2 snippets across 2 stacks - Interview Prep, Python

DSAInterview Prep

Frequency Counting

DSA · Hash Maps & Sets
Syntax
Build a map of element → count.
Useful for: most common element, anagrams, character counting, voting problems.
Example
// JavaScript
function frequencyMap(arr) {
  const freq = new Map();
  for (const item of arr) {
    freq.set(item, (freq.get(item) || 0) + 1);
  }
  return freq;
}

function mostFrequent(arr) {
  const freq = frequencyMap(arr);
  let maxCount = 0, result = null;
  for (const [key, count] of freq) {
    if (count > maxCount) { maxCount = count; result = key; }
  }
  return result;
}

# Python
from collections import Counter

def frequency_map(arr):
    freq = {}
    for item in arr:
        freq[item] = freq.get(item, 0) + 1
    return freq

def most_frequent(arr):
    return Counter(arr).most_common(1)[0][0]
Output
most_frequent([1,2,2,3,3,3]) → 3

Note Time O(n), Space O(k) where k is unique elements. Python's Counter is a powerful shortcut. In interviews, building the map manually shows understanding. Tie-breaking: clarify with interviewer what to return if multiple elements share max frequency.

PYPython

Counter

PY · Dictionaries
Syntax
from collections import Counter
Example
from collections import Counter

letters = Counter("mississippi")
print(letters.most_common(3))

inventory = Counter(apples=5, oranges=3)
inventory.update(apples=2)
print(inventory["apples"])
Output
[('s', 4), ('i', 4), ('p', 2)]
7

Note Counter supports arithmetic: Counter('aab') - Counter('ab') gives Counter({'a': 1}). most_common() returns elements in descending frequency.

Frequently asked questions

How does Interview Prep handle counter?
This task is covered in 2 stacks on this page: Interview Prep, Python. The "Frequency Counting" snippet in Interview Prep uses `Build a map of element → count.`.
Which code does the Interview Prep example use?
The "Frequency Counting" snippet uses `Build a map of element → count.`, from the Hash Maps & Sets section of the Interview Prep cheat sheet.
Which stacks cover "counter" on this page?
Interview Prep, Python. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Frequency Counting": Time O(n), Space O(k) where k is unique elements. Python's Counter is a powerful shortcut. In interviews, building the map manually shows understanding. Tie-breaking: clarify with interviewer what to return if multiple elements share max frequency.