Sum of middle elements of two sorted Arrays

By | September 23, 2023

Given 2 sorted arrays A and B of size N each. Print the sum of the middle elements of the array obtained after merging the given arrays.

Examples:

Input: arr1: 1 2 4 6 10
Input: arr2: 4 5 6 9 12
Output: 11 (5 + 6)

The approach is similar to that of Merge function of Merge Sort. We will merge the given arrays into a vector in sorted form. Since the size of both arrays is the same ‘n’, the middle elements would be at index ‘n-1’ and ‘n’. Add them and return.

C++ Implementation:

#include <bits/stdc++.h>
using namespace std;
int main()
{
    int t;
    cin >> t;
    // for multiple test cases
    while (t--)
    {
        int n;
        cin >> n;
        int arr1[n], arr2[n];
        vector<int> v;
        // input two arrays separately
        for (int i = 0; i < n; i++)
        {
            cin >> arr1[i];
        }
        for (int i = 0; i < n; i++)
        {
            cin >> arr2[i];
        }
        int i = 0, j = 0;
        // Compare elements of both arrays and store
        // in sorted format in a vector
        while (i < n and j < n)
        {
            if (arr1[i] > arr2[j])
            {
                v.push_back(arr2[j]);
                j++;
            }
            else
            {
                v.push_back(arr1[i]);
                i++;
            }
        }
        // Adding middle elements of vector
        cout << v[n - 1] + v[n] << endl;
    }
    return 0;
}

Time Complexity: O(N)

Author: Mithlesh Upadhyay

Mithlesh Upadhyay is a Computer Science and AI expert from Madhya Pradesh with strong academic background (BE in CSE and M.Tech in AI) and over six years of experience in technical content development. He has contributed tech articles, led teams, and worked in Full Stack Development and Data Science. He founded the w3colleges.org portal for learning resources.