Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Data type conversion problem for leetcode pratice "Moving Average from Data Stream"

When I was running the code for the leetcode question ""Moving Average from Data Stream"". I got a partly different output with the expected:
enter image description here
Here is my code:

class MovingAverage {
    
    int front = 0, rear = 0; Double sum = 0.00000;
    int[] data;

    
    public MovingAverage(int size) {
        
        data = new int[size];
        Arrays.fill(data, 0);
        
        
        
    }
    
    public double next(int val) {
        
        if(data.length == 1){
            data[rear] = val;
            return val;
        }else{
             if(rear < data.length){
             data[rear] = val;
             sum += data[rear];
             rear++;         
             return sum/rear;
                 
         }else{
             sum -= data[front];
             rear = (rear+1) % data.length - 1;
             front = (front+1) % data.length ;
             data[rear] = val;
             sum += data[rear];
             rear++;
             return sum/data.length;
         }
         
        }
        

         
    }
}

The requirement for code is :
enter image description here

When I run the tast cases of the example provided, everything is ok.
But when I run this edge case, thing is different:
["MovingAverage","next","next","next","next","next","next","next","next","next","next"]
[[5],[12009],[1965],[-940],[-8516],[-16446],[7870],[25545],[-21028],[18430],[-23464]]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Anyone can help me pls? Is my code wrong or I didn’t process the data conversion well?

>Solution :

This logical check is incorrect:

if (rear < data.length)

In the corresponding else block, when rear = data.length, you set rear = (rear+1) % data.length - 1, so rear < data.length becomes true in the next iteration, and you go back to the if block again. However, the logic to dequeue and update values is in the else block (which is where you should end up once data is filled completely). This is why you’re getting an incorrect answer; if (rear < data.length) isn’t correct.

Replacing that condition with something like if (numberOfElementsTillNow < data.length) should fix this issue.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading