Find the Running Median

  • + 1 comment

    My short solution, passes all tests. Steps:

    1) Started sorting the input list.
    2) Iterated over the input list starting from the last element and decreasing the iterator. In each step of this loop, calculate the median of the sorted list and remove the last element of the non sorted original input list from the sorted list (using binary search to locate the element). 3) Reversed the result list.

    Code:

    public static List<Double> runningMedian(List<Integer> a) {

        var results = new ArrayList<Double>(); 
        var c = List.copyOf(a);
        Collections.sort(a);
    
        for (int k = a.size(); k > 0; k--) {
            if (k % 2 == 0) {
                results.add(((double) a.get(k / 2) + a.get((k / 2) - 1)) / 2.0);
            } else {
                results.add((double) a.get(k / 2));
            }
            a.remove(Collections.binarySearch(a, c.get(k - 1))); 
        }
        Collections.reverse(results); 
        return results; 
    }