Skip to main content
Back to problems
Leetcode
Medium
Arrays
Sliding Window
Hash Maps
Sliding Subarray Beauty

Find the x-th smallest negative number in every subarray of length k.

Acceptance 100%
Problem Statement

Given an integer array, scan all contiguous subarrays of length kk. For each window, consider only the negative values inside it and sort those negative values in non-decreasing order. The beauty of the window is the xx-th smallest negative value; if fewer than xx negative values exist, the beauty is $0$.

Return the beauty for every window from left to right.

Input Format

  • An integer array nums
  • Two integers k and x

For every contiguous subarray of length k, compute its beauty as defined above.

Output Format

  • Return an array of integers of length nums.length - k + 1
  • The i-th value is the beauty of the window nums[i..i+k-1]

Constraints

  • The array contains integers
  • 1 <= k <= nums.length
  • 1 <= x <= k
  • Only negative values contribute to the beauty; non-negative values are ignored
  • Return 0 when a window has fewer than x negative values
Examples
Sample cases returned by the problem API.

Example 1

Input

nums = [1,-1,-3,-2,3], k = 3, x = 2

Output

[-1,-2,-2]

Explanation

Windows of size 3 are [1,-1,-3], [-1,-3,-2], and [-3,-2,3]. Their negative values are [-1,-3], [-1,-3,-2], and [-3,-2]. The 2nd smallest negative values are -1, -2, and -2.

Example 2

Input

nums = [-1,-2,-3,-4], k = 2, x = 3

Output

[0,0,0]

Explanation

Each window has only 2 negative values, so none has a 3rd smallest negative value. Every beauty is 0.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.