Find Occurrences of an Element in an Array - Problem

You are given an integer array nums, an integer array queries, and an integer x.

For each queries[i], you need to find the index of the queries[i]th occurrence of x in the nums array. If there are fewer than queries[i] occurrences of x, the answer should be -1 for that query.

Return an integer array answer containing the answers to all queries.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,3,1,1,2], queries = [1,3], x = 1
Output: [0,3]
💡 Note: The 1st occurrence of 1 is at index 0. The 3rd occurrence of 1 is at index 3.
Example 2 — Query Not Found
$ Input: nums = [1,2,3], queries = [2], x = 1
Output: [-1]
💡 Note: Element 1 appears only once at index 0, so the 2nd occurrence doesn't exist.
Example 3 — Multiple Queries
$ Input: nums = [1,2,1,2,1], queries = [1,2,3,4], x = 1
Output: [0,2,4,-1]
💡 Note: 1st occurrence at index 0, 2nd at index 2, 3rd at index 4. 4th occurrence doesn't exist.

Constraints

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

Visualization

Tap to expand
Find Occurrences of Element in ArrayInput: nums = [1,3,1,1,2], queries = [1,3], x = 1Step 1: Input Array13112Step 2: Find Positions of x=1idx 0idx 2idx 3Queries1st occ3rd occStep 3: Answer Queries1st occurrence of 1 → index 03rd occurrence of 1 → index 3Output: [0, 3]
Understanding the Visualization
1
Input
Array nums, queries for occurrence positions, target element x
2
Process
Find positions of x, then lookup nth occurrences
3
Output
Array of indices for each query or -1 if not found
Key Takeaway
🎯 Key Insight: Preprocessing occurrence positions enables O(1) query responses
Asked in
Google 15 Amazon 12 Meta 8
12.5K Views
Medium Frequency
~15 min Avg. Time
428 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen