LeetCode 3159: Find Occurrences of an Element in an Array Solution

Master LeetCode problem 3159 (Find Occurrences of an Element in an Array), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

3159. Find Occurrences of an Element in an Array

Problem Explanation

Explanation:

To solve this problem, we can iterate through the nums array and maintain a hashmap to store the indices of occurrences of element x. Then, for each query, we can check the hashmap to find the corresponding index of the queries[i]th occurrence of x.

  1. Iterate through the nums array and store the indices of occurrences of x in a hashmap.
  2. For each query in the queries array, check if there are enough occurrences of x and return the corresponding index from the hashmap.
  3. If there are fewer occurrences of x, return -1 for that query.
  4. Return the array of answers.

Time Complexity:

  • O(N) where N is the length of the nums array, as we iterate through the array to build the hashmap and for each query.

Space Complexity:

  • O(N) to store the hashmap of indices.

:

Solution Code

class Solution {
    public int[] findOccurrences(int[] nums, int[] queries, int x) {
        Map<Integer, List<Integer>> indexMap = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == x) {
                indexMap.computeIfAbsent(nums[i], k -> new ArrayList<>()).add(i);
            }
        }
        
        int[] answer = new int[queries.length];
        for (int i = 0; i < queries.length; i++) {
            List<Integer> indices = indexMap.getOrDefault(x, new ArrayList<>());
            if (queries[i] <= indices.size()) {
                answer[i] = indices.get(queries[i] - 1);
            } else {
                answer[i] = -1;
            }
        }
        
        return answer;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 3159 (Find Occurrences of an Element in an Array)?

This page provides optimized solutions for LeetCode problem 3159 (Find Occurrences of an Element in an Array) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 3159 (Find Occurrences of an Element in an Array)?

The time complexity for LeetCode 3159 (Find Occurrences of an Element in an Array) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 3159 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3159 in Java, C++, or Python.

Back to LeetCode Solutions