Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
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:
nums, so the answer is -1.nums, so the answer is -1.Example 2:
Input: nums = [1,2,3], queries = [10], x = 5
Output: [-1]
Explanation:
nums, so the answer is -1.Constraints:
1 <= nums.length, queries.length <= 1051 <= queries[i] <= 1051 <= nums[i], x <= 104Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map
[1,3,1,7] [1,3,2,4] 1
[1,2,3] [10] 5
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3159: Find Occurrences of an Element in an Array
class Solution {
public int[] occurrencesOfElement(int[] nums, int[] queries, int x) {
List<Integer> ids = new ArrayList<>();
for (int i = 0; i < nums.length; ++i) {
if (nums[i] == x) {
ids.add(i);
}
}
int m = queries.length;
int[] ans = new int[m];
for (int i = 0; i < m; ++i) {
int j = queries[i] - 1;
ans[i] = j < ids.size() ? ids.get(j) : -1;
}
return ans;
}
}
// Accepted solution for LeetCode #3159: Find Occurrences of an Element in an Array
func occurrencesOfElement(nums []int, queries []int, x int) (ans []int) {
ids := []int{}
for i, v := range nums {
if v == x {
ids = append(ids, i)
}
}
for _, i := range queries {
if i-1 < len(ids) {
ans = append(ans, ids[i-1])
} else {
ans = append(ans, -1)
}
}
return
}
# Accepted solution for LeetCode #3159: Find Occurrences of an Element in an Array
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]
// Accepted solution for LeetCode #3159: Find Occurrences of an Element in an Array
/**
* [3159] Find Occurrences of an Element in an Array
*/
pub struct Solution {}
// submission codes start here
impl Solution {
pub fn occurrences_of_element(nums: Vec<i32>, queries: Vec<i32>, x: i32) -> Vec<i32> {
let x_pos: Vec<usize> = nums
.iter()
.enumerate()
.filter_map(|(i, v)| if *v == x { Some(i) } else { None })
.collect();
let result = queries
.into_iter()
.map(|x| {
let x = x as usize - 1;
if x >= x_pos.len() {
-1
} else {
x_pos[x] as i32
}
})
.collect();
result
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_3159() {
assert_eq!(
vec![0, -1, 2, -1],
Solution::occurrences_of_element(vec![1, 3, 1, 7], vec![1, 3, 2, 4], 1)
);
assert_eq!(
vec![-1],
Solution::occurrences_of_element(vec![1, 2, 3], vec![10], 5)
);
}
}
// Accepted solution for LeetCode #3159: Find Occurrences of an Element in an Array
function occurrencesOfElement(nums: number[], queries: number[], x: number): number[] {
const ids: number[] = nums.map((v, i) => (v === x ? i : -1)).filter(v => v !== -1);
return queries.map(i => ids[i - 1] ?? -1);
}
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.
Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.