LeetCode in Kotlin

2080. Range Frequency Queries

Medium

Design a data structure to find the frequency of a given value in a given subarray.

The frequency of a value in a subarray is the number of occurrences of that value in the subarray.

Implement the RangeFreqQuery class:

A subarray is a contiguous sequence of elements within an array. arr[left...right] denotes the subarray that contains the elements of nums between indices left and right (inclusive).

Example 1:

Input

["RangeFreqQuery", "query", "query"]
[[[12, 33, 4, 56, 22, 2, 34, 33, 22, 12, 34, 56]], [1, 2, 4], [0, 11, 33]]

Output: [null, 1, 2]

Explanation:

RangeFreqQuery rangeFreqQuery = new RangeFreqQuery([12, 33, 4, 56, 22, 2, 34, 33, 22, 12, 34, 56]);
rangeFreqQuery.query(1, 2, 4); // return 1. The value 4 occurs 1 time in the subarray [33, 4]
rangeFreqQuery.query(0, 11, 33); // return 2. The value 33 occurs 2 times in the whole array. 

Constraints:

Solution

import java.util.Collections

class RangeFreqQuery(arr: IntArray) {
    private val map: MutableMap<Int, MutableList<Int>>

    init {
        map = HashMap()
        for (i in arr.indices) {
            if (!map.containsKey(arr[i])) {
                map[arr[i]] = ArrayList()
            }
            map[arr[i]]!!.add(i)
        }
    }

    fun query(left: Int, right: Int, value: Int): Int {
        if (!map.containsKey(value)) {
            return 0
        }
        val list: List<Int> = map[value]!!
        var s = Collections.binarySearch(list, left)
        var e = Collections.binarySearch(list, right)
        if (s < 0) {
            s = (s + 1) * -1
        }
        if (e < 0) {
            e = (e + 2) * -1
        }
        return e - s + 1
    }
}
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy