#1838

Frequency of the Most Frequent Element

Medium
ArrayBinary SearchGreedySliding WindowSortingPrefix SumSliding WindowSorting
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(1)
💡

Intuition

Time O(n log n)Space O(1)

The optimal approach uses a sliding window technique after sorting the array. By maintaining a window of elements that can be incremented to the same value, we can efficiently calculate the maximum frequency.

⚙️

Algorithm

4 steps
  1. 1Step 1: Sort the array.
  2. 2Step 2: Use two pointers to maintain a window of elements that can be made equal to the largest element in the window.
  3. 3Step 3: Calculate the total increments needed to make all elements in the window equal to the rightmost element and check if it exceeds k.
  4. 4Step 4: If it does, move the left pointer to reduce the window size. If not, update the maximum frequency.
solution.py15 lines
1# Full working Python code
2from collections import deque
3
4def maxFrequency(nums, k):
5    nums.sort()
6    left = 0
7    total = 0
8    max_freq = 0
9    for right in range(len(nums)):
10        total += nums[right]
11        while nums[right] * (right - left + 1) - total > k:
12            total -= nums[left]
13            left += 1
14        max_freq = max(max_freq, right - left + 1)
15    return max_freq

Complexity note: The sorting step takes O(n log n), and the sliding window approach runs in O(n), making the overall complexity dominated by the sorting step.

  • 1Sorting the array helps in efficiently managing the increments needed to equalize elements.
  • 2Using a sliding window allows us to dynamically adjust our range of elements without recalculating from scratch.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.