#2653

Sliding Subarray Beauty

Medium
ArrayHash TableSliding WindowHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(k)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

By maintaining a frequency count of negative numbers in the current window, we can efficiently determine the x-th smallest negative integer without sorting each time.

⚙️

Algorithm

4 steps
  1. 1Step 1: Use a frequency map to count negative numbers in the current window of size k.
  2. 2Step 2: For each new element added to the window, update the frequency map.
  3. 3Step 3: When moving the window, remove the element that is sliding out and update the frequency map accordingly.
  4. 4Step 4: To find the x-th smallest negative, iterate through the frequency map in sorted order.
solution.py21 lines
1from collections import defaultdict
2
3def beautyOfSubarrays(nums, k, x):
4    result = []
5    freq = defaultdict(int)
6    negatives = []
7
8    for i in range(len(nums)):
9        if nums[i] < 0:
10            freq[nums[i]] += 1
11            if freq[nums[i]] == 1:
12                negatives.append(nums[i])
13        if i >= k:
14            if nums[i - k] < 0:
15                freq[nums[i - k]] -= 1
16                if freq[nums[i - k]] == 0:
17                    negatives.remove(nums[i - k])
18        if i >= k - 1:
19            negatives.sort()
20            result.append(negatives[x - 1] if len(negatives) >= x else 0)
21    return result

Complexity note: This complexity arises from maintaining the frequency map and sorting the negatives, which is efficient compared to the brute force approach.

  • 1Maintaining a frequency count allows for efficient updates as the window slides.
  • 2Sorting the negatives only when necessary reduces unnecessary computations.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.