LeetCode solutions

3420. Find Occurrences of an Element in an Array

My accepted Python solution to LeetCode problem 3420, Find Occurrences of an Element in an Array, running in 44ms.

  • Difficulty: Medium
  • Python
  • Runtime 44ms
  • Memory 35.1MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 44ms, memory 35.1MB, accepted 2025-12-31.

python
class Solution:
    def occurrencesOfElement(self, nums: List[int], queries: List[int], x: int) -> List[int]:
        # Find all indices where x occurs
        x_indices = []
        for i, num in enumerate(nums):
            if num == x:
                x_indices.append(i)
        
        # Answer queries
        answer = []
        for q in queries:
            # q is 1-indexed, so q-th occurrence is at index q-1
            if q <= len(x_indices):
                answer.append(x_indices[q - 1])
            else:
                answer.append(-1)
        
        return answer

Source