Algorithms and Data Structures · Junior · Question 2 of 75
What is the time complexity of this function?
function sum(arr) {
let total = 0;
for (const x of arr) total += x;
return total;
}- ✓Correct answer: O(n)
- 2O(n²)
- 3O(1)
Explanation
The loop visits each element once, so the work grows linearly with the length of the array. The additions and the assignment inside the loop are constant-time operations.