LeetCode 2090: K Radius Subarray Averages Solution

Master LeetCode problem 2090 (K Radius Subarray Averages), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2090. K Radius Subarray Averages

Problem Explanation

Explanation

To solve this problem, we can iterate through the given array nums and for each index i, calculate the sum of elements within the range [i-k, i+k]. If the number of elements within this range is less than 2*k+1, we set the average to -1, otherwise, we calculate the average. We repeat this process for all indices and store the results in the output array avgs.

Algorithm:

  1. Initialize an array avgs of size n to store the k-radius averages.
  2. Iterate over each index i in the range [0, n-1].
  3. Calculate the sum of elements in the range [max(0, i-k), min(n-1, i+k)].
  4. If the number of elements in this range is less than 2*k+1, set avgs[i] to -1, otherwise calculate the average.
  5. Return the avgs array.

Time Complexity:

The time complexity of this algorithm is O(n), where n is the length of the input array nums.

Space Complexity:

The space complexity of this algorithm is O(n) for the output array avgs.


Solution Code

class Solution {
    public int[] kRadiusAverages(int[] nums, int k) {
        int n = nums.length;
        int[] avgs = new int[n];
        
        for (int i = 0; i < n; i++) {
            int sum = 0;
            int count = 0;
            for (int j = Math.max(0, i - k); j <= Math.min(n-1, i + k); j++) {
                sum += nums[j];
                count++;
            }
            if (count < 2*k+1) {
                avgs[i] = -1;
            } else {
                avgs[i] = sum / count;
            }
        }
        return avgs;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2090 (K Radius Subarray Averages)?

This page provides optimized solutions for LeetCode problem 2090 (K Radius Subarray Averages) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2090 (K Radius Subarray Averages)?

The time complexity for LeetCode 2090 (K Radius Subarray Averages) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2090 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2090 in Java, C++, or Python.

Back to LeetCode Solutions