August 2024
Intermediate to advanced
516 pages
11h 47m
English
The following method accepts an array of numbers and returns the mean average of all its even numbers. How would we express its efficiency in terms of Big O?
| | function averageOfEvenNumbers(array) { |
| | let sum = 0; |
| | let countOfEvenNumbers = 0; |
| | |
| | for (const number of array) { |
| | if (number % 2 === 0) { |
| | sum += number; |
| | countOfEvenNumbers += 1; |
| | } |
| | }; |
| | |
| | if (countOfEvenNumbers === 0) { return null; } |
| | |
| | return Math.floor(sum / countOfEvenNumbers); |
| | } |
Here’s how to break the code down to determine its efficiency.
Remember that Big O is all about answering the key question: if there are N data elements, how many steps will the algorithm take? Therefore, the first thing we want to do is determine ...
Read now
Unlock full access