15% off all plans & roadmaps Use code

See plans

Frequency of the Most Frequent Element

Updated

TL;DR: Sort the array, then slide a window whose right end is the target value. Shrink from the left while raising every value in the window to the target costs more than k.

Problem

You get an integer array nums and an integer k. The frequency of a value is how many times it appears in the array. In one operation you choose an index and add 1 to that element.

Return the highest frequency any single value can reach after at most k operations.

Example 1

Input: nums = [1,2,4], k = 5
Output: 3
Explanation: Raise the first element by 3 and the second by 2. Now nums is [4,4,4], so 4 appears 3 times.

Example 2

Input: nums = [1,4,8,13], k = 5
Output: 2
Explanation:
Several choices are optimal.
- Raise the first element by 3 to get [4,4,8,13]. The value 4 appears 2 times.
- Raise the second element by 4 to get [1,8,8,13]. The value 8 appears 2 times.
- Raise the third element by 5 to get [1,4,13,13]. The value 13 appears 2 times.

Example 3

Input: nums = [3,9,6], k = 2
Output: 1

Constraints

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

Constraints that matter

  • n up to 10^5 rules out checking every subarray with a fresh sum, which is O(n^3). Even O(n^2) means about 5 * 10^9 pairs, which is too slow.
  • Values and window sums can reach about 10^10, so the cost check must use 64-bit integers.
  • Only increments are allowed, so the target of a group must be its largest value. After sorting, that value sits at the right end of the window.

View on LeetCode

Hints

Hint 1

Operations only increase values, so any group you make equal must end at its largest member.

Hint 2

A beginner sorts the array, then tries every contiguous block nums[i..j] as the group to raise.

Solution

Intuition

Operations only increase values, so any group you make equal must end at its largest member. Call that member the target t. Every other member has to climb up to t, so the cost is t times the group size, minus the group's sum.

Picture a row of cups sorted by height, where you must pour water so every cup in a chosen group matches the tallest one. The right end is the tallest cup in the window, and the left end drops the shortest cups when the water needed exceeds k.

Sorting turns this into a contiguous problem. For a target at index j, the cheapest group of size m is the m values directly below it, which are nums[j-m+1..j]. Swapping in a value that sits farther below the target only adds cost, so no other group of that size beats the contiguous one.

This is the variable-size sliding window pattern with a cost condition. Move the right end to add a value, and move the left end while the cost is above k. Moving the right end onto a larger value raises the cost of every window that ends there, so the left end never has to move back. You do not need a deque, because the target is always the right end, which is the largest value in the window after sorting.

Watch the pattern animation

Worked example

Input: nums = [1, 2, 2, 3, 4, 6, 7], k = 7
Output: 4
Explanation: Raise the two 2s by 2 each and the 3 by 1, so the group 2, 2, 3, 4 becomes four 4s. That costs 2 + 2 + 1 + 0 = 5, which is within k = 7. The cheapest group of five values costs 8, which is over budget, so 4 is the answer.

Approach 1: Brute force over every subarray

A beginner sorts the array, then tries every contiguous block nums[i..j] as the group to raise. The target is nums[j], the largest value in the block. The cost is the target times the block length, minus the block's sum.

What's slow: the code adds up the block from scratch on every try. Each pair (i, j) costs a loop over the block, so the scan does far more work than the answer needs. The logic is still correct, which makes this a fair baseline to improve on.

Steps

  1. Sort nums in ascending order.
  2. Set best to 1, because any single element works with zero operations.
  3. For each start index i, consider each end index j from i to the last index.
  4. Add up nums[i] through nums[j] with a loop.
  5. Compute cost = nums[j] * (j - i + 1) - sum.
  6. If cost <= k, update best with the block length j - i + 1.
  7. Return best.

Dry run

