Am given a array of numbers [5,1,3, etc, etc].
I want to sum 5&1 and save the results in new array called results.
then sum 5&3 and save results
and then sum 5 & etc till I reach the last number.
after that I want to sum 1&3 and save results.
then sum 1 & etc till the last.
then sum 3 & etc till i reach the last and so on…But I don’t want to sum a number with itself.
i want to achieve this without using nested loops so to maintain time complexity at linear.
function sumTwo(arr) {
const results = []
for(let i = 0; i < arr.length - 1; i++) {
let sum = arr[i] + arr[i + 1]
results.push(sum)
}
console.log(results)
}
console.log(sumTwo([5, 1, 3]));
this outputs = [6,4] instead of [6,8,4]
3
Answers
you can create second results when you create results for first element.
when you create second result for first element you can ignore first element this is first result for second element and etc…
you know?
You can optimize the code a bit to make it more efficient within the O(n^2) boundary. One possible approach is using the concept of a sliding window. But again, it won’t reduce the time complexity to O(n).
This won’t help you escape the O(n^2) time complexity. I’m not sure that you can achieve the desired result without using a nested loop.
You can calculate the
sum
of all elements and then subtract each element from the totalsum
to get thesum
of all other elements.