Find Occurrences of an Element in an Array - Problem
Imagine you're a data analyst working with search logs, and you need to quickly find the nth occurrence of specific search terms across your database. This problem captures that exact scenario!
You are given an integer array nums, an integer array queries, and a target integer x. For each query queries[i], you need to find the index where the queries[i]-th occurrence of x appears in the nums array.
Key Rules:
- If there are fewer than
queries[i]occurrences ofx, return-1for that query - Occurrences are counted from left to right (1st, 2nd, 3rd, etc.)
- Return an integer array containing answers to all queries
Example: If nums = [1, 3, 1, 7, 1], x = 1, and queries = [1, 3, 2], then the 1st occurrence of 1 is at index 0, the 3rd occurrence is at index 4, and the 2nd occurrence is at index 2. Answer: [0, 4, 2]
Input & Output
example_1.py โ Basic Case
$
Input:
nums = [1,3,1,7,1], queries = [1,3,2], x = 1
โบ
Output:
[0,4,2]
๐ก Note:
The 1st occurrence of x = 1 is at index 0. The 3rd occurrence of x = 1 is at index 4. The 2nd occurrence of x = 1 is at index 2.
example_2.py โ Query Exceeds Occurrences
$
Input:
nums = [1,2,3], queries = [10], x = 5
โบ
Output:
[-1]
๐ก Note:
x = 5 doesn't appear in nums, so the 10th occurrence doesn't exist. Return -1.
example_3.py โ Mixed Valid and Invalid Queries
$
Input:
nums = [5,2,5,4], queries = [2,4], x = 5
โบ
Output:
[2,-1]
๐ก Note:
The 2nd occurrence of x = 5 is at index 2. The 4th occurrence doesn't exist since x only appears twice.
Constraints
- 1 โค nums.length โค 105
- 1 โค queries.length โค 105
- 1 โค queries[i] โค 105
- 1 โค nums[i], x โค 109
Visualization
Tap to expand
Understanding the Visualization
1
Create Index
Walk through the library once and note all positions where 'Harry Potter' appears
2
Answer Queries
When someone asks for the 2nd copy, instantly look up position from our index
3
Handle Missing
If someone asks for the 5th copy but we only have 3, return 'Not Found'
Key Takeaway
๐ฏ Key Insight: Preprocessing data once allows us to answer multiple queries efficiently, transforming O(nรm) brute force into O(n+m) optimal solution!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code