KatInterview

Shortest Window With Unique-Value Sum Meeting a Goal

Arrays & HashingAuto-graded · 26 test cases
MediumAuto-gradedArrays & Hashingsliding-windowhash-maptwo-pointers

Last 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 i through j with i <= j; its length is j - 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. Return 0 when none exists.

Constraints

  • 1 <= len(values) <= 10^5
  • 1 <= values[i] <= 10^4
  • 1 <= 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.