Find Occurrences of an Element in an Array Problem
#3159
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3159.
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.
Example 1:
Input: nums = [1,3,1,7], queries = [1,3,2,4], x = 1
Output: [0,-1,2,-1]
Explanation:
- For the 1^st query, the first occurrence of 1 is at index 0.
- For the 2^nd query, there are only two occurrences of 1 in nums, so the answer is -1.
- For the 3^rd query, the second occurrence of 1 is at index 2.
- For the 4^th query, there are only two occurrences of 1 in nums, so the answer is -1.
Example 2:
Input: nums = [1,2,3], queries = [10], x = 5
Output: [-1]
Explanation:
- For the 1^st query, 5 doesn't exist in nums, so the answer is -1.
Constraints:
1 <= nums.length, queries.length <= 10^51 <= queries[i] <= 10^51 <= nums[i], x <= 10^4
Solution
Approach: Record the Indices
Collect the indices of all elements equal to x in an array ids. For a query i, the answer is ids[i - 1] if i - 1 < len(ids), and -1 otherwise.
Complexity: O(n + q) time and O(n + q) extra space, where n is the length of nums and q the number of queries.
class Solution:
def occurrencesOfElement(
self, nums: List[int], queries: List[int], x: int
) -> List[int]:
ids = [i for i, v in enumerate(nums) if v == x]
return [ids[i - 1] if i - 1 < len(ids) else -1 for i in queries]