skip to Main Content

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


  1. 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?

    Login or Signup to reply.
  2. 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).

    function sumTwo(arr) {
      const results = [];
    
      for (let i = 0; i < arr.length; i++) {
        for (let j = i + 1; j < arr.length; j++) {
          results.push(arr[i] + arr[j]);
        }
      }
      return results;
    }
    
    const output = sumTwo([5, 1, 3]);
    console.log(output); // outputs: [6, 8, 4]
    

    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.

    Login or Signup to reply.
  3. You can calculate the sum of all elements and then subtract each element from the total sum to get the sum of all other elements.

    function sumTwo(arr) {
      const results = arr.reduce((acc, value, index) => {
        return acc.concat(
          arr.slice(index + 1).map((otherValue) => value + otherValue)
        );
      }, []);
    
      return results;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search