#2090

K Radius Subarray Averages

Medium
ArraySliding WindowSliding WindowPrefix Sums
LeetCode ↗

Approaches

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

Intuition

Time O(n)Space O(n)

The optimal solution uses a sliding window technique to maintain the sum of the current k-radius subarray, allowing us to compute averages in constant time after the initial sum. This significantly reduces the time complexity.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize an empty result array avgs of the same length as nums and a variable total to keep track of the current sum.
  2. 2Step 2: Calculate the sum of the first 2k+1 elements (if possible) and store the average for the center index k.
  3. 3Step 3: Slide the window one element at a time, updating the total by subtracting the element that is sliding out and adding the new element that is sliding in, and calculate the new average.
solution.py11 lines
1def getAverages(nums, k):
2    n = len(nums)
3    avgs = [-1] * n
4    if 2 * k + 1 > n:
5        return avgs
6    total = sum(nums[:2 * k + 1])
7    avgs[k] = total // (2 * k + 1)
8    for i in range(k + 1, n - k):
9        total += nums[i + k] - nums[i - k - 1]
10        avgs[i] = total // (2 * k + 1)
11    return avgs

Complexity note: The time complexity is O(n) because we traverse the array once to calculate the initial sum and then slide the window across the array. The space complexity is O(n) due to the output array avgs.

  • 1Using a sliding window can significantly reduce time complexity.
  • 2Understanding when to apply prefix sums or sliding window techniques is crucial.

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