Use the example nums = [1, 2, 2, 3, 4, 6, 7], k = 7, which is already sorted. Start at index 1 (value 2).

  • Block [2]: cost 0.
  • Block [2, 2]: sum 4, cost 2 * 2 - 4 = 0.
  • Block [2, 2, 3]: sum 7, cost 3 * 3 - 7 = 2.
  • Block [2, 2, 3, 4]: sum 11, cost 4 * 4 - 11 = 5. That is within 7, so best becomes 4.
  • Block [2, 2, 3, 4, 6]: sum 17, cost 6 * 5 - 17 = 13. Too costly.
  • Block [2, 2, 3, 4, 6, 7]: sum 24, cost 7 * 6 - 24 = 18. Too costly.

No other start produces a valid block longer than 4, so the output is 4.

Complexity

TimeO(n^3)
SpaceO(1) extra beyond the sort

Let n be the length of nums. There are about n^2 / 2 pairs (i, j). For each pair the sum loop runs up to n times, so the total is on the order of n^3 / 6 additions, which is O(n^3). The sort costs O(n log n), which is smaller, and the code stores only a few scalar variables, so the extra space is O(1).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def maxFrequency(self, nums: List[int], k: int) -> int:
        nums.sort()
        n = len(nums)
        best = 1
        for i in range(n):
            for j in range(i, n):
                # Re-add the block from scratch on every try
                total = sum(nums[i:j + 1])
                cost = nums[j] * (j - i + 1) - total
                if cost <= k:
                    best = max(best, j - i + 1)
        return best

Approach 2: Running sum per start

What's slow: the brute force re-adds the block on every try, so each pair costs O(n). Fixing the start i makes the block grow by one value each time j moves right.

The insight that fixes it: keep a running sum for a fixed start and add one value per step. Each cost check then takes O(1), so the pair scan drops from cubic to quadratic.

Steps

  1. Sort nums in ascending order.
  2. Set best to 1.
  3. For each start index i, set total to 0.
  4. For each end index j from i onward, add nums[j] to total.
  5. Compute cost = nums[j] * (j - i + 1) - total.
  6. If cost <= k, update best with j - i + 1.
  7. Return best.

Dry run

Use the example nums = [1, 2, 2, 3, 4, 6, 7], k = 7. Start at index 0 (value 1) and extend j.

  • j = 0: total 1, cost 1 * 1 - 1 = 0.
  • j = 1: total 3, cost 2 * 2 - 3 = 1.
  • j = 2: total 5, cost 2 * 3 - 5 = 1.
  • j = 3: total 8, cost 3 * 4 - 8 = 4. Valid, so best becomes 4.
  • j = 4: total 12, cost 4 * 5 - 12 = 8. Too costly.
  • j = 5: total 18, cost 6 * 6 - 18 = 18. Too costly.
  • j = 6: total 25, cost 7 * 7 - 25 = 24. Too costly.

The other starts never exceed 4 either, so the output is 4.

Complexity

TimeO(n^2)
SpaceO(1) extra beyond the sort

Let n be the length of nums. The pairs (i, j) with i <= j number about n^2 / 2, and each pair does a fixed amount of work: one addition, one multiplication, one subtraction and one comparison. The total work is O(n^2), which is larger than the O(n log n) sort. Only a few scalar variables are stored, so the extra space is O(1).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def maxFrequency(self, nums: List[int], k: int) -> int:
        nums.sort()
        n = len(nums)
        best = 1
        for i in range(n):
            total = 0
            for j in range(i, n):
                # Grow the block by one value instead of re-summing it
                total += nums[j]
                cost = nums[j] * (j - i + 1) - total
                if cost <= k:
                    best = max(best, j - i + 1)
        return best

The Variable Size (Condition-Based) infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

Variable Size (Condition-Based)

Part of Sliding Window

Approach 3: Sort, then sliding window with a running totalOptimalVariable Size (Condition-Based)

What's slow: the running-sum version still tries every start for every end, so about n^2 / 2 pairs get checked even when most of them cannot win.

The insight that fixes it: for a fixed right end, moving the left end right only lowers the cost. Also, moving the right end onto a value at least as large never lowers the cost of a window. So a left end that is too costly for one right end stays too costly for later ones, and the left end only moves forward. One pointer pair covers all the windows.

Steps

  1. Sort nums in ascending order.
  2. Set left to 0, total to 0 and best to 0.
  3. Move right from 0 to the last index, adding nums[right] to total.
  4. While nums[right] * (right - left + 1) - total > k, subtract nums[left] from total and increment left.
  5. Update best with right - left + 1.
  6. Return best.

Dry run

Use the example nums = [1, 2, 2, 3, 4, 6, 7], k = 7. Each row is one value of right. The drops column lists the values removed from the left during that step.

rightvaluedropslefttotallengthcostbest
01none01101
12none03212
22none05313
33none08444
44drop 1111454
56drop 2 and 2313354
67drop 3417344

At right = 4 the window [1, 2, 2, 3, 4] costs 8, so the code drops the 1. At right = 5 one drop is not enough, so the while removes two values. The final best is 4, which matches the expected output.

Complexity

TimeO(n log n)
SpaceO(1) extra beyond the sort

Let n be the length of nums. Sorting takes O(n log n). In the window loop, right moves n times and left only moves forward, so it moves at most n times in total, and each move does constant work. The loop is therefore O(n), and the total is O(n log n) + O(n), which is O(n log n).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def maxFrequency(self, nums: List[int], k: int) -> int:
        nums.sort()
        left = 0
        total = 0
        best = 0
        for right in range(len(nums)):
            total += nums[right]
            # Shrink until raising the window to nums[right] costs at most k
            while nums[right] * (right - left + 1) - total > k:
                total -= nums[left]
                left += 1
            best = max(best, right - left + 1)
        return best

Common mistakes

  • Using if cost > k instead of while cost > k when shrinking. One new value can require several drops, as at right = 5 in the dry run, where two values leave the window.
  • Moving left without subtracting the outgoing value first. Fix it by running total -= nums[left] before left++, so the sum always matches the window.
  • Computing nums[right] * (right - left + 1) in a 32-bit int in Java, C++ or C#. The product can reach about 10^10. Cast to long before multiplying.
  • Computing the cost with nums[left] as the target. The target is always nums[right], which is the largest value in the window after sorting.
  • Updating best before the shrink loop. The window is invalid at that point, so the length can be too large. Update best after the while loop.
  • Running the window on unsorted input. The argument that the left pointer only moves forward depends on sorted order, so sort first.

Edge cases

  • Single element, nums = [5], k = 1: the answer is 1, because the cost of a single value is 0.
  • All values equal, nums = [3, 3, 3], k = 0: the answer is 3, because every window costs 0.
  • Distinct values with k = 0, nums = [1, 2, 4]: the answer is 1, because no two values can match without spending budget.
  • Wide gap, nums = [1, 100000]: with k = 99999 the answer is 2, and with k = 98999 the answer is 1.
  • Maximum size with equal values, n = 10^5 all equal to 1 and k = 1: the answer is 10^5, and the sums stay within 64-bit range.
  • Duplicates in the middle, nums = [2, 2, 2, 5], k = 0: the answer is 3, because the three 2s already match.

Follow-ups interviewers ask

Follow-ups are part of Pro

The questions interviewers ask after you solve Frequency of the Most Frequent Element, with how to answer them.

Unlock the follow-ups

Frequency of the Most Frequent Element FAQ

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

The total time is O(n log n). The sort takes O(n log n), and the sliding window pass after it takes O(n) because each index enters and leaves the window at most once.

Why use a sliding window for Frequency of the Most Frequent Element?

After sorting, the cost of a window only goes up when its right end moves onto a larger value. One left pointer can serve every right end, so a single pass finds the longest valid window.

Can Frequency of the Most Frequent Element be solved in O(1) extra space?

The window itself uses O(1) extra space, but sorting does not. Python's sort can use O(n) temporary memory, and Java's primitive sort uses about O(log n) stack space. Heapsort sorts in place with O(1) extra space, but it is slower in practice.

Does this problem need a monotonic deque?

No. The target is always the right end of the window, and after sorting that value is the largest in the window. The right end already gives the maximum, so no queue of candidates is needed.

Does the Python solution change the input list?

Yes. The call nums.sort() sorts the caller's list in place. If the caller needs the original order, copy the list first with sorted(nums), which costs O(n) extra memory.

Asked at

See which companies ask this — Pro

Practise it