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^51 <= nums[i] <= 10^51 <= k <= 10^9
Step-by-step walkthrough
Restate the problem and rules
We are given an integer list
numsand a budgetk. One step picks any indexiand adds+1tonums[i]. Spending at mostksteps 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)reaches10^5andkreaches10^9, so simulating+1one step at a time or testing every pair of indices (O(n^2)) times out. We need anO(n log n)algorithm.- Leaving any single entry untouched uses
0steps and already forms a group of size1, so the answer for a non-empty list is always at least1.
- Values only move upward (
Start with brute force to build intuition
Suppose we guess the final shared number
target. Which entries could becometarget? Only entriesx <= target, since larger entries cannot be lowered, and raisingxup totargetcoststarget - xsteps. To fit as many entries as possible inside budgetk, we greedily pick entries with the smallest gapstarget - xfirst.Testing every entry in
numsastarget, sorting the gaps, and greedily summing them works on tiny inputs, but sorting up tongaps for each ofntargets takesO(n^2 log n)time—roughly10^10steps whenn = 10^5. Let's find the structure that avoids repeating that work.Observation 1: sort so optimal groups form contiguous slices
Two insights unlock the problem:
- The final shared value can always be one of the original entries in
nums. Suppose a valid group of entries all end up equal tov, and the largest original value among them wasM <= v. Ifv > M, every single member of that group was raised by an extrav - Msteps pastM. Stopping atMpreserves the exact same group size while savingv - Msteps per member. - Once
numsis sorted ascending, the cheapest partners forsorted_nums[right]sit immediately to its left. Raisingxtotargetcoststarget - x: the closerxalready is totarget, the fewer+1blocks it needs. In ascending order, the largest values<= sorted_nums[right]sit right before indexright, forming a contiguous slicesorted_nums[left .. right].
Picture Example 1 (
sorted_nums = [2, 3, 5, 6]) as vertical columns of blocks, where+marks the+1increments needed to bring every column up totarget = 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- The final shared value can always be one of the original entries in
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 totarget = sorted_nums[right], thosewindow_len = right - left + 1columns fill a solid rectangle of areatarget * window_len. Before leveling, those columns already containedwindow_sum = sum(sorted_nums[left .. right])blocks. Thus the number of+blocks we need to add is:needed_ops = target * (right - left + 1) - window_sumMaintaining
window_sumin a running integer variable lets us evaluateneeded_ops <= kinO(1)time.Now we can sweep a sliding window (a pair of
leftandrightindices bounding a contiguous slice[left .. right]that glides rightward across the sorted list):- When
rightsteps forward toright + 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
leftthat already exceeded budgetkforrightis guaranteed to still exceedkforright + 1. Soleftnever moves backward—it only ever advances right.
- When
Write the sliding-window loop
For each
rightfrom0ton - 1:- Set
target = sorted_nums[right]and addtargettowindow_sum. - While
target * (right - left + 1) - window_sum > k, the leftmost entrysorted_nums[left]is the smallest (most expensive) member in the window: subtractsorted_nums[left]fromwindow_sumand advanceleft += 1. - Update
best_freqwith the valid window sizeright - left + 1.
Notice two safety details:
- Use strict
>(> k), not>=, because spending allksteps is valid. - Whenever
leftcatches up toright, the window has length1andtarget * 1 - target == 0 <= k, so thewhileloop always terminates withleft <= 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, where10^5 * 10^5 = 10^10overflows a 32-bit signedint, storewindow_sumand the product in 64-bitlong long/long.)- Set
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: 4Example 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: 3Complete 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), wheren = len(nums). SortingnumstakesO(n log n)comparisons, and the sliding-window sweep takesO(n)total work becauserightadvancesntimes andleftadvances at mostntimes across the entire run (every element enters the window once and leaves at most once). - Space:
O(n).sorted(nums)allocates a sorted copy ofnintegers without mutating the caller's list, while the pointers andwindow_sumuseO(1)scalar variables.
Edge cases
- Single-element list (
len(nums) == 1):target * 1 - target == 0 <= k, so the loop finishes withbest_freq = 1for everyk. - All elements already equal (e.g.,
[3, 3, 3, 3]): Every window hasneeded_ops == 0,leftremains0, andbest_freqreachesn. - Budget smaller than every gap (Example 3,
[12, 4, 19], k = 5): Every multi-element window exceedskand shrinks back toleft == right, returning1. - Budget equals the exact deficit (
needed_ops == k): Valid under "at mostksteps"; 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 everyrightrecords[6, 10, 11]atright = 3(best_freq = 3) beforeright = 4(target = 20) shrinks to size1. - 64-bit intermediate products:
target * window_lencan reach10^5 * 10^5 = 10^10; Pythonintscales automatically, whereas C++/Java requirelong long/long.
Common mistakes
- Forgetting to sort
numsfirst: On an unsorted list, entries beforerightare arbitrary—some possibly larger thannums[right]—makingtarget * window_len - window_suminvalid. - Assuming decrements are allowed: In
[1, 10, 10, 10, 11]withk = 1,11cannot be lowered to10, so the answer is3, not4. - Writing
>= kinstead of> kin thewhileloop: Wrongly discards valid windows that spend allksteps (such as Example 1 where8 == k). - Recomputing
sum(sorted_nums[left:right + 1])each step: Slicing and summing inside the loop degrades theO(n)sweep toO(n^2). - Resetting
left = 0for eachright: Because the target only grows withright, 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 arrayprefixwhereprefix[i]stores the sum of the firstisorted numbers so any slice sum equalsprefix[right + 1] - prefix[left]inO(1)time), and for eachrightbinary search for the smallestleftwith leveling deficit<= k. Total complexity staysO(n log n), though the post-sort sweep spendsO(n log n)instead ofO(n). - Counting sort + value-bucket sweep (
O(n + M)time,O(M)space whereM = max(nums) <= 10^5): Counting frequencies in an array avoids comparison sorting, though handling partially consumed buckets at theleftboundary adds extra bookkeeping unnecessary atn <= 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
+1and-1are permitted, bringing a group totcostssum(|x - t|), which is minimized whentis the median (the middle value in sorted order) of that group—meaning an existing entry ofnumsis still an optimal meeting point! In sorted order, the cheapest group around its median is still a contiguous slicesorted_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]tosorted_nums[(left + right) // 2]inO(1), the same two-pointer sweep runs inO(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
fin[1, n](checking inO(n)with a fixed-width window of lengthfwhether anyfconsecutive sorted entries cost<= k), or binary search the leftmost validleftperrightbacked by a prefix-sum array. Overall asymptotic runtime remainsO(n log n)since sorting already takesO(n log n), but the post-sort pass slows fromO(n)toO(n log n)(and per-rightbinary search allocates an extraO(n)prefix-sum array instead of oneO(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 innums(lowering a higher target savesweights[i]per step on every chosen member), and raising entryitotargetcostsweights[i] * (target - nums[i]). However, varying slopesweights[i]break the contiguous sorted-slice property because a smallernums[i]with tinyweights[i]can be cheaper than a closernums[j]with hugeweights[j]; testing each candidate target by sorting smaller items' weighted costs takesO(n^2 log n)time. In the special case whereweights[i]is non-increasing withnums[i], closer values are both nearer and cheaper per unit, restoring theO(n log n)sliding window with deficittarget * window_weight_sum - window_weighted_val_sum.
Follow-up questions
- What changes if each step may either add 1 or subtract 1, allowing elements to meet at any integer?
- How could you replace the two-pointer sweep with binary search, and how does that affect time and space complexity?
- How would your algorithm change if incrementing nums[i] by 1 cost a position-specific weight weights[i] instead of 1?
Similar questions
- Maximum Rocks Along an Up-Right Grid Path
- Decision Tree Split Selection and MSE Gradient Update
- Palindromic Substring Count
- Strictly Rising Subarrays and Three-Group Partition Score
- Hierarchical Resource Tree Manager
- Largest Component Root in Parent-Link Forest
More Goldman Sachs interview questions
- Constant-Time LRU Cache with Fixed Capacity Easy
- Rainwater Trapped Across Unit-Width Elevation Columns Medium
- Strictly Rising Subarrays and Three-Group Partition Score Medium Pro
- Real-Time Telemetry Dashboard: Range Rollups and Watermarking Medium Pro
- Monte Carlo Estimation of Pi Using Cardboard and a Six-Sided Die Medium Pro
- Largest Component Root in Parent-Link Forest Medium Pro
- Translating Equity Signals into Portfolios: Validation, Regimes, and Information Theory Medium Pro
- Maximum Floored Student Average Across Streaming, Disk, and Parallel Execution Medium Pro
- Cheapest Directed Tour Across All Locations Medium Pro
- Room Allocation with Custom Sorting, Streams, and Append-Only Logs Medium Pro