Foundations Counting with arrays and maps
42. Count the Frequency of Each Element
You are given an array of integers nums and an array of integers queries. For each query, count how many
times its value appears in nums.
Return a list of these counts, one for each query, in the same order as queries. So the first count is for
queries[0], the second for queries[1], and so on. A value that does not appear in nums has a count of 0.
If the same value is asked about twice, answer it both times.
Example 1
Input: nums = [4, -2, 4, 7, -2, 4], queries = [4, 7, 5, -2]
[3,1,0,2]Explanation: 4 appears three times, 7 once and −2 twice. 5 does not appear in nums, so its count is 0.
Example 2
Input: nums = [1000000000, -1000000000, 1000000000]
queries = [1000000000, 0, -1000000000, 1000000000]
[2,0,1,2]Explanation: 109 is asked about twice, so its count, 2, appears twice in the answer.
Example 3
Input: nums = [0, 0, 0], queries = [-1, 0, 1]
[0,3,0]Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ nums.length ≤ 1051 ≤ queries.length ≤ 105-109 ≤ nums[i], queries[j] ≤ 109
Clarifying questions
What you would ask an interviewer before writing any code.