oneby7

Binary Search Lower and upper bounds

230. Count Occurrences in a Sorted Array

Medium

You are given an array of integers nums, sorted in non-decreasing order, and an array targets. A value can appear in nums any number of times. For each target, count how many elements of nums are equal to it.

Return an array answer with one entry per target, in the order the targets are given: answer[j] is the number of times targets[j] appears in nums. A target that does not appear has a count of 0.

The targets come in any order, and the same target can appear more than once.

Example 1

Input: nums = [-4, 2, 2, 2, 7, 7, 11, 15] targets = [2, 7, 5, 15]

Output: [3,2,0,1]

Explanation: 2 fills indexes 1 to 3, so it appears 3 times. 7 appears twice and 15 once. No element equals 5, so its count is 0.

Example 2

Input: nums = [6, 6, 6, 6, 6], targets = [6, 5, 7]

Output: [5,0,0]

Explanation: Every element is 6, so 6 appears 5 times. The targets 5 and 7 sit just below and just above it, and neither appears.

Example 3

Input: nums = [-1000000000, -1000000000, 0, 1000000000, 1000000000, 1000000000] targets = [1000000000, -1000000000, 0, 0, 1]

Output: [3,2,1,1,0]

Explanation: The largest allowed value fills the last three places and the smallest the first two. 0 is asked twice, and each copy gets its own answer.

Check your understanding

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

nums = [1, 3, 3, 3, 8], targets = [3, 4]

Constraints

  • 1 ≤ nums.length ≤ 105
  • -109 ≤ nums[i] ≤ 109
  • nums[i] ≤ nums[i + 1] (non-decreasing)
  • 1 ≤ targets.length ≤ 105
  • -109 ≤ targets[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

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

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

New here? This creates your account too.