Highest Frequency Within Increment Budget

Medium · Coding & Algorithms · Software Engineer · Onsite

Problem Statement

Given an integer list nums and a step budget k, you want to make as many entries in nums equal to one another as possible.

In one step, you may pick any index i (0 <= i < len(nums)) and add 1 to nums[i] (subtracting is not allowed). Performing at most k steps in total across the list, return the highest count (frequency) that any single integer value can achieve in nums.

def max_frequency(nums: list[int], k: int) -> int:

Examples

Example 1

Input:  nums = [2, 5, 3, 6], k = 8
Output: 4

Walk-through: Add 4 to 2, 1 to 5, and 3 to 3 (4 + 1 + 3 = 8 <= 8). The list becomes [6, 6, 6, 6], giving value 6 a frequency of 4.

Example 2

Input:  nums = [2, 6, 10, 11, 20], k = 6
Output: 3

Walk-through: Add 5 to 6 and 1 to 10 (5 + 1 = 6 steps) so [6, 10, 11] all become 11, reaching frequency 3. Raising 2 to 11 as well would require 9 additional steps, and raising 11 to 20 alone requires 9 > 6.

Example 3

Input:  nums = [12, 4, 19], k = 5
Output: 1

Walk-through: Even the closest pair (12 up to 19) needs 7 increments, which exceeds k = 5, so every value stays distinct and the highest frequency is 1.

Constraints

  • 1 <= len(nums) <= 10^5
  • 1 <= nums[i] <= 10^5
  • 1 <= k <= 10^9

