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
  • 0 if there are fewer than x negative 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
Sliding Window Beauty Algorithm1-1-3-23Window k=3: [1, -1, -3]Frequency Counter:-3: 1 occurrence-1: 1 occurrencex=2: 2nd smallest = -1Beauty-1Find x-th smallest
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.
Asked in
Google 25 Amazon 18 Microsoft 12 Meta 8
28.5K Views
Medium-High Frequency
~18 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen