Problem Description
Given an integer array nums and a positive integer k, a subarray’s frequency score is defined as the sum (modulo 10^9 + 7) of each distinct value raised to the power of its frequency in that subarray. For example, the frequency score of [5,4,5,7,4,4] is computed as (4^3 + 5^2 + 7^1) mod (10^9+7) = 96. The task is to return the maximum frequency score among all contiguous subarrays of length k in nums. Note that when comparing scores, we maximize the value as computed under the modulo, not the true large integer value.
Key Insights
- Use a sliding window of size k to traverse the array.
- Maintain a hash table (or dictionary) to track frequencies of each element in the current window.
- Update the frequency score on-the-fly by adjusting only the elements that leave or enter the window.
- On frequency change of an element x from f to f+1, update the score by subtracting x^f and adding x^(f+1) (all operations done modulo 10^9+7).
- Built-in fast modular exponentiation (such as using pow(x, exp, mod)) is used for computing powers efficiently.
Space and Time Complexity
Time Complexity: O(n * log(k)) – each window update computes two modular exponentiations (each taking O(log(k)) time) and there are O(n) windows. Space Complexity: O(k) – used for the frequency hash table for the current window.
Solution
We use a sliding window approach with a hash table to maintain the frequency of each element in the current window. For each window, the frequency score is defined as the sum over distinct numbers x of (x^(frequency)) modulo the mod value. When sliding the window by one element, we update the frequency of the element that is removed and the element that is added. For each update, we subtract the old contribution (x raised to the old frequency) and add the new contribution (x raised to the new frequency). We keep the score modulo 10^9+7 and update the maximum score encountered. This approach efficiently recalculates the frequency score without having to recompute from scratch in each step.