Start learning free

LESSON 140 OF 348 · LOOPS & GLOBAL VARIABLES

Student Grades in TypeScript: Average of an Array in O(n)

Practice Read the full explanation

Given the grades of a student as an array, determine if the student has passed the class.

A Student has passed the class if the average of grades is 5 or more.

The average is defined as (grades[0] + grades[1] + ... + grades[n - 1]) / n

Example 1:

Input: grades = [4, 7, 5, 9, 8, 2]
Output: true
Explanation:
average = (4 + 7 + 5 + 9 + 8 + 2) / 6 =
= 35 / 6 = 5.833333333... >= 5

Example 2:

Input: grades = [4, 7, 5, 3, 8, 2]
Output: false
Explanation:
average = (4 + 7 + 5 + 3 + 8 + 2) / 6 =
= 29 / 6 = 4.83333.. < 5

Hints:

The problem can be broken in 3 steps:
1. Compute the sum of the array
2. Compute the average by dividing the sum by the length of the array
3. Decide the result based on the average being greater than or equal to 5
Let's start with step 1: How can we compute the sum of the array?

First of all, we should store this sum somewhere as we compute it. That 'somewhere' is a variable, let's name it sum. We have to iterate through every element of grades and add its value to sum. How can we achieve this?

With a loop! Let's use a for loop and a variable grade to iterate through the elements:
sum = 0
for each grade in grades:
	sum += grade
When the loop terminates, we know the sum. What should we do next?

We should compute average = sum / length and return average >= 5:
sum = 0
for each grade in grades:
	sum += grade
average = sum / length
return average >= 5


We have a for loop that performs exactly n iterations (n is the length of grades), thus the Time Complexity is O(n).
The only extra space we use are the variables sum, average and the iterator variable grade inside the loop, thus the Extra Space used is O(1).
STEP 1 OF 5
    Ctrl + Enter to check

    TYPESCRIPT · LOOPS & GLOBAL VARIABLES

    Student Grades in TypeScript, explained

    Problem overview

    The method hasPassed receives an array of numbers, grades, and returns true if the average grade is 5 or more, and false otherwise. The average is the sum of the grades divided by how many there are.

    In the first example, [4, 7, 5, 9, 8, 2] sums to 35. Divided by 6 grades that is about 5.83, which is at least 5, so the answer is true. In the second example, [4, 7, 5, 3, 8, 2] sums to 29, and 29 / 6 is about 4.83. That is below 5, so the answer is false.

    Approach: sum, divide, compare

    The problem splits into three small jobs, done in order:

    1. add up all the grades;
    2. divide the sum by the number of grades to get the average;
    3. compare the average with 5.

    Only the first job needs a loop. A running total starts at 0, and each grade is added to it as the loop visits that grade. The other two jobs are one line each. The loop visits every grade once, so the time is proportional to the number of grades, and only a few variables are stored.

    Step by step

    1. Declare sum with let and set it to 0. It is the running total, and since the loop updates it, it can't be const.
    2. Loop over the grades with for...of. The loop variable grade is declared with const and holds one array element per pass. The loop doesn't need the positions of the elements, only their values, so for...of is simpler than counting indices.
    3. Add grade to sum on each pass. After the loop, sum holds the total of all grades.
    4. Compute the average. Declare average as sum / grades.length. Dividing two number values in TypeScript keeps the fractional part, so 35 / 6 is 5.833..., not 5.
    5. Return the comparison. average >= 5 is already a boolean, so the method returns it directly. An if that returns true in one branch and false in the other would only repeat what the expression says.

    The solution in TypeScript

    class Solution {
        hasPassed(grades: number[]): boolean {
            let sum: number = 0;
            for (const grade of grades) {
                sum += grade;
            }
            let average: number = sum / grades.length;
            return average >= 5;
        }
    }
    

    The TypeScript points worth noting:

    • Division does not truncate. Every number is a double, so 7 / 2 is 3.5. Some other languages give 3 for the same expression with integers, but not TypeScript. If you wanted a whole-number result, you'd have to ask for it with Math.floor or Math.trunc. For this lesson the fractional part is not needed to decide the answer, but it keeps the average meaningful.
    • grades.length is a property. There are no parentheses after length.
    • The annotations check nothing at run time. grades: number[] tells the compiler what to expect, but it is erased in the JavaScript. The compiler reports a call such as hasPassed(["5"]), yet the JavaScript would still run.
    • One expression is enough for the return. return average >= 5; works because a comparison produces true or false.

    Complexity

    Time: O(n), where n is the number of grades. The loop does one addition per grade, and the division and comparison happen once.

    Space: O(1). The method stores sum, average and the loop variable, whatever the size of the array.

    Edge cases and common mistakes

    • The average is exactly 5. The condition is "5 or more", so >= is needed. For [5, 5, 5, 4, 6] the sum is 25, the average is 5, and the answer is true. Writing > would return false.
    • A single grade. [5] has an average of 5 and returns true.
    • An empty array. The sum is 0 and the length is 0, and in TypeScript 0 / 0 is NaN, not an error. Every comparison with NaN is false, so the method returns false. The lesson does not ask about this case, but it is worth knowing that no exception is thrown.
    • Dividing by the wrong number. The divisor is the number of grades, grades.length, and not the largest index or a fixed number such as 10.
    • Comparing the sum. sum >= 5 would pass nearly every class. The comparison is on the average.

    Testing

    • [4, 7, 5, 9, 8, 2] gives true.
    • [4, 7, 5, 3, 8, 2] gives false.
    • [5, 5, 5, 4, 6] gives true (the average is exactly 5).
    • [5] gives true.
    • [] gives false.
    Keep going with TypeScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free