DSA interview question
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.
vector<pair<int, int>> frequencies(const vector<int>& arr); // (value, count) in first-appearance order
Input arr | Output | Explanation |
|---|---|---|
[10, 5, 10, 15, 10, 5] | 10:3 5:2 15:1 | Ordered by first appearance, not by value |
[2, 2, 2, 2] | 2:4 | A single distinct value |
[1] | 1:1 | |
[] | (empty) | |
[-1, 0, -1] | -1:2 0:1 | Negative 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.)
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 interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in