K Radius Subarray Averages

Given a 0-indexed array `nums` of `n` integers and an integer `k`, the k-radius average for the subarray centered at index `i` is the average of `nums[i - k..i + k]` (inclusive), using integer division that truncates toward zero. If fewer than `k` elements exist on either side of `i`, the k-radius average is `-1`. Return an array `avgs` of length `n` where `avgs[i]` is the k-radius average centered at `i`.

30:00

K Radius Subarray Averages
medium
Free written solution
Topics
Companies

Given a 0-indexed array nums of n integers and an integer k, the k-radius average for the subarray centered at index i is the average of nums[i - k..i + k] (inclusive), using integer division that truncates toward zero. If fewer than k elements exist on either side of i, the k-radius average is -1. Return an array avgs of length n where avgs[i] is the k-radius average centered at i.

Example 1:
Input: {"nums":[7,4,3,9,1,8,5,2,6],"k":3}
Output: [-1,-1,-1,5,4,4,-1,-1,-1]
Constraints:
  • n=nums.lengthn = \text{nums.length}

  • 1≤n≤1051 \leq n \leq 10^5

  • 0≤nums[i],k≤1050 \leq \text{nums}[i], k \leq 10^5

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[7,4,3,9,1,8,5,2,6],"k":3}

The lens around a center covers 2k + 1 = 7 elements. Centers closer than 3 to an edge keep -1.

nums, lens of radius k = 3

7

4

3

9

1

8

5

2

6

0

1

2

3

4

5

6

7

8

↓

↓

↓

↓

↓

↓

↓

↓

↓

avgs

-1

-1

-1

-1

-1

-1

striped = fewer than k neighbours on a side, stays -1

sum = 0

width = 2k + 1 = 7

Variables
VariableValue
k3
width7
n9
DepthFunction Call
Stack empty
0/13