Minimum Subarray Length With Distinct Sum At Least K Problem
#3795
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3795.
You are given an integer array nums and an integer k.
Return the minimum length of a subarray whose sum of the distinct values present in that subarray (each value counted once) is at least k. If no such subarray exists, return -1.
Example 1:
Input: nums = [2,2,3,1], k = 4
Output: 2
Explanation:
The subarray [2, 3] has distinct elements {2, 3} whose sum is 2 + 3 = 5, which is at least k = 4. Thus, the answer is 2.
Example 2:
Input: nums = [3,2,3,4], k = 5
Output: 2
Explanation:
The subarray [3, 2] has distinct elements {3, 2} whose sum is 3 + 2 = 5, which is at least k = 5. Thus, the answer is 2.
Example 3:
Input: nums = [5,5,4], k = 5
Output: 1
Explanation:
The subarray [5] has distinct elements {5} whose sum is 5, which is at least k = 5. Thus, the answer is 1.
Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 10^51 <= k <= 10^9
Solution
Approach: Sliding Window
Making a window larger can only add new distinct values, so the sum of distinct values never decreases as the window grows. That is what makes a sliding window work.
Keep a window [l, r], a table cnt of how many times each value occurs in it, and s, the sum of its distinct values.
- Move
rto the right. Ifnums[r]is new to the window (its count becomes1), add it tos. - While
s >= k, the window is valid: record its length, then dropnums[l]from the left. If its count falls to0, subtract it froms. - At the end, return the shortest recorded length, or
-1if no window was valid.
Complexity: O(n) time, since each index enters and leaves the window once, and O(n) extra space for the table.
from collections import defaultdict
class Solution:
def minLength(self, nums: List[int], k: int) -> int:
cnt = defaultdict(int)
n = len(nums)
ans = n + 1
s = l = 0
for r, x in enumerate(nums):
cnt[x] += 1
if cnt[x] == 1:
s += x
while s >= k:
ans = min(ans, r - l + 1)
cnt[nums[l]] -= 1
if cnt[nums[l]] == 0:
s -= nums[l]
l += 1
return -1 if ans > n else ans