Open In App

Sum of Middle Elements of Two Sorted Arrays using JavaScript

Last Updated : 09 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given 2 sorted arrays Array1 and Array2 of size n each. Merge the given arrays and find the sum of the two middle elements of the merged array.

Example:

Input: array1 = [1, 3, 5]
array2 = [2, 4, 6]
n = 3
Output: 7
Explanation: Given two sorted arrays ar1 and ar2 of size n each: ar1 = [1, 3, 5] and ar2 = [2, 4, 6]. After merging these arrays, we get [1, 2, 3, 4, 5, 6]. The sum of the two middle elements (3 and 4) is 7. Therefore, the output is 7.

Below are the approaches to find the sum of the middle elements of two arrays using JavaScript:

Naive Approach

  • Merge the arrays: Concatenate the two sorted arrays into a single array while maintaining the sorted order.
  • Calculate the middle elements: Find the middle elements of the merged array. If the total length of the array is odd, there will be only one middle element. If it’s even, there will be two middle elements.
  • Calculate the sum: Sum the middle elements found in step 2.

Example: To demonstrate finding the sum of the elements of the two sorted arrays using naive approach.

JavaScript
function sumMidE(arr1, arr2) 
{
    let mergedArray = [];
    let i = 0, j = 0;
    while (i < arr1.length && j < arr2.length) 
    {
        if (arr1[i] < arr2[j])
        {
            mergedArray.push(arr1[i]);
            i++;
        } else 
        {
            mergedArray.push(arr2[j]);
            j++;
        }
    }
    while (i < arr1.length) {
        mergedArray.push(arr1[i]);
        i++;
    }
    while (j < arr2.length) {
        mergedArray.push(arr2[j]);
        j++;
    }
    
    const midIndex = Math
    .floor(mergedArray.length / 2);
    let middleElements;
    if (mergedArray.length % 2 === 0)
    {
        middleElements = 
            [mergedArray[midIndex - 1], mergedArray[midIndex]];
    } else {
        middleElements = [mergedArray[midIndex]];
    }
    
    const sum = middleElements
    .reduce((acc, curr) => acc + curr, 0);
    return sum;
}

const arr1 = [1, 3, 5];
const arr2 = [2, 4, 6];
console.log( sumMidE(arr1, arr2));

Output
7

Time Complexity: O(n + m)

Auxiliary Space: O(n + m)

Binary search is like a smart way to find something quickly in a sorted list. In this problem, we want to use binary search to find the middle numbers in both sorted lists. Then, we’ll add those middle numbers together to get our answer.

  • We start by finding the middle points of both lists.
  • Then, we compare the middle numbers from both lists.
  • If they’re the same, great! We found our answer. We just add them up and we’re done.
  • If the middle number from the first list is smaller, we know our answer must be somewhere to the right of that number in the first list or to the left of that number in the second list. So, we ignore the left side of the first list and the right side of the second list.
  • If the middle number from the first list is bigger, we do the opposite. We ignore the right side of the first list and the left side of the second list.
  • We keep doing these steps until we narrow down the search to two numbers in each list.

Example: To demonstrate finding the sum of the sorted arrays using binary search in JavaScript.

JavaScript
function MaximumSum(array1, array2, size) {
    if (size === 1) {
        return array1[0] + array2[0];
    }
    if (size === 2) {
        return Math
            .max(array1[0], array2[0]) + Math
                .min(array1[1], array2[1]);
    }

    let low = 0;
    let high = size - 1;
    let answer = -1;
    while (low <= high) {
        let cut1 = low + Math
            .floor((high - low) / 2);
        let cut2 = size - cut1;

        let left1 = (cut1 === 0) ? -Infinity : array1[cut1 - 1];
        let left2 = (cut2 === 0) ? -Infinity : array2[cut2 - 1];
        let right1 = (cut1 === size) ? Infinity : array1[cut1];
        let right2 = (cut2 === size) ? Infinity : array2[cut2];

        if (left1 > right2) {
            high = cut1 - 1;
        } else if (left2 > right1) {
            low = cut1 + 1;
        } else {
            answer = Math
                .max(left1, left2) + Math
                    .min(right1, right2);
            break;
        }
    }
    return answer;
}

const array1 = [1, 2, 4, 6, 10];
const array2 = [4, 5, 6, 9, 12];
const length = array1.length;
console.log(MaximumSum(array1, array2, length));

Output
11

Time Complexity: O(log min(n, m))

Auxiliary Space: O(1)

Two Pointer Approach

Two Pointer Approach harnesses the properties of sorted arrays to optimize the search process, making it well-suited for scenarios where performance is paramount. By utilizing two pointers to traverse the arrays simultaneously, this approach minimizes computational complexity and memory overhead.

  • Initialization: Start with two pointers at the beginning of each array and determine if the total length of both arrays is even or odd.
  • Traverse Arrays: Move pointers towards the middle elements of both arrays, comparing elements and updating the middle elements as needed.
  • Identify Middle Elements: After traversal, the middle elements are identified.
  • Calculate Sum: If the total length is even, return the sum of the two middle elements; if odd, return the single middle element.

Example: To demonstrate finding the sum of the two middle elements of the two sorted arrays using two pointer approach in JavaScript.

JavaScript
function sumMiddle(arr1, arr2) {
    let ptr1 = 0;
    let ptr2 = 0;
    const totalLen = arr1.length + arr2.length;
    const isEven = totalLen % 2 === 0;
    let mid1, mid2;

    for (let i = 0; i <= totalLen / 2; i++) {
        mid1 = mid2;
        if (arr1[ptr1] === undefined || arr2[ptr2] < arr1[ptr1]) {
            mid2 = arr2[ptr2];
            ptr2++;
        } else {
            mid2 = arr1[ptr1];
            ptr1++;
        }
    }

    return isEven ? mid1 + mid2 : mid2;
}

const arr1 = [1, 3, 5];
const arr2 = [2, 4, 6];
console.log(sumMiddle(arr1, arr2));

Output
7

Time Complexity: O(min(n, m))

Space Auxiliary: O(1)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads