Taro Logo

Frequency of the Most Frequent Element

#122 Most AskedMedium
0 views
Topics:
ArraysSliding WindowsGreedy Algorithms

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.

Example 1:

Input: nums = [1,2,4], k = 5
Output: 3
Explanation: Increment the first element three times and the second element two times to make nums = [4,4,4].
4 has a frequency of 3.

Example 2:

Input: nums = [1,4,8,13], k = 5
Output: 2
Explanation: There are multiple optimal solutions:
- Increment the first element three times to make nums = [4,4,8,13]. 4 has a frequency of 2.
- Increment the second element four times to make nums = [1,8,8,13]. 8 has a frequency of 2.
- Increment the third element five times to make nums = [1,4,13,13]. 13 has a frequency of 2.

Example 3:

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

Constraints:

  • 1 <= nums.length <= 105
  • 1 <= nums[i] <= 105
  • 1 <= k <= 105

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. Can the input array contain negative integers, or are we guaranteed that all numbers are non-negative?
  2. Can the operations be applied to multiple different elements as long as the total number of increments across all elements does not exceed $k$?
  3. What is the expected behavior if the input array is empty?
  4. Are there any constraints on the size of the array `nums` or the magnitude of the integer $k$?
  5. If multiple elements can achieve the same maximum frequency, does it matter which specific element's frequency we return?

Brute Force Solution

Approach

Imagine you have a collection of items of various sizes and you want to make as many of them equal as possible by boosting their values within a limited budget of total increases. The brute force approach systematically tries every single item in the collection as the target value and tests how many other items can be raised to match it using your available budget.

Here's how the algorithm would work step-by-step:

  1. Pick a starting item from your collection to act as your target goal.
  2. Look at every other item in the collection and calculate how much of your budget would be needed to boost that item until it matches your chosen target.
  3. Try adding up these required boosts, starting with the items closest in value to your target, and see how many you can successfully boost before running out of budget.
  4. Count how many items end up matching your chosen target.
  5. Write down this total count for the target you just tested.
  6. Repeat this entire process by picking a different item to be the target goal.
  7. Compare the counts from all the different targets you tested and pick the highest one as your final answer.

Code Implementation

def max_frequency(numbers_list, budget_limit):
    # Sort numbers to easily check elements smaller than the target in ascending order
    sorted_numbers = sorted(numbers_list)
    
    maximum_frequency = 0
    
    # Iterate through every item to test it as the potential target value
    for target_index in range(len(sorted_numbers)):
        target_value = sorted_numbers[target_index]
        current_budget = budget_limit
        current_frequency = 0
        
        # Scan backward from the target to find how many smaller elements we can boost
        for scan_index in range(target_index, -1, -1):
            cost_to_increase = target_value - sorted_numbers[scan_index]
            
            if current_budget >= cost_to_increase:
                current_budget -= cost_to_increase
                current_frequency += 1
            else:
                break
        
        # Keep track of the highest count achieved across all tested target values
        if current_frequency > maximum_frequency:
            maximum_frequency = current_frequency
            
    return maximum_frequency

Big(O) Analysis

Time Complexity
O(n²) – For each of the n items chosen as the target goal in the outer process, the algorithm iterates through every other item in the collection to calculate the required budget. For the first target we check (n-1) items, for the second (n-2) items, and so on. This nested examination leads to approximately n * n/2 total operations, which simplifies to O(n²).
Space Complexity
O(1) – The brute-force process described relies entirely on a few scalar variables, such as a counter for the items matching the target goal and an accumulator for the budget used, without allocating any auxiliary data structures. Since no extra collections, hash maps, or recursive stacks scale with the input size N, the auxiliary memory remains constant. Therefore, the extra memory used beyond the input itself simplifies to O(1) space complexity.

Optimal Solution

Approach

To find out how many times we can make the most frequent item appear by boosting smaller items, the best strategy is to sort everything from smallest to largest and examine groups of items side-by-side. By using a flexible window that expands when we have enough resources to boost everyone up to the highest value in the group, and shrinks from the back when costs get too high, we can efficiently track the largest possible group.

Here's how the algorithm would work step-by-step:

  1. Arrange all the items in order from smallest to largest so that similar values are sitting right next to each other.
  2. Imagine a flexible frame that looks at a continuous stretch of these sorted items, starting with just a single item.
  3. Look at the item at the very front of your frame, because this will be your target goal for every other item currently inside the frame.
  4. Calculate how much total effort or cost it would take to boost all the other items in your frame so they match that front target item.
  5. If your total available budget is enough to cover this cost, keep the frame growing larger by including the next item in line.
  6. If the total cost exceeds your budget, slide the back edge of your frame forward to drop the smallest item and reduce the cost.
  7. Keep track of the maximum number of items you were ever able to comfortably fit inside your frame at the same time without breaking the budget.

Code Implementation

def max_frequency(nums, k):
    nums.sort()
    
    left_pointer = 0
    current_sum = 0
    max_freq = 0

    # Sorting allows us to evaluate contiguous elements that can be efficiently incremented.
    for right_pointer in range(len(nums)):
        current_sum += nums[right_pointer]

        # If increments exceed budget, shrink window from left to maintain valid operations.
        while (right_pointer - left_pointer + 1) * nums[right_pointer] - current_sum > k:
            current_sum -= nums[left_pointer]
            left_pointer += 1

        # Track the largest valid window size found during our linear scan.
        max_freq = max(max_freq, right_pointer - left_pointer + 1)

    return max_freq

Big(O) Analysis

Time Complexity
O(n log n) – Sorting the array of n elements initially takes O(n log n) time to arrange the items from smallest to largest. The sliding window uses a left and right pointer where the right pointer iterates through all n elements once, and the left pointer only moves forward without ever resetting. Across the entire execution, the operations scale linearly with n, resulting in n plus n steps for the window traversal. Combining the initial sorting step and the linear window scan, the total operations approximate n log n plus 2n, which simplifies to O(n log n).
Space Complexity
O(sorting space) – The auxiliary space complexity is determined by the memory required to sort the input array of size N. Depending on the sorting algorithm used by the language runtime, this typically requires O(log N) or O(N) extra space for the sorting stack or temporary arrays. Beyond the sorting operation, the algorithm only uses a few primitive variables like pointers and a budget tracker, which consume constant O(1) auxiliary space. Therefore, the total extra memory needed beyond the input itself is dominated by the sorting process, simplifying to O(N) or O(log N) auxiliary space.

Edge Cases

Array with a single element
How to Handle:
The sliding window correctly evaluates a window size of one and returns a frequency of one.
k is equal to zero
How to Handle:
With no increments allowed, the window size collapses and returns the count of the most frequent duplicate element.
Array with all identical elements
How to Handle:
Sorting has no effect and the sliding window expands to cover the entire array length.
k is large enough to make all elements equal to the maximum element
How to Handle:
The window expands to encompass the entire sorted array because the cost condition is always satisfied.
Negative numbers and zeros in the array
How to Handle:
Sorting correctly orders negative numbers, zeros, and positives, ensuring the distance math holds true.
Large inputs with maximum constraints causing integer overflow during window cost calculations
How to Handle:
Using 64-bit integers for the sum and window calculations prevents arithmetic overflow during multiplication.
Maximum sized inputs where O(n squared) naive approaches would Time Out
How to Handle:
The O(n log n) sorting plus O(n) sliding window approach ensures efficient scaling for large datasets.
0/257 completed