Find the Running Median

  • + 0 comments

    JS

    function runningMedian(a) {
        // Write your code here
        const currentArr = [];
        const results = [];
        
        for(let i = 0; i < a.length; i++) {
            if(!currentArr.length) {
                currentArr.push(a[i]);
            } else if (a[i] < currentArr[0]) {
                currentArr.unshift(a[i]);
            } else if(a[i] > currentArr[currentArr.length - 1]) {
                currentArr.push(a[i])
            } else {
                // seems like we need to insert somewhere in the middle
                let index = 0;
                // Find the correct index to insert the new number
                while (index < a.length && currentArr[index] < a[i]) {
                    index++;
                }
                // Insert the new number at the found index
                currentArr.splice(index, 0, a[i]);
            }
    
            // calculate the median for current list
            if(currentArr.length % 2 === 0) {
                results.push(((currentArr[(currentArr.length/2) - 1] + currentArr[currentArr.length/2]) / 2).toFixed(1));
            } else {
                results.push(currentArr[Math.floor(currentArr.length/2)].toFixed(1));
            }
        }
        
        return results;
    }