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 an Element in an Array INPUT nums array: 1 i=0 3 i=1 1 i=2 1 i=3 2 i=4 Target x = 1 x = 1 queries array: 1 3 Find 1st and 3rd occurrence of x=1 ALGORITHM STEPS 1 Scan nums array Find all indices where nums[i] == x 2 Store in list occurrences = [0, 2, 3] 0 2 3 1st 2nd 3rd occurrence 3 Process queries For each query q: return occurrences[q-1] 4 Handle edge cases If q > list size, return -1 q=1 --> occ[0] = 0 q=3 --> occ[2] = 3 Result: [0, 3] FINAL RESULT Query Results: Query 1: Find 1st x occurrences[1-1] = occ[0] = 0 (index 0) Query 2: Find 3rd x occurrences[3-1] = occ[2] = 3 (index 3) Output Array: [0, 3] OK - Verified! Key Insight: Pre-compute all occurrence indices of x in O(n) time, then answer each query in O(1) by direct index lookup. Total time complexity: O(n + q) where n = nums length, q = queries count. Space complexity: O(k) where k = number of occurrences of x in nums array. TutorialsPoint - Find Occurrences of an Element in an Array | Optimal Solution Time: O(n + q) Space: O(k)
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