Step-by-step walkthrough

  1. Restate the problem and rules

    We are given an integer list nums and a budget k. One step picks any index i and adds +1 to nums[i]. Spending at most k steps overall, we want to maximize how many copies of a single number appear in the list and return that count (its frequency).

    Keep three constraints in mind:

    • Values only move upward (+1), never downward (-1).
    • len(nums) reaches 10^5 and k reaches 10^9, so simulating +1 one step at a time or testing every pair of indices (O(n^2)) times out. We need an O(n log n) algorithm.
    • Leaving any single entry untouched uses 0 steps and already forms a group of size 1, so the answer for a non-empty list is always at least 1.
  2. Start with brute force to build intuition

    Suppose we guess the final shared number target. Which entries could become target? Only entries x <= target, since larger entries cannot be lowered, and raising x up to target costs target - x steps. To fit as many entries as possible inside budget k, we greedily pick entries with the smallest gaps target - x first.

    Testing every entry in nums as target, sorting the gaps, and greedily summing them works on tiny inputs, but sorting up to n gaps for each of n targets takes O(n^2 log n) time—roughly 10^10 steps when n = 10^5. Let's find the structure that avoids repeating that work.

  3. Observation 1: sort so optimal groups form contiguous slices

    Two insights unlock the problem:

    1. The final shared value can always be one of the original entries in nums. Suppose a valid group of entries all end up equal to v, and the largest original value among them was M <= v. If v > M, every single member of that group was raised by an extra v - M steps past M. Stopping at M preserves the exact same group size while saving v - M steps per member.
    2. Once nums is sorted ascending, the cheapest partners for sorted_nums[right] sit immediately to its left. Raising x to target costs target - x: the closer x already is to target, the fewer +1 blocks it needs. In ascending order, the largest values <= sorted_nums[right] sit right before index right, forming a contiguous slice sorted_nums[left .. right].

    Picture Example 1 (sorted_nums = [2, 3, 5, 6]) as vertical columns of blocks, where + marks the +1 increments needed to bring every column up to target = 6:

      height 6 |  +   +   +   #
      height 5 |  +   +   #   #      # = original value
      height 4 |  +   +   #   #      + = +1 increment added
      height 3 |  +   #   #   #
      height 2 |  #   #   #   #
      height 1 |  #   #   #   #
               +---------------
                 [2,  3,  5,  6]   ->  4 + 3 + 1 + 0 = 8 increments total
    
  4. Observation 2: compute window cost in O(1) and slide two pointers

    Look at the block diagram above: once every entry in sorted_nums[left .. right] is leveled up to target = sorted_nums[right], those window_len = right - left + 1 columns fill a solid rectangle of area target * window_len. Before leveling, those columns already contained window_sum = sum(sorted_nums[left .. right]) blocks. Thus the number of + blocks we need to add is:

    needed_ops = target * (right - left + 1) - window_sum
    

    Maintaining window_sum in a running integer variable lets us evaluate needed_ops <= k in O(1) time.

    Now we can sweep a sliding window (a pair of left and right indices bounding a contiguous slice [left .. right] that glides rightward across the sorted list):

    • When right steps forward to right + 1, the target ceiling rises (or stays equal on duplicates). Every entry inside [left .. right] now needs at least as many increments as before to reach the higher ceiling.
    • Consequently, any left that already exceeded budget k for right is guaranteed to still exceed k for right + 1. So left never moves backward—it only ever advances right.
  5. Write the sliding-window loop

    For each right from 0 to n - 1:

    1. Set target = sorted_nums[right] and add target to window_sum.
    2. While target * (right - left + 1) - window_sum > k, the leftmost entry sorted_nums[left] is the smallest (most expensive) member in the window: subtract sorted_nums[left] from window_sum and advance left += 1.
    3. Update best_freq with the valid window size right - left + 1.

    Notice two safety details:

    • Use strict > (> k), not >=, because spending all k steps is valid.
    • Whenever left catches up to right, the window has length 1 and target * 1 - target == 0 <= k, so the while loop always terminates with left <= right.
    def max_frequency(nums: list[int], k: int) -> int:
        # Phase 1: Sort ascending so the cheapest values to raise up to any target
        # sit contiguously immediately to that target's left.
        sorted_nums = sorted(nums)
    
        best_freq = 0
        left = 0
        # window_sum: running sum of sorted_nums[left .. right] inclusive
        window_sum = 0
    
        # Phase 2: Sweep `right` across each candidate target value.
        for right in range(len(sorted_nums)):
            target = sorted_nums[right]
            window_sum += target
    
            # Phase 3: Shrink from `left` while leveling [left .. right] up to `target`
            # exceeds our budget `k`. Leveling makes all (right - left + 1) elements equal
            # to `target`, so needed increments = desired rectangle sum - current window_sum.
            # Strict `>` keeps windows that spend *exactly* `k` operations.
            while target * (right - left + 1) - window_sum > k:
                window_sum -= sorted_nums[left]
                left += 1
    
            window_len = right - left + 1
            if window_len > best_freq:
                best_freq = window_len
    
        return best_freq
    

    (Note on integer width: Python integers have arbitrary precision, so target * (right - left + 1) never overflows. In C++ or Java, where 10^5 * 10^5 = 10^10 overflows a 32-bit signed int, store window_sum and the product in 64-bit long long / long.)

  6. Trace Example 1 and Example 2 step by step

    Example 1: nums = [2, 5, 3, 6], k = 8 (sorted_nums = [2, 3, 5, 6])

    right=0 (target=2): [2]          sum=2   needed = 2*1 - 2  = 0 <= 8  -> len=1, best_freq=1
    right=1 (target=3): [2, 3]       sum=5   needed = 3*2 - 5  = 1 <= 8  -> len=2, best_freq=2
    right=2 (target=5): [2, 3, 5]    sum=10  needed = 5*3 - 10 = 5 <= 8  -> len=3, best_freq=3
    right=3 (target=6): [2, 3, 5, 6] sum=16  needed = 6*4 - 16 = 8 <= 8  -> len=4, best_freq=4
    Result: 4
    

    Example 2: nums = [2, 6, 10, 11, 20], k = 6 (sorted_nums = [2, 6, 10, 11, 20])

    right=0 (target=2):  [2]            sum=2   needed = 2*1  - 2  = 0 <= 6               -> best_freq=1
    right=1 (target=6):  [2, 6]         sum=8   needed = 6*2  - 8  = 4 <= 6               -> best_freq=2
    right=2 (target=10): [2, 6, 10]     sum=18  needed = 10*3 - 18 = 12 > 6 -> drop 2 (left=1)
                         [6, 10]        sum=16  needed = 10*2 - 16 = 4 <= 6               -> best_freq=2
    right=3 (target=11): [6, 10, 11]    sum=27  needed = 11*3 - 27 = 6 <= 6               -> best_freq=3
    right=4 (target=20): [6, 10, 11,20] sum=47  needed = 20*4 - 47 = 33 > 6 -> drop 6, 10, 11 (left=4)
                         [20]           sum=20  needed = 20*1 - 20 = 0 <= 6               -> best_freq=3
    Result: 3
    
  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def max_frequency(nums: list[int], k: int) -> int:
        # Phase 1: Sort ascending so the cheapest values to raise up to any target
        # sit contiguously immediately to that target's left.
        sorted_nums = sorted(nums)
    
        best_freq = 0
        left = 0
        # window_sum: running sum of sorted_nums[left .. right] inclusive
        window_sum = 0
    
        # Phase 2: Sweep `right` across each candidate target value.
        for right in range(len(sorted_nums)):
            target = sorted_nums[right]
            window_sum += target
    
            # Phase 3: Shrink from `left` while leveling [left .. right] up to `target`
            # exceeds our budget `k`. Leveling makes all (right - left + 1) elements equal
            # to `target`, so needed increments = desired rectangle sum - current window_sum.
            # Strict `>` keeps windows that spend *exactly* `k` operations.
            while target * (right - left + 1) - window_sum > k:
                window_sum -= sorted_nums[left]
                left += 1
    
            window_len = right - left + 1
            if window_len > best_freq:
                best_freq = window_len
    
        return best_freq
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine lining up wooden fence posts from shortest to tallest and carrying a bucket of k one-inch blocks that you can stack on top of shorter posts (you can never saw a post down) so as many posts as possible stand at the exact same height. Whenever you test an existing post target as your goal height, the cheapest posts to raise up to target are the ones standing immediately to its left, because they are already closest in height to target and consume the fewest blocks. That turns the search into a sliding window—a pair of left and right indices bounding a contiguous slice sorted_nums[left .. right] across the sorted list: right steps forward to try each post as target, we measure missing blocks via target * window_len - window_sum, and whenever that deficit exceeds k, left steps forward to drop the shortest, costliest post.

