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
Sliding Subarray Beauty INPUT nums array: 1 -1 -3 -2 3 0 1 2 3 4 Parameters: k = 3 (window size) x = 2 (xth smallest) Sliding Window (k=3): [1,-1,-3] [-1,-3,-2] [-3,-2,3] ALGORITHM STEPS 1 Initialize Freq Array count[-50..50] = all zeros 2 Build First Window Add first k elements 3 Find xth Smallest Neg Scan freq from -50 to -1 4 Slide Window Remove left, add right Window [1,-1,-3] Freq Count: val: -3 -2 -1 1 cnt: 1 0 1 1 Negatives sorted: [-3, -1] x=2, so 2nd smallest = -1 Beauty = -1 FINAL RESULT Beauty values for each window: Window 0: [1,-1,-3] Neg sorted: [-3,-1], x=2 -1 Window 1: [-1,-3,-2] Neg sorted: [-3,-2,-1], x=2 -2 Window 2: [-3,-2,3] Neg sorted: [-3,-2], x=2 -2 Output Array: [-1,-2,-2] OK - n-k+1 = 3 values Key Insight: Fixed-size frequency array [-50 to 50] allows O(1) updates when sliding the window. Finding xth smallest negative: iterate from index -50 to -1, counting frequencies until sum >= x. Time: O(n * 101) = O(n), Space: O(101) = O(1) since value range is fixed [-50, 50]. TutorialsPoint - Sliding Subarray Beauty | Fixed Array Frequency Counter Approach
Asked in
Amazon 35 Microsoft 28 Google 22 Apple 15
28.4K Views
Medium Frequency
~25 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