Foundations Counting with arrays and maps

42. Count the Frequency of Each Element

Easy

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]

Output: [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]

Output: [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]

Output: [0,3,0]

Check your understanding

Work out the answer for this input before you write any code.

nums = [3, -1, 3, 3, 8], queries = [3, 8, -1, 2]

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ queries.length ≤ 105
  • -109 ≤ nums[i], queries[j] ≤ 109

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.