#3159

Find Occurrences of an Element in an Array

Medium
ArrayHash TableHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n + m)
Space
O(1)
O(n)
💡

Intuition

Time O(n + m)Space O(n)

The optimal approach involves precomputing the indices of all occurrences of x in the nums array. This allows each query to be answered in constant time, significantly improving efficiency.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a list to store indices of occurrences of x in nums.
  2. 2Step 2: Iterate through nums and populate the list with indices where x is found.
  3. 3Step 3: For each query, check if the requested occurrence exists in the list; if yes, return the index, otherwise return -1.
solution.py3 lines
1def find_occurrences(nums, queries, x):
2    indices = [i for i, num in enumerate(nums) if num == x]
3    return [indices[q - 1] if q - 1 < len(indices) else -1 for q in queries]

Complexity note: The time complexity is O(n + m), where n is the length of nums and m is the length of queries. We first scan nums to find occurrences (O(n)) and then answer each query in O(1) time (O(m)).

  • 1Precomputing indices allows for faster query responses.
  • 2Understanding the problem constraints helps in choosing the right approach.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.