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;
}

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.

Further reading

Problem with a question

Algorithms and Data Structures · Junior · question 2

Test yourself

Take the Algorithms and Data Structures · Junior quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz