LeetCode 2080: Range Frequency Queries Solution

Master LeetCode problem 2080 (Range Frequency Queries), 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.

2080. Range Frequency Queries

Problem Explanation

Explanation:

To solve this problem efficiently, we can use a combination of prefix sum and a HashMap to keep track of the frequencies of each value in the array.

  1. Initialize a HashMap to store the frequency of each value in the given array.
  2. Calculate the prefix sum of frequencies for each value up to the current index.
  3. When a query is made for a subarray, we can utilize the prefix sum to get the frequency of the value in that subarray.

Time Complexity:

  • Constructing the data structure: O(n)
  • Query operation: O(1)

Space Complexity:

  • O(n) for storing the frequencies in the HashMap.

:

Solution Code

import java.util.HashMap;

class RangeFreqQuery {
    private HashMap<Integer, Integer> freqMap;

    public RangeFreqQuery(int[] arr) {
        freqMap = new HashMap<>();
        for (int num : arr) {
            freqMap.put(num, freqMap.getOrDefault(num, 0) + 1);
        }
    }

    public int query(int left, int right, int value) {
        int count = freqMap.getOrDefault(value, 0);
        if (left > 0) {
            for (int i = 0; i < left; i++) {
                if (arr[i] == value) {
                    count--;
                }
            }
        }
        if (right < arr.length - 1) {
            for (int i = right + 1; i < arr.length; i++) {
                if (arr[i] == value) {
                    count--;
                }
            }
        }
        return count;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2080 (Range Frequency Queries)?

This page provides optimized solutions for LeetCode problem 2080 (Range Frequency Queries) 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 2080 (Range Frequency Queries)?

The time complexity for LeetCode 2080 (Range Frequency Queries) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2080 on DevExCode?

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

Back to LeetCode Solutions