LeetCode 346: Moving Average from Data Stream Solution
Master LeetCode problem 346 (Moving Average from Data Stream), a easy 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.
346. Moving Average from Data Stream
Problem Explanation
Explanation
To solve this problem, we can use a queue to store the incoming data values. We will maintain a running sum of the elements currently in the queue to calculate the moving average efficiently. When a new element comes in, we add it to the queue and update the running sum. If the queue size exceeds the specified window size, we remove the oldest element from the queue and update the running sum accordingly.
Time Complexity
- The time complexity for adding a new element and calculating the moving average is O(1) since we are only performing constant time operations for each element.
Space Complexity
- The space complexity is O(n) where n is the specified window size, as we are storing at most n elements in the queue at any given time.
Solution Code
import java.util.LinkedList;
import java.util.Queue;
class MovingAverage {
private Queue<Integer> queue;
private int size;
private double sum;
public MovingAverage(int size) {
this.queue = new LinkedList<>();
this.size = size;
this.sum = 0.0;
}
public double next(int val) {
if (queue.size() == size) {
sum -= queue.poll();
}
queue.offer(val);
sum += val;
return sum / queue.size();
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 346 (Moving Average from Data Stream)?
This page provides optimized solutions for LeetCode problem 346 (Moving Average from Data Stream) 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 346 (Moving Average from Data Stream)?
The time complexity for LeetCode 346 (Moving Average from Data Stream) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 346 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 346 in Java, C++, or Python.