Frequency of the Most Frequent Element - Problem

The frequency of an element is the number of times it occurs in an array.

You are given an integer array nums and an integer k. In one operation, you can choose an index of nums and increment the element at that index by 1.

Return the maximum possible frequency of an element after performing at most k operations.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,4], k = 5
Output: 3
💡 Note: We can make all elements equal to 4 by incrementing 1 by 3 and 2 by 2, using 5 operations total. Final array: [4,4,4] with frequency 3.
Example 2 — Limited Operations
$ Input: nums = [1,4,8,13], k = 5
Output: 2
💡 Note: We can make [1,4] both equal to 4 using 3 operations (1→4 needs 3 ops). Or make [4,8] both equal to 8 using 4 operations. Maximum frequency is 2.
Example 3 — Single Element
$ Input: nums = [3], k = 0
Output: 1
💡 Note: With only one element and no operations allowed, the maximum frequency is 1.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 105
  • 1 ≤ k ≤ 109

Visualization

Tap to expand
Frequency of the Most Frequent Element INPUT Array nums: 1 idx 0 2 idx 1 4 idx 2 k = 5 Max operations: 5 Each op: increment any element by 1 Goal: Find max frequency of any element possible ALGORITHM STEPS 1 Sort Array [1, 2, 4] (already sorted) 2 Sliding Window Use two pointers: left, right 3 Calculate Cost Cost to make all = nums[r] 4 Shrink if Needed If cost > k, move left Window Analysis 1 2 4 Cost: (4-1)+(4-2) = 3+2 = 5 5 <= k, window valid! FINAL RESULT Make all elements equal to 4: Before: 1 2 4 +3 +2 +0 After: 4 4 4 Total ops: 3 + 2 + 0 = 5 5 <= k (valid) Output: 3 Max frequency = 3 (OK) Key Insight: Sort the array first. Then use sliding window: for each right pointer, the cost to make all elements in window equal to nums[right] is (window_size * nums[right]) - window_sum. Shrink window if cost > k. Time: O(n log n), Space: O(1). The answer is the maximum window size found during iteration. TutorialsPoint - Frequency of the Most Frequent Element | Optimal Solution (Sliding Window)
Asked in
Amazon 45 Google 38 Microsoft 32 Apple 25
89.0K Views
High Frequency
~25 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen