Skip to content

Commit 920f1f1

Browse files
committed
Sync LeetCode submission Runtime - 1 ms (87.96%), Memory - 20.9 MB (6.68%)
1 parent bce1109 commit 920f1f1

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
<p>Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.</p>
2+
3+
<p>Implement the&nbsp;<code>MovingAverage</code> class:</p>
4+
5+
<ul>
6+
<li><code>MovingAverage(int size)</code> Initializes&nbsp;the object with the size of the window <code>size</code>.</li>
7+
<li><code>double next(int val)</code> Returns the moving average of the last <code>size</code> values of the stream.</li>
8+
</ul>
9+
10+
<p>&nbsp;</p>
11+
<p><strong class="example">Example 1:</strong></p>
12+
13+
<pre>
14+
<strong>Input</strong>
15+
[&quot;MovingAverage&quot;, &quot;next&quot;, &quot;next&quot;, &quot;next&quot;, &quot;next&quot;]
16+
[[3], [1], [10], [3], [5]]
17+
<strong>Output</strong>
18+
[null, 1.0, 5.5, 4.66667, 6.0]
19+
20+
<strong>Explanation</strong>
21+
MovingAverage movingAverage = new MovingAverage(3);
22+
movingAverage.next(1); // return 1.0 = 1 / 1
23+
movingAverage.next(10); // return 5.5 = (1 + 10) / 2
24+
movingAverage.next(3); // return 4.66667 = (1 + 10 + 3) / 3
25+
movingAverage.next(5); // return 6.0 = (10 + 3 + 5) / 3
26+
</pre>
27+
28+
<p>&nbsp;</p>
29+
<p><strong>Constraints:</strong></p>
30+
31+
<ul>
32+
<li><code>1 &lt;= size &lt;= 1000</code></li>
33+
<li><code>-10<sup>5</sup> &lt;= val &lt;= 10<sup>5</sup></code></li>
34+
<li>At most <code>10<sup>4</sup></code> calls will be made to <code>next</code>.</li>
35+
</ul>
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# Approach 2: Double ended queue
2+
3+
# Time: O(1)
4+
# Space: O(n), n = size of moving window
5+
6+
from collections import deque
7+
8+
class MovingAverage:
9+
10+
def __init__(self, size: int):
11+
self.size = size
12+
self.queue = deque()
13+
self.window_sum = 0
14+
15+
def next(self, val: int) -> float:
16+
self.queue.append(val)
17+
count = len(self.queue)
18+
tail = self.queue.popleft() if count > self.size else 0
19+
20+
self.window_sum = self.window_sum - tail + val
21+
22+
return self.window_sum / min(self.size, count)
23+
24+
25+
# Your MovingAverage object will be instantiated and called as such:
26+
# obj = MovingAverage(size)
27+
# param_1 = obj.next(val)

0 commit comments

Comments
 (0)