Skip to main content
1 of 9
peterSO
  • 3.6k
  • 14
  • 14

How can I further optimize student average coding challenge?


For a real-world code review, code should be correct, maintainable, robust, reasonably efficient, and, most important, readable.

For your coding challenge, as you requested, I promoted efficiency to be the most important criterion.


I revised your code by simplifying code and stripping out extraneous code.

Using jsbench.me, your code is about 34.12% slower than my revised code.

Here is my revised version of your code:

function totalMarks(N, M, students) {
    let totals = Array(N).fill(0);
    let subjects = Array(M).fill(0);
    for (let [i, marks] of students.entries()) {
        for (let [j, mark] of marks.entries()) {
            totals[i] += mark, 
            subjects[j] += mark;
        }
    }

    let lowIndex = 0, lowValue = subjects[lowIndex];
    for (let i = 1; i < subjects.length; i++) {
        if (lowValue > subjects[i]) {
            lowIndex = i, lowValue = subjects[lowIndex];
        }
    }    

    for (let i = 0; i < totals.length; i++) {
        totals[i]-= students[i][lowIndex];
    }
    return totals;
}

// data
const students = [
    [75, 76, 65, 87, 87],
    [78, 76, 68, 56, 89],
    [67, 87, 78, 77, 65]
];
let N = students.length, M = students[0].length;

totalMarks(N, M, students); // benchmark

console.log(totalMarks(N, M, students)); // test => [ 325, 299, 296 ]
peterSO
  • 3.6k
  • 14
  • 14