#3159
Medium Algorithms Find occurrences of an element in an array
Array Hash Table
73.3% acceptance
Feb 24, 2026
181
25
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.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn occurrences_of_element(nums: Vec<i32>, queries: Vec<i32>, x: i32) -> Vec<i32> {
let indices: Vec<i32> = nums
.iter()
.enumerate()
.filter(|&(_, &v)| v == x)
.map(|(i, _)| i as i32)
.collect();
queries
.iter()
.map(|&q| {
let idx = (q - 1) as usize;
if idx < indices.len() {
indices[idx]
} else {
-1
}
})
.collect()
}
}