Sliding Subarray Beauty - Problem
Given an integer array nums containing n integers, find the beauty of each subarray of size k.
The beauty of a subarray is the xth smallest integer in the subarray if it is negative, or 0 if there are fewer than x negative integers.
Return an integer array containing n - k + 1 integers, which denote the beauty of the subarrays in order from the first index in the array.
A subarray is a contiguous non-empty sequence of elements within an array.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [1,-1,-3,-2,3], k = 3, x = 2
›
Output:
[-1,-2,-2]
💡 Note:
Window [1,-1,-3]: negatives [-3,-1], 2nd smallest is -1. Window [-1,-3,-2]: negatives [-3,-2,-1], 2nd smallest is -2. Window [-3,-2,3]: negatives [-3,-2], 2nd smallest is -2.
Example 2 — Insufficient Negatives
$
Input:
nums = [-1,2,-3,4,-5], k = 2, x = 3
›
Output:
[0,0,0,0]
💡 Note:
Each window of size 2 has at most 2 elements, so fewer than 3 negatives. Beauty is 0 for all windows.
Example 3 — All Positives
$
Input:
nums = [1,2,3,4,5], k = 3, x = 1
›
Output:
[0,0,0]
💡 Note:
No negative numbers in any window, so beauty is always 0.
Constraints
- 1 ≤ n == nums.length ≤ 105
- 1 ≤ k ≤ n
- 1 ≤ x ≤ k
- -50 ≤ nums[i] ≤ 50
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array with mixed positive/negative values and parameters k, x
2
Sliding Windows
Process each subarray of size k, tracking only negatives
3
Beauty Calculation
Find x-th smallest negative or return 0
Key Takeaway
🎯 Key Insight: Only negative numbers matter for beauty calculation - use sliding window to efficiently track their frequencies
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code