Why does a naive approach fall short? Testing each entry as a target and scanning or sorting smaller entries around it takes O(n^2) or O(n^2 log n) steps, hitting roughly 10^10 operations when n = 10^5. Simulating +1 additions one unit at a time is even slower because k can reach 10^9.

Let's trace Example 2 (nums = [2, 6, 10, 11, 20], k = 6):

right=0 (target=2):  window=[2]             sum=2   cost = 2*1  - 2  = 0 <= 6  -> size 1
right=1 (target=6):  window=[2, 6]          sum=8   cost = 6*2  - 8  = 4 <= 6  -> size 2
right=2 (target=10): window=[2, 6, 10]      sum=18  cost = 10*3 - 18 = 12 > 6  -> drop 2
                     window=[6, 10]         sum=16  cost = 10*2 - 16 = 4 <= 6  -> size 2
right=3 (target=11): window=[6, 10, 11]     sum=27  cost = 11*3 - 27 = 6 <= 6  -> size 3
right=4 (target=20): window=[6, 10, 11, 20] sum=47  cost = 20*4 - 47 = 33 > 6  -> drop 6, 10, 11
                     window=[20]            sum=20  cost = 20*1 - 20 = 0 <= 6  -> size 1
Maximum window size = 3

Notice that left never had to move backward when right stepped from 10 to 11 or 20: raising the target ceiling only makes earlier entries more expensive, never cheaper.

Complexity

  • Time: O(n log n), where n = len(nums). Sorting nums takes O(n log n) comparisons, and the sliding-window sweep takes O(n) total work because right advances n times and left advances at most n times across the entire run (every element enters the window once and leaves at most once).
  • Space: O(n). sorted(nums) allocates a sorted copy of n integers without mutating the caller's list, while the pointers and window_sum use O(1) scalar variables.

Edge cases

  • Single-element list (len(nums) == 1): target * 1 - target == 0 <= k, so the loop finishes with best_freq = 1 for every k.
  • All elements already equal (e.g., [3, 3, 3, 3]): Every window has needed_ops == 0, left remains 0, and best_freq reaches n.
  • Budget smaller than every gap (Example 3, [12, 4, 19], k = 5): Every multi-element window exceeds k and shrinks back to left == right, returning 1.
  • Budget equals the exact deficit (needed_ops == k): Valid under "at most k steps"; checking > k (rather than >= k) preserves windows like Example 1 (8 == k) and Example 2 (6 == k).
  • Optimal target is an interior value (Example 2, [2, 6, 10, 11, 20], k = 6): Checking every right records [6, 10, 11] at right = 3 (best_freq = 3) before right = 4 (target = 20) shrinks to size 1.
  • 64-bit intermediate products: target * window_len can reach 10^5 * 10^5 = 10^10; Python int scales automatically, whereas C++/Java require long long / long.

Common mistakes

  • Forgetting to sort nums first: On an unsorted list, entries before right are arbitrary—some possibly larger than nums[right]—making target * window_len - window_sum invalid.
  • Assuming decrements are allowed: In [1, 10, 10, 10, 11] with k = 1, 11 cannot be lowered to 10, so the answer is 3, not 4.
  • Writing >= k instead of > k in the while loop: Wrongly discards valid windows that spend all k steps (such as Example 1 where 8 == k).
  • Recomputing sum(sorted_nums[left:right + 1]) each step: Slicing and summing inside the loop degrades the O(n) sweep to O(n^2).
  • Resetting left = 0 for each right: Because the target only grows with right, any entry already too far below an earlier target is even further below a higher target.

Alternative approaches

  • Prefix sums + binary search (O(n log n) time, O(n) space): Build a prefix-sum array (an array prefix where prefix[i] stores the sum of the first i sorted numbers so any slice sum equals prefix[right + 1] - prefix[left] in O(1) time), and for each right binary search for the smallest left with leveling deficit <= k. Total complexity stays O(n log n), though the post-sort sweep spends O(n log n) instead of O(n).
  • Counting sort + value-bucket sweep (O(n + M) time, O(M) space where M = max(nums) <= 10^5): Counting frequencies in an array avoids comparison sorting, though handling partially consumed buckets at the left boundary adds extra bookkeeping unnecessary at n <= 10^5.

Follow-up questions

  • What changes if each step may either add 1 or subtract 1, allowing elements to meet at any integer? When both +1 and -1 are permitted, bringing a group to t costs sum(|x - t|), which is minimized when t is the median (the middle value in sorted order) of that group—meaning an existing entry of nums is still an optimal meeting point! In sorted order, the cheapest group around its median is still a contiguous slice sorted_nums[left .. right], and widening the slice never lowers its median cost. With a prefix-sum array to evaluate the distance of both halves of [left .. right] to sorted_nums[(left + right) // 2] in O(1), the same two-pointer sweep runs in O(n log n) time.
  • How could you replace the two-pointer sweep with binary search, and how does that affect time and space complexity? You can either binary search on the achievable frequency f in [1, n] (checking in O(n) with a fixed-width window of length f whether any f consecutive sorted entries cost <= k), or binary search the leftmost valid left per right backed by a prefix-sum array. Overall asymptotic runtime remains O(n log n) since sorting already takes O(n log n), but the post-sort pass slows from O(n) to O(n log n) (and per-right binary search allocates an extra O(n) prefix-sum array instead of one O(1) running sum).
  • How would your algorithm change if incrementing nums[i] by 1 cost a position-specific weight weights[i] instead of 1? For weights[i] >= 0, the best target is still an existing value in nums (lowering a higher target saves weights[i] per step on every chosen member), and raising entry i to target costs weights[i] * (target - nums[i]). However, varying slopes weights[i] break the contiguous sorted-slice property because a smaller nums[i] with tiny weights[i] can be cheaper than a closer nums[j] with huge weights[j]; testing each candidate target by sorting smaller items' weighted costs takes O(n^2 log n) time. In the special case where weights[i] is non-increasing with nums[i], closer values are both nearer and cheaper per unit, restoring the O(n log n) sliding window with deficit target * window_weight_sum - window_weighted_val_sum.

Follow-up questions

Similar questions

More Goldman Sachs interview questions

All 35 Goldman Sachs questions →