PPractick

DSA interview question

Counting Frequencies of Array Elements

Easy · Algorithms · Topics: hashing, array, frequency map

The problem

A survey app collects answers as numeric option codes, and the results screen must list each distinct answer with how many times it was chosen, in the order the answers first appeared, so the list matches what respondents saw. Counting with nested loops (for each element, scan the whole array) is O(N²) and also prints duplicates unless you track what's already been reported. A hash map does the counting in one pass, and a second pass over the original array gives the first-appearance order.

Example: [10, 5, 10, 15, 10, 5] → 10: 3, 5: 2, 15: 1.

Function signature

vector<pair<int, int>> frequencies(const vector<int>& arr);  // (value, count) in first-appearance order

Test cases

Input arrOutputExplanation
[10, 5, 10, 15, 10, 5]10:3 5:2 15:1Ordered by first appearance, not by value
[2, 2, 2, 2]2:4A single distinct value
[1]1:1
[](empty)
[-1, 0, -1]-1:2 0:1Negative values work with a hash map

(Confirm: values can be any int, including negatives; each distinct value is reported once, in order of first appearance.)

How interviewers phrase it

Clarifying questions to ask

  1. What range can the values take? (Small range → array; otherwise hash map.)
  2. In what order should the output be: first appearance, sorted by value, or any order?
  3. Can I use extra space, or must it be in place?
  4. How large is N?

Follow-ups to expect

  1. "What's wrong with the nested-loop approach?"
  2. "How do you keep first-appearance order?"
  3. "What if the values are 1..N and you can't use extra space?"
  4. "Sorted by value instead?"
  5. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in