Sliding Subarray Beauty - Problem
You're given an integer array nums containing n integers and two parameters k and x. Your task is to find the "beauty" of each sliding window of size k as you move through the array.
The beauty of a subarray is defined as:
- The
xth smallest negative integer in the subarray, OR 0if there are fewer thanxnegative integers
Note: Only negative numbers contribute to the beauty calculation - positive numbers and zeros are ignored for ranking purposes.
Return an array of n - k + 1 integers representing the beauty values of all possible subarrays of size k.
Example: For array [1, -1, -3, -2, 3] with k=3, x=2, the first window [1, -1, -3] has negatives [-3, -1], so the 2nd smallest is -1.
Input & Output
example_1.py โ Basic Case
$
Input:
nums = [1,-1,-3,-2,3], k = 3, x = 2
โบ
Output:
[-1,-2,-2]
๐ก Note:
Window [1,-1,-3]: negatives are [-3,-1], 2nd smallest is -1. Window [-1,-3,-2]: negatives are [-3,-2,-1], 2nd smallest is -2. Window [-3,-2,3]: negatives are [-3,-2], 2nd smallest is -2.
example_2.py โ Insufficient Negatives
$
Input:
nums = [-1,-2,-3,1,2,3], k = 2, x = 3
โบ
Output:
[0,0,0,0,0]
๐ก Note:
Each window of size 2 has at most 2 negative numbers, but we need the 3rd smallest, so all results are 0.
example_3.py โ 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 all beauty values are 0.
Constraints
- n == nums.length
- 1 โค n โค 105
- 1 โค k โค n
- 1 โค x โค k
- -50 โค nums[i] โค 50
Visualization
Tap to expand
Understanding the Visualization
1
Set Window Size
Define inspection batch size k and target rank x
2
Track Defects
Use frequency counter for defective items in current batch
3
Calculate Beauty
Find x-th worst defect level, or 0 if insufficient defects
4
Slide Batch
Move to next batch, updating defect counters efficiently
Key Takeaway
๐ฏ Key Insight: By constraining negatives to [-50, -1], we can use a fixed-size frequency array and achieve O(n) sliding window processing instead of repeatedly sorting each window.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code