Skip to content

3159. Find Occurrences of an Element in an Array 👍

  • Time: $O(n + q)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
 public:
  vector<int> occurrencesOfElement(vector<int>& nums, vector<int>& queries,
                                   int x) {
    const vector<int> indices = getIndices(nums, x);
    vector<int> ans;

    for (const int query : queries)
      ans.push_back(query <= indices.size() ? indices[query - 1] : -1);

    return ans;
  }

 private:
  vector<int> getIndices(const vector<int>& nums, int x) {
    vector<int> indices;
    for (int i = 0; i < nums.size(); ++i)
      if (nums[i] == x)
        indices.push_back(i);
    return indices;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
  public int[] occurrencesOfElement(int[] nums, int[] queries, int x) {
    List<Integer> indices = getIndices(nums, x);
    int[] ans = new int[queries.length];

    for (int i = 0; i < queries.length; i++)
      ans[i] = queries[i] <= indices.size() ? indices.get(queries[i] - 1) : -1;

    return ans;
  }

  private List<Integer> getIndices(int[] nums, int x) {
    List<Integer> indices = new ArrayList<>();
    for (int i = 0; i < nums.length; ++i)
      if (nums[i] == x)
        indices.add(i);
    return indices;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution:
  def occurrencesOfElement(
      self,
      nums: list[int],
      queries: list[int],
      x: int,
  ) -> list[int]:
    indices = [i for i, num in enumerate(nums) if num == x]
    return [indices[query - 1] if query <= len(indices) else -1
            for query in queries]