Sum of middle elements of two sorted Arrays
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 + m2
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)
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 input
# Driver 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));
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem