Shortest Window With Unique-Value Sum Meeting a Goal
Arrays & HashingAuto-graded · 26 test casesLast updated
Sliding-window task where the window score is the sum of its distinct values, not the plain sum of its elements.
You are given a list of positive integers values and a positive integer goal. A subarray is any nonempty block of consecutive positions in values.
Define the unique sum of a subarray as the total obtained by adding up each different number appearing in it exactly once, no matter how many times that number occurs inside the block. For instance, the block [7, 7, 4] has unique sum 7 + 4 = 11.
Return the number of elements in the shortest subarray whose unique sum is greater than or equal to goal. Length is measured by position count, so repeated elements inside the block still each contribute 1 to the length. If no subarray reaches the goal, return 0.
Function Signature
def min_span_covering_unique_sum(values: List[int], goal: int) -> int:
Rules
- A subarray spans positions
ithroughjwithi <= j; its length isj - i + 1, counting every element including duplicates. - A number repeated inside the subarray contributes its value to the unique sum only once, whether the copies sit together or far apart.
- Among all subarrays whose unique sum is at least
goal, return the smallest length. Return0when none exists.
Constraints
1 <= len(values) <= 10^51 <= values[i] <= 10^41 <= goal <= 10^9- Every unique sum stays below
10^8, so results fit comfortably in a 32-bit signed integer
Examples
Example 1
Input: min_span_covering_unique_sum([5, 5, 1, 2, 6], 9)
Output: 3
Example 2
Input: min_span_covering_unique_sum([4, 4, 4, 3], 8)
Output: 0
Example 3
Input: min_span_covering_unique_sum([4, 2, 2, 5], 11)
Output: 4
Hints
Hint 1
Extending a subarray can only add new distinct values, so the unique sum never drops as the block grows — that monotonicity allows a two-pointer window.
Hint 2
Track how many times each value currently appears inside the window; adjust the running unique sum only when a count moves between 0 and 1.
Hint 3
For each right endpoint, shrink from the left while the window still meets the goal, recording the window length each time, and keep the smallest recorded length.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Use a sliding window values[left..right] together with a frequency map of the values currently inside it, plus a running unique_total that equals the sum of distinct values in the window.
The crucial observation is monotonicity: adding an element to a window can only introduce a distinct value or repeat one already present, so the unique sum never decreases as the window grows, and never increases as it shrinks. That is precisely what a two-pointer scan requires.
For each right endpoint, insert the new element, bumping unique_total only when its count rises from 0 to 1. Then, while the window still meets the goal, record its length as a candidate answer and drop the leftmost element, decreasing unique_total only when that value's count falls to 0. Each index enters the window once and leaves at most once.
Why It Is Correct
Because the unique sum is monotone under shrinking, all windows ending at a given right endpoint that meet the goal form a prefix of possible left endpoints: once a window is too small, every further shrink is also too small. The inner loop visits exactly the valid windows ending at that right endpoint, so their shortest one is recorded. Any other left endpoint that was skipped corresponds to a longer window ending at the same or an earlier right endpoint, so it cannot improve the best answer. Taking the minimum over all right endpoints yields the global shortest valid subarray, and if the goal is never reached, best stays 0.
Complexity
- Time: O(n), since each index is added once and removed at most once, with O(1) expected hash-map operations.
- Space: O(k), where k is the number of distinct values in the current window (at most
min(n, 10^4)).
from typing import List
def min_span_covering_unique_sum(values: List[int], goal: int) -> int:
freq = {}
unique_total = 0
best = 0
left = 0
for right, x in enumerate(values):
c = freq.get(x, 0)
if c == 0:
unique_total += x
freq[x] = c + 1
while unique_total >= goal:
span = right - left + 1
if best == 0 or span < best:
best = span
y = values[left]
freq[y] -= 1
if freq[y] == 0:
unique_total -= y
left += 1
return best