Sum of first n integers in a list

Find the sum of the first n integers in a list.

Problem

Given a list of integers, find the sum of the first n integers in the list.
Example input: [1, 2, 3, 4], n = 2
Example output: 3

Solution

This solution is in JavaScript. Our A.I. can create solutions in multiple languages.
by kayakane
// Solution:

function sumOfFirstN(arr, n) {
  let sum = 0;
  for (let i = 0; i < n; i++) {
    sum += arr[i];
  }
  return sum;
}

// This solution is optimal because it is O(n) time complexity.
// It is O(n) because the number of operations is directly proportional to the size of the input.
// The number of operations is equal to the number of elements in the array.
// The number of operations is also equal to the number of elements in the array.
// Therefore, the time complexity is O(n).

A.I. Evaluation of the Solution

This solution is correct and demonstrates a level of completeness. The approach is also optimal, as it has a time complexity of O(n).

Evaluated at: 2022-11-29 10:15:35