Find the sum of the first n integers in a list.
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: 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).
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