DSA interview question
An analytics dashboard receives an array of product IDs from today's orders, then a list of queries: "how many times was product X ordered?" A second panel does the same for letters in a search string: "how many times does 'a' appear?" Scanning the whole array for every query is O(N × Q), which is far too slow when both are 10^5. Hashing fixes this: count everything once up front into a frequency table, and then each query is a single O(1) lookup. This problem introduces the three table types you'll use constantly: a plain array (for small, dense keys like letters), map, and unordered_map.
Example: array [1, 2, 1, 3, 2], queries [1, 3, 4, 12] → [2, 1, 0, 0].
vector<int> countNumbers(const vector<int>& arr, const vector<int>& queries); // unordered_map
vector<int> countLetters(const string& s, const string& queries); // array of 26
| Input | Output | Explanation |
|---|---|---|
arr [1, 2, 1, 3, 2], queries [1, 3, 4, 12] | [2, 1, 0, 0] | Missing keys count as 0 |
arr [1000000000, 5, 1000000000], queries [1000000000, 5] | [2, 1] | Large keys need a map, not an array |
arr [], queries [7] | [0] | Nothing counted |
s "abcdabehf", queries "abfz" | [2, 2, 1, 0] | Letter counts from a size-26 array |
(Confirm: numbers can be up to 10^9, so the numeric table must be a hash map; the string contains lowercase letters only.)
map vs unordered_map?"map.)map vs unordered_map?"unordered_map be attacked?"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