Problem Description
Given an integer array nums, an integer array queries, and an integer x, for each query queries[i] you need to determine the index of the queries[i]th occurrence of x in the nums array. If nums contains fewer than queries[i] occurrences of x, return -1 for that query.
Key Insights
- Pre-process the nums array to record the positions (indices) where the element x appears.
- For each query, check if the occurrence number requested is within the bounds of the precomputed list.
- Return the corresponding index if available; otherwise, return -1.
Space and Time Complexity
Time Complexity: O(n + q) where n is the length of nums (to precompute positions) and q is the length of queries (to answer each query in constant time). Space Complexity: O(n) in the worst case where all elements in nums equal x and are stored in the positions array.
Solution
The solution involves a two-step approach:
- Iterate through the nums array once to store the index of each occurrence of x in a list called positions.
- For each query in queries, check if there is at least as many occurrences as the query specifies by verifying if queries[i] is less than or equal to the length of positions. If yes, return the (queries[i]-1)th element from positions (since it is zero-indexed). Otherwise, return -1.
This approach efficiently handles multiple queries by utilizing precomputed data and simple indexing.