Frequency of the Most Frequent Element

Medium Arrays & Hashing Sliding Window · Variable

Frequency of the Most Frequent Element is a medium arrays & hashing problem solved with the sliding window · variable pattern. The best approach, optimal (sort and slide a window), runs in O(n log n) time and O(1) space. Below are 3 approaches in Java, Python, C++ and JavaScript, from brute force (grow left from every target) up.

Problem

You are given an integer array nums and an integer k. In one operation you may pick any index and add 1 to the value stored there. You may perform at most k operations in total, spread over the elements however you like.

The frequency of a value is the number of times it appears in the array. After performing your operations, return the largest frequency that any single value can have.

Examples

Example 1

Input
nums = [3,1,4,2], k = 4
Output
3
Why
Sorted, the array is [1,2,3,4]. Raising 2 and 3 up to 4 costs 2 + 1 = 3 increments, which is within 4, and gives three 4s. Making all four values equal would cost at least 6, so 3 is the best.

Example 2

Input
nums = [5,9,2,7], k = 3
Output
2
Why
Raising the 5 to 7 costs 2 and gives two 7s. Any group of three needs at least 4 increments (5 and 7 up to 9 costs 4 + 2 = 6; 2 and 5 up to 7 costs 5 + 2 = 7), so the answer is 2.

Example 3

Input
nums = [10,20,30], k = 1
Output
1
Why
The values are 10 apart and one increment closes none of the gaps, so every value stays alone.

Constraints

  • 1 <= nums.length <= 10^5
  • 1 <= nums[i] <= 10^5
  • 1 <= k <= 10^5

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (3 examples, or your own). Submit also runs 14 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Brute force (grow left from every target)O(n^2)O(1)
Prefix sums and binary searchO(n log n)O(n)
Optimal (sort and slide a window)O(n log n)O(1)

1Brute force (grow left from every target)

TimeO(n^2)Sorting is O(n log n), but each of the n targets can walk back over up to n values.
SpaceO(1)Only a few variables besides the sort.

Increments only go up, so a group made equal ends at its largest value, and the cheapest values to pull up are the ones closest below it. Sort the array. Then try each element as the target and walk left from it, adding the cost of raising each next smaller value, for as long as the total stays within k. The longest run found is the answer.

  1. Sort nums.
  2. For each index i, start with cost = 0 and j = i.
  3. While j > 0 and cost + (nums[i] - nums[j - 1]) <= k, add that amount to cost and move j left.
  4. The group nums[j..i] can all become nums[i]; keep the largest i - j + 1.
class Solution {
    public int maxFrequency(int[] nums, int k) {
        Arrays.sort(nums);
        int best = 0;
        for (int i = 0; i < nums.length; i++) {
            long cost = 0;
            int j = i;
            while (j > 0 && cost + (nums[i] - nums[j - 1]) <= k) {
                cost += nums[i] - nums[j - 1];
                j--;
            }
            best = Math.max(best, i - j + 1);
        }
        return best;
    }
}

3Optimal (sort and slide a window)

TimeO(n log n)Sorting dominates. After it, r and l each move at most n times, so the window pass is O(n).
SpaceO(1)Only a few variables, apart from the space the sort uses.

Sort, then keep a window nums[l..r] whose values can all be raised to nums[r] within k, along with its running sum. The cost of the window is nums[r] * (r - l + 1) - sum. Moving r to the right raises the target, which can only make the cost bigger, so the left edge never has to move back: whenever the cost goes over k, drop values from the left until it fits again. The widest window seen is the answer.

  1. Sort nums. Set l = 0, sum = 0, best = 0.
  2. For each r: add nums[r] to sum.
  3. While nums[r] * (r - l + 1) - sum > k: subtract nums[l] from sum and move l right.
  4. best = max(best, r - l + 1). Return best.
class Solution {
    public int maxFrequency(int[] nums, int k) {
        Arrays.sort(nums);
        long sum = 0;
        int l = 0, best = 0;
        for (int r = 0; r < nums.length; r++) {
            sum += nums[r];
            while ((long) nums[r] * (r - l + 1) - sum > k) {
                sum -= nums[l];
                l++;
            }
            best = Math.max(best, r - l + 1);
        }
        return best;
    }
}

Edge cases to test

  • A single element: the answer is 1
  • All values already equal: the answer is n, with no increments spent
  • k is large enough to raise everything to the maximum: the answer is n
  • The gaps are too big for any increment to help: the answer is 1
  • Duplicates in the input: equal values cost nothing to join
  • The cost of a window can reach about 10^10, more than an int holds: use a long for sums and products
  • Values can only go up, so the target of a group is always its largest member

Hints

Hint 1

You can only increase values. If a group of numbers is turned into one value, which value is the cheapest choice?

Hint 2

After sorting, the cheapest group that ends at a given target is the run of values just below it. Why is skipping a value never better?

Hint 3

The cost of raising a window nums[l..r] to nums[r] is nums[r] * (r - l + 1) - sum(nums[l..r]). As r moves right, does l ever need to move left?

FAQ

What is the best time complexity for Frequency of the Most Frequent Element?

Optimal (sort and slide a window) runs in O(n log n) time and O(1) extra space. Sorting dominates. After it, r and l each move at most n times, so the window pass is O(n).

Which pattern does Frequency of the Most Frequent Element use?

It is a arrays & hashing problem that uses the sliding window · variable pattern. Other problems with the same pattern: Minimum Size Subarray Sum, Count of Subarrays with Product Less Than K, Longest Repeating Character Replacement.

Is there a brute force solution for Frequency of the Most Frequent Element?

Yes. Brute force (grow left from every target) takes O(n^2) time and O(1) space. Increments only go up, so a group made equal ends at its largest value, and the cheapest values to pull up are the ones closest below it.

Which edge cases should I test for Frequency of the Most Frequent Element?

A single element: the answer is 1; All values already equal: the answer is n, with no increments spent; k is large enough to raise everything to the maximum: the answer is n; The gaps are too big for any increment to help: the answer is 1; Duplicates in the input: equal values cost nothing to join; The cost of a window can reach about 10^10, more than an int holds: use a long for sums and products; Values can only go up, so the target of a group is always its largest member.