LeetCode 2854: Rolling Average Steps Solution
Master LeetCode problem 2854 (Rolling Average Steps), a medium 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.
2854. Rolling Average Steps
Problem Explanation
Explanation:
To solve this problem, we can use a queue to maintain the rolling average of the last k steps. We will keep track of the sum of the last k steps and update it as new steps are added and old steps are removed. This way, we can calculate the rolling average by dividing the sum by k.
Algorithm:
- Initialize a queue to store the last
ksteps and a variablesumto keep track of the sum of the lastksteps. - Iterate through each step in the input list:
- If the size of the queue is less than
k, add the step to the queue and update the sum. - If the size of the queue is equal to
k, remove the oldest step from the queue, subtract it from the sum, add the new step to the queue, and update the sum. - Calculate the rolling average by dividing the sum by
kand store it in the result list.
- If the size of the queue is less than
- Return the list of rolling averages.
Time Complexity: O(n) where n is the number of steps in the input list. Space Complexity: O(k) where k is the size of the rolling window.
:
Solution Code
class RollingAverageSteps {
public double[] rollingAverage(int[] steps, int k) {
double[] result = new double[steps.length - k + 1];
Queue<Integer> queue = new LinkedList<>();
int sum = 0;
int index = 0;
for (int i = 0; i < steps.length; i++) {
if (queue.size() < k) {
queue.offer(steps[i]);
sum += steps[i];
} else {
result[index] = (double) sum / k;
sum -= queue.poll();
queue.offer(steps[i]);
sum += steps[i];
index++;
}
}
result[index] = (double) sum / k;
return result;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2854 (Rolling Average Steps)?
This page provides optimized solutions for LeetCode problem 2854 (Rolling Average Steps) 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 2854 (Rolling Average Steps)?
The time complexity for LeetCode 2854 (Rolling Average Steps) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2854 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2854 in Java, C++, or Python.