Sum of middle elements of two sorted Arrays (original) (raw)
Last Updated : 23 Jul, 2025
Given two sorted arrays, **arr1[] and **arr2[], each of size **N, the task is to merge the arrays and find the sum of the two middle elements of the merged array.
**Example:
**Input: N = 5, arr1[] = {1,2,4,6,10}, arr2[] = {4,5,6,9,12}
**Output: 11
**Explanation: The merged array is {1,2,4,4,5,6,6,9,10,12}. The sum of the middle elements (5 and 6) is 11.**Input: N = 5, arr1[] = {1,12,15,26,38}, arr2[]={2,13,17,30,45}
**Output: 32
**Explanation: The merged array is {1,2,12,13,15,17,26,30,38,45}. The sum of the middle elements (15 and 17) is 32.
[Naive Approach] Using Merging Arrays with space- O(n) time and O(n) auxiliary space
The simplest way to solve the problem is to merge the two sorted arrays into one single sorted array. Merging two sorted array can be done by initializing a new array **merged[] of size **2*N, we traverse both **arr1[] and **arr2[] simultaneously using two pointers. We compare the current elements of both arrays and append the smaller element to **merged[]. Once all elements are merged, the middle two elements are at positions **N-1 and **N, and their sum is the required result.
C++ `
#include <bits/stdc++.h> using namespace std;
// Function to find the sum of the middle elements of the // merged array int findMidSum(int arr1[], int arr2[], int n) { // Create a merged array of size 2*n int merged[2 * n]; int i = 0, j = 0, k = 0;
// Traverse both arrays and merge them into the merged
// array
while (i < n && j < n) {
if (arr1[i] <= arr2[j]) {
merged[k++] = arr1[i++];
}
else {
merged[k++] = arr2[j++];
}
}
// If there are remaining elements in arr1[], add them
// to merged array
while (i < n) {
merged[k++] = arr1[i++];
}
// If there are remaining elements in arr2[], add them
// to merged array
while (j < n) {
merged[k++] = arr2[j++];
}
// Return the sum of the middle two elements
return merged[n] + merged[n - 1];}
int main() { int arr1[] = { 1, 2, 4, 6, 10 }; int arr2[] = { 4, 5, 6, 9, 12 }; int n = sizeof(arr1) / sizeof(arr1[0]);
// Function call to find the sum of the middle elements
cout << findMidSum(arr1, arr2, n) << endl;
return 0;}
Java
public class FindMidSum {
public static int findMidSum(int[] arr1, int[] arr2,
int n)
{
// Create a merged array of size 2*n
int[] merged = new int[2 * n];
int i = 0, j = 0, k = 0;
// Traverse both arrays and merge them into the
// merged array
while (i < n && j < n) {
if (arr1[i] <= arr2[j]) {
merged[k++] = arr1[i++];
}
else {
merged[k++] = arr2[j++];
}
}
// If there are remaining elements in arr1[], add
// them to merged array
while (i < n) {
merged[k++] = arr1[i++];
}
// If there are remaining elements in arr2[], add
// them to merged array
while (j < n) {
merged[k++] = arr2[j++];
}
// Return the sum of the middle two elements
return merged[n] + merged[n - 1];
}
public static void main(String[] args)
{
int[] arr1 = { 1, 2, 4, 6, 10 };
int[] arr2 = { 4, 5, 6, 9, 12 };
int n = arr1.length;
// Function call to find the sum of the middle
// elements
int midSum = findMidSum(arr1, arr2, n);
System.out.println(midSum);
}}
Python
def find_mid_sum(arr1, arr2, n):
merged = []
i, j, k = 0, 0, 0
# Merge the two arrays into a single sorted array
while i < n and j < n:
if arr1[i] <= arr2[j]:
merged.append(arr1[i])
i += 1
else:
merged.append(arr2[j])
j += 1
# Add remaining elements from arr1
while i < n:
merged.append(arr1[i])
i += 1
# Add remaining elements from arr2
while j < n:
merged.append(arr2[j])
j += 1
# Return the sum of the middle two elements
return merged[n] + merged[n - 1]Example usage
arr1 = [1, 2, 4, 6, 10] arr2 = [4, 5, 6, 9, 12] n = len(arr1)
mid_sum = find_mid_sum(arr1, arr2, n) print(mid_sum)
JavaScript
function findMidSum(arr1, arr2, n) {
// Create a merged array of size 2*n const merged = new Array(2 * n); let i = 0, j = 0, k = 0;
// Merge the two arrays into the merged array while (i < n && j < n) { if (arr1[i] <= arr2[j]) { merged[k++] = arr1[i++]; } else { merged[k++] = arr2[j++]; } }
// Add remaining elements from arr1 while (i < n) { merged[k++] = arr1[i++]; }
// Add remaining elements from arr2 while (j < n) { merged[k++] = arr2[j++]; }
// Return the sum of the middle two elements return merged[n] + merged[n - 1]; }
// Example usage const arr1 = [1, 2, 4, 6, 10]; const arr2 = [4, 5, 6, 9, 12]; const n = arr1.length;
const midSum = findMidSum(arr1, arr2, n); console.log(midSum);
`
**[Optimized Approach] Using Merging Arrays without space - O(n) time and O(1) auxiliary space
In the optimized approach, we eliminate the need for an auxiliary array by keeping track of the middle elements during a single pass merge. Using two pointers for **arr1[] and **arr2[], and two variables **m1 and **m2 to store the middle elements, we traverse both arrays. At each step, we update **m1 to the previous **m2 and set **m2 to the smaller current element of the two arrays. This continues until we reach the middle of the merged array, ensuring **m1 and **m2 hold the middle elements.
C++ `
#include <bits/stdc++.h> using namespace std;
// Function to find the sum of the middle elements of the // merged array int findMidSum(int arr1[], int arr2[], int n) { int i = 0, j = 0; // Pointers for arr1[] and arr2[] int m1 = -1, m2 = -1; // Variables to store middle elements
// Traverse until we reach the middle of the merged
// array
for (int count = 0; count <= n; count++) {
// If arr1[] is exhausted, the middle elements are
// in arr2[]
if (i == n) {
m1 = m2;
m2 = arr2[0];
break;
}
// If arr2[] is exhausted, the middle elements are
// in arr1[]
else if (j == n) {
m1 = m2;
m2 = arr1[0];
break;
}
// Update m1 and m2 with the smaller current element
if (arr1[i] <= arr2[j]) {
m1 = m2;
m2 = arr1[i];
i++;
}
else {
m1 = m2;
m2 = arr2[j];
j++;
}
}
// Return the sum of the middle elements
return m1 + m2;}
int main() { int arr1[] = { 1, 2, 4, 6, 10 }; int arr2[] = { 4, 5, 6, 9, 12 }; int n = sizeof(arr1) / sizeof(arr1[0]);
// Function call to find the sum of the middle elements
cout << findMidSum(arr1, arr2, n) << endl;
return 0;}
Java
public class FindMiddleSum {
public static int findMidSum(int[] arr1, int[] arr2,
int n)
{
int i = 0, j = 0;
int m1 = -1, m2 = -1;
// Iterate until we reach the middle of the merged
// array
for (int count = 0; count <= n; count++) {
// If arr1[] is exhausted, the middle elements
// are in arr2[]
if (i == n) {
m1 = m2;
m2 = arr2[0];
break;
}
// If arr2[] is exhausted, the middle elements
// are in arr1[]
else if (j == n) {
m1 = m2;
m2 = arr1[0];
break;
}
// Update m1 and m2 with the smaller current
// element
if (arr1[i] <= arr2[j]) {
m1 = m2;
m2 = arr1[i];
i++;
}
else {
m1 = m2;
m2 = arr2[j];
j++;
}
}
// Return the sum of the middle elements
return m1 + m2;
}
public static void main(String[] args)
{
int[] arr1 = { 1, 2, 4, 6, 10 };
int[] arr2 = { 4, 5, 6, 9, 12 };
int n = arr1.length;
int midSum = findMidSum(arr1, arr2, n);
System.out.println(midSum);
}}
Python
def find_mid_sum(arr1, arr2, n):
i, j = 0, 0
m1, m2 = -1, -1
# Iterate until we reach the middle of the merged array
for count in range(n + 1):
# If arr1[] is exhausted, the middle elements are in arr2[]
if i == n:
m1 = m2
m2 = arr2[0]
break
# If arr2[] is exhausted, the middle elements are in arr1[]
elif j == n:
m1 = m2
m2 = arr1[0]
break
# Update m1 and m2 with the smaller current element
if arr1[i] <= arr2[j]:
m1 = m2
m2 = arr1[i]
i += 1
else:
m1 = m2
m2 = arr2[j]
j += 1
# Return the sum of the middle elements
return m1 + m2arr1 = [1, 2, 4, 6, 10] arr2 = [4, 5, 6, 9, 12] n = len(arr1)
mid_sum = find_mid_sum(arr1, arr2, n) print(mid_sum)
C#
using System;
public class FindMiddleSum { public static int FindMidSum(int[] arr1, int[] arr2, int n) { int i = 0, j = 0; int m1 = -1, m2 = -1;
// Iterate until we reach the middle of the merged
// array
for (int count = 0; count <= n; count++) {
// If arr1[] is exhausted, the middle elements
// are in arr2[]
if (i == n) {
m1 = m2;
m2 = arr2[0];
break;
}
// If arr2[] is exhausted, the middle elements
// are in arr1[]
else if (j == n) {
m1 = m2;
m2 = arr1[0];
break;
}
// Update m1 and m2 with the smaller current
// element
if (arr1[i] <= arr2[j]) {
m1 = m2;
m2 = arr1[i];
i++;
}
else {
m1 = m2;
m2 = arr2[j];
j++;
}
}
// Return the sum of the middle elements
return m1 + m2;
}
public static void Main(string[] args)
{
int[] arr1 = { 1, 2, 4, 6, 10 };
int[] arr2 = { 4, 5, 6, 9, 12 };
int n = arr1.Length;
int midSum = FindMidSum(arr1, arr2, n);
Console.WriteLine(midSum);
}}
JavaScript
function findMidSum(arr1, arr2, n) {
let i = 0, j = 0; let m1 = -1, m2 = -1;
// Iterate until we reach the middle of the merged array for (let count = 0; count <= n; count++) { // If arr1[] is exhausted, the middle elements are in arr2[] if (i === n) { m1 = m2; m2 = arr2[0]; break; } else if (j === n) { m1 = m2; m2 = arr1[0]; break; }
// Update m1 and m2 with the smaller current element
if (arr1[i] <= arr2[j]) {
m1 = m2;
m2 = arr1[i];
i++;
} else {
m1 = m2;
m2 = arr2[j];
j++;
}}
// Return the sum of the middle elements return m1 + m2; }
const arr1 = [1, 2, 4, 6, 10]; const arr2 = [4, 5, 6, 9, 12]; const n = arr1.length;
const midSum = findMidSum(arr1, arr2, n); console.log(midSum);
`
**Time Complexity: O(n)
**Auxiliary Space: O(1), Since we have used count, m1 and m2 to keep track of the middle elements
**[Expected Approach] Using Binary search - O(log(n)) time and O(1) auxiliary space
**Prerequisite: Median of two sorted array
The most efficient approach use binary search to find the correct partition point in one of the arrays, this ensuring the two halves contain the middle elements. By setting initial search range pointers **low and **high, we use binary search to find the partition **cut1 in arr1[] and **cut2 in **arr2[]. We then check if the largest elements of the **left partitions and the smallest elements of the **right partitions form a valid split. If not, we adjust the search range accordingly. Once the partitions are valid, the middle elements are determined by the maximum of the **left partition elements and the minimum of the **right partition elements.
**Detailed Intuition:
- **Initialize Search Range: Set **low = 0 and high = N to define the search range within **arr1[].
- **Binary Search Partition: Use binary search to find the partition point **cut1 in **arr1[].
- Calculate the corresponding partition point **cut2 in arr2[].
- **Determine Partition Validity:
- Define **l1 as the largest element on the left side of **arr1[] partition, and **l2 as the largest element on the left side of **arr2[] partition.
- Define **r1 as the smallest element on the right side of **arr1[] partition, and **r2 as the smallest element on the right side of **arr2[] partition.
- **Adjust Search Range: Check if the partitions are valid:
- If **l1 <= r2 and l2 <= r1, the partitions are valid.
- If **l1 > r2, adjust the search range to **high = cut1 - 1.
- If **l2 > r1, adjust the search range to **low = cut1 + 1.
- **Find Middle Elements: Once the partitions are valid, the middle elements are **max(l1, l2) and **min(r1, r2). Sum these elements to get the result.
C++ `
#include <bits/stdc++.h> using namespace std;
// Function to find the sum of the middle elements using binary search int findMidSum(int arr1[], int arr2[], int n) { int low = 0, high = n;
while (low <= high) {
// Partition points in both arrays
int cut1 = (low + high) / 2;
int cut2 = n - cut1;
// Elements around the partition points
int l1 = (cut1 == 0) ? INT_MIN : arr1[cut1 - 1];
int l2 = (cut2 == 0) ? INT_MIN : arr2[cut2 - 1];
int r1 = (cut1 == n) ? INT_MAX : arr1[cut1];
int r2 = (cut2 == n) ? INT_MAX : arr2[cut2];
// Check if we have found the correct partition
if (l1 <= r2 && l2 <= r1) {
// Return the sum of the middle elements
return max(l1, l2) + min(r1, r2);
} else if (l1 > r2) {
high = cut1 - 1;
} else {
low = cut1 + 1;
}
}
// This case will never occur for valid input
return 0;}
// Driver code int main() { int arr1[] = {1, 2, 4, 6, 10}; int arr2[] = {4, 5, 6, 9, 12 }; int n = sizeof(arr1) / sizeof(arr1[0]);
// Function call to find the sum of the middle elements
cout << findMidSum(arr1, arr2, n) << endl;
return 0;}
Java
public class FindMidSum {
public static int findMidSum(int[] arr1, int[] arr2,
int n)
{
int low = 0, high = n;
while (low <= high) {
// Calculate the partition points in both
// arrays.
int cut1 = (low + high) / 2;
int cut2 = n - cut1;
// Get the elements around the partition points.
int l1 = (cut1 == 0) ? Integer.MIN_VALUE
: arr1[cut1 - 1];
int l2 = (cut2 == 0) ? Integer.MIN_VALUE
: arr2[cut2 - 1];
int r1 = (cut1 == n) ? Integer.MAX_VALUE
: arr1[cut1];
int r2 = (cut2 == n) ? Integer.MAX_VALUE
: arr2[cut2];
// Check if the partition is correct.
if (l1 <= r2 && l2 <= r1) {
// Return the sum of the middle elements.
return Math.max(l1, l2) + Math.min(r1, r2);
}
else if (l1 > r2) {
// Move the high pointer to the left.
high = cut1 - 1;
}
else {
// Move the low pointer to the right.
low = cut1 + 1;
}
}
// This case will never occur for valid input.
return 0;
}
public static void main(String[] args)
{
int[] arr1 = { 1, 2, 4, 6, 10 };
int[] arr2 = { 4, 5, 6, 9, 12 };
int n = arr1.length;
System.out.println(findMidSum(arr1, arr2, n));
}}
Python
def find_mid_sum(arr1, arr2, n):
low = 0
high = n
while low <= high:
# Calculate the partition points in both arrays.
cut1 = (low + high) // 2
cut2 = n - cut1
# Get the elements around the partition points.
l1 = arr1[cut1 - 1] if cut1 > 0 else float('-inf')
l2 = arr2[cut2 - 1] if cut2 > 0 else float('-inf')
r1 = arr1[cut1] if cut1 < n else float('inf')
r2 = arr2[cut2] if cut2 < n else float('inf')
# Check if the partition is correct.
if l1 <= r2 and l2 <= r1:
# Return the sum of the middle elements.
return max(l1, l2) + min(r1, r2)
elif l1 > r2:
# Move the high pointer to the left.
high = cut1 - 1
else:
# Move the low pointer to the right.
low = cut1 + 1
return 0 # This case will never occur for valid inputDriver code
arr1 = [1, 2, 4, 6, 10] arr2 = [4, 5, 6, 9, 12] n = len(arr1)
print(find_mid_sum(arr1, arr2, n))
JavaScript
function findMidSum(arr1, arr2, n) {
let low = 0; let high = n;
while (low <= high) { // Calculate the partition points in both arrays. const cut1 = Math.floor((low + high) / 2); const cut2 = n - cut1;
// Get the elements around the partition points.
const l1 = cut1 > 0 ? arr1[cut1 - 1] : Number.MIN_VALUE;
const l2 = cut2 > 0 ? arr2[cut2 - 1] : Number.MIN_VALUE;
const r1 = cut1 < n ? arr1[cut1] : Number.MAX_VALUE;
const r2 = cut2 < n ? arr2[cut2] : Number.MAX_VALUE;
// Check if the partition is correct.
if (l1 <= r2 && l2 <= r1) {
// Return the sum of the middle elements.
return Math.max(l1, l2) + Math.min(r1, r2);
} else if (l1 > r2) {
// Move the high pointer to the left.
high = cut1 - 1;
} else {
// Move the low pointer to the right.
low = cut1 + 1;
}}
return 0; // This case will never occur for valid input }
// Driver code const arr1 = [1, 2, 4, 6, 10]; const arr2 = [4, 5, 6, 9, 12]; const n = arr1.length;
console.log(findMidSum(arr1, arr2, n));
`