Leetcode 2090: K Radius Subarray Averages

grid47
grid47
Exploring patterns and algorithms
Apr 12, 2024 6 min read

Given an array of integers, you need to compute the k-radius average for each element in the array. The k-radius average for an element at index i is the average of the elements from index i - k to i + k (inclusive). If there are fewer than k elements before or after the index i, the result for that index will be -1.
Problem
Approach
Steps
Complexity
Input: You are given an integer array nums and an integer k.
Example: nums = [7,4,3,9,1,8,5,2,6], k = 3
Constraints:
• 1 <= nums.length <= 10^5
• 0 <= k <= 10^5
• -10^9 <= nums[i] <= 10^9
Output: Return an array of integers where each element is the k-radius average for the corresponding index in the input array.
Example: Output: [-1,-1,-1,5,4,4,-1,-1,-1]
Constraints:
• The length of the output array is the same as the input array.
Goal: Calculate the k-radius average for each index in the array.
Steps:
• Initialize an array to store prefix sums of the input array.
• For each index, check if there are enough elements to the left and right to calculate the k-radius average.
• If there are enough elements, compute the sum of the subarray and calculate the integer division of the sum by the total number of elements.
• If there are not enough elements, set the result for that index to -1.
Goal: The function must handle large input sizes efficiently.
Steps:
• 1 <= nums.length <= 10^5
• 0 <= k <= 10^5
• -10^9 <= nums[i] <= 10^9
Assumptions:
• The array may contain both large positive and negative integers.
• The function should be optimized for large inputs.
Input: Input: nums = [1,2,3,4,5], k = 2
Explanation: The k-radius average for index 2 is calculated using elements from index 0 to index 4. The sum is 15, so the average is 15 // 5 = 3.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus