Skip to content

Commit

Permalink
feature: k radius subarray averages using sliding window prefix sum
Browse files Browse the repository at this point in the history
  • Loading branch information
solairerove committed Jun 20, 2023
1 parent 1863d8b commit 912fcdb
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
17 changes: 17 additions & 0 deletions arrays/KRadiusSubarrayAverages.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
from typing import List


# O(n) time || O(1) space
def get_averages(self, nums: List[int], k: int) -> List[int]:
n = len(nums)
res = [-1] * n

left, curr_window_sum, diameter = 0, 0, 2 * k + 1
for right in range(n):
curr_window_sum += nums[right]
if right - left + 1 >= diameter:
res[left + k] = curr_window_sum // diameter
curr_window_sum -= nums[left]
left += 1

return res
15 changes: 15 additions & 0 deletions arrays/test/test_get_averages.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import unittest

from arrays.KRadiusSubarrayAverages import get_averages


class MyTestCase(unittest.TestCase):
def test_get_averages(self):
self.assertEqual([-1, -1, -1, 5, 4, 4, -1, -1, -1], get_averages(self, [7, 4, 3, 9, 1, 8, 5, 2, 6], 3))

def test_get_averages_1(self):
self.assertEqual([100000], get_averages(self, [100000], 0))


if __name__ == '__main__':
unittest.main()

0 comments on commit 912fcdb

Please sign in to comment.