Frequency of the Most Frequent Element
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^51 <= nums[i] <= 10^51 <= 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.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
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.
| Approach | Time | Space |
|---|---|---|
| Brute force (grow left from every target) | O(n^2) | O(1) |
| Prefix sums and binary search | O(n log n) | O(n) |
| Optimal (sort and slide a window) | O(n log n) | O(1) |
1Brute force (grow left from every target)
O(n^2)Sorting is O(n log n), but each of the n targets can walk back over up to n values.O(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.
- Sort nums.
- For each index i, start with cost = 0 and j = i.
- While j > 0 and cost + (nums[i] - nums[j - 1]) <= k, add that amount to cost and move j left.
- 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;
}
}class Solution:
def maxFrequency(self, nums: List[int], k: int) -> int:
nums.sort()
best = 0
for i in range(len(nums)):
cost = 0
j = i
while j > 0 and cost + (nums[i] - nums[j - 1]) <= k:
cost += nums[i] - nums[j - 1]
j -= 1
best = max(best, i - j + 1)
return bestclass Solution {
public:
int maxFrequency(vector<int>& nums, int k) {
sort(nums.begin(), nums.end());
int best = 0;
for (int i = 0; i < (int) nums.size(); i++) {
long long cost = 0;
int j = i;
while (j > 0 && cost + (nums[i] - nums[j - 1]) <= k) {
cost += nums[i] - nums[j - 1];
j--;
}
best = max(best, i - j + 1);
}
return best;
}
};function maxFrequency(nums, k) {
nums.sort((a, b) => a - b);
let best = 0;
for (let i = 0; i < nums.length; i++) {
let cost = 0;
let 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;
}2Prefix sums and binary search
O(n log n)Sorting plus one binary search of O(log n) steps for each of the n targets.O(n)The prefix-sum array has n + 1 entries.With prefix sums, the cost of raising a whole window nums[j..i] to nums[i] is a single formula: nums[i] * (i - j + 1) minus the window's sum. For a fixed target i, that cost only grows as j moves left, so the smallest j that still fits in k can be found by binary search instead of a walk.
- Sort nums and build pre, where pre[i + 1] = pre[i] + nums[i].
- For each i, binary search j in [0, i]: cost(j) = nums[i] * (i - j + 1) - (pre[i + 1] - pre[j]).
- If cost(j) <= k, a longer window may still fit, so search left; otherwise search right.
- Keep the largest i - j + 1.
class Solution {
public int maxFrequency(int[] nums, int k) {
Arrays.sort(nums);
int n = nums.length;
long[] pre = new long[n + 1];
for (int i = 0; i < n; i++) pre[i + 1] = pre[i] + nums[i];
int best = 0;
for (int i = 0; i < n; i++) {
int lo = 0, hi = i;
while (lo < hi) {
int mid = (lo + hi) / 2;
long cost = (long) nums[i] * (i - mid + 1) - (pre[i + 1] - pre[mid]);
if (cost <= k) hi = mid;
else lo = mid + 1;
}
best = Math.max(best, i - lo + 1);
}
return best;
}
}class Solution:
def maxFrequency(self, nums: List[int], k: int) -> int:
nums.sort()
n = len(nums)
pre = [0] * (n + 1)
for i in range(n):
pre[i + 1] = pre[i] + nums[i]
best = 0
for i in range(n):
lo, hi = 0, i
while lo < hi:
mid = (lo + hi) // 2
cost = nums[i] * (i - mid + 1) - (pre[i + 1] - pre[mid])
if cost <= k:
hi = mid
else:
lo = mid + 1
best = max(best, i - lo + 1)
return bestclass Solution {
public:
int maxFrequency(vector<int>& nums, int k) {
sort(nums.begin(), nums.end());
int n = nums.size();
vector<long long> pre(n + 1, 0);
for (int i = 0; i < n; i++) pre[i + 1] = pre[i] + nums[i];
int best = 0;
for (int i = 0; i < n; i++) {
int lo = 0, hi = i;
while (lo < hi) {
int mid = (lo + hi) / 2;
long long cost = (long long) nums[i] * (i - mid + 1) - (pre[i + 1] - pre[mid]);
if (cost <= k) hi = mid;
else lo = mid + 1;
}
best = max(best, i - lo + 1);
}
return best;
}
};function maxFrequency(nums, k) {
nums.sort((a, b) => a - b);
const n = nums.length;
const pre = new Array(n + 1).fill(0);
for (let i = 0; i < n; i++) pre[i + 1] = pre[i] + nums[i];
let best = 0;
for (let i = 0; i < n; i++) {
let lo = 0, hi = i;
while (lo < hi) {
const mid = (lo + hi) >> 1;
const cost = nums[i] * (i - mid + 1) - (pre[i + 1] - pre[mid]);
if (cost <= k) hi = mid;
else lo = mid + 1;
}
best = Math.max(best, i - lo + 1);
}
return best;
}3Optimal (sort and slide a window)
O(n log n)Sorting dominates. After it, r and l each move at most n times, so the window pass is O(n).O(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.
- Sort nums. Set l = 0, sum = 0, best = 0.
- For each r: add nums[r] to sum.
- While nums[r] * (r - l + 1) - sum > k: subtract nums[l] from sum and move l right.
- 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;
}
}class Solution:
def maxFrequency(self, nums: List[int], k: int) -> int:
nums.sort()
total = 0
l = best = 0
for r in range(len(nums)):
total += nums[r]
while nums[r] * (r - l + 1) - total > k:
total -= nums[l]
l += 1
best = max(best, r - l + 1)
return bestclass Solution {
public:
int maxFrequency(vector<int>& nums, int k) {
sort(nums.begin(), nums.end());
long long sum = 0;
int l = 0, best = 0;
for (int r = 0; r < (int) nums.size(); r++) {
sum += nums[r];
while ((long long) nums[r] * (r - l + 1) - sum > k) {
sum -= nums[l];
l++;
}
best = max(best, r - l + 1);
}
return best;
}
};function maxFrequency(nums, k) {
nums.sort((a, b) => a - b);
let sum = 0;
let l = 0, best = 0;
for (let r = 0; r < nums.length; r++) {
sum += nums[r];
while (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.