702760. Sum of Middle elements of two sorted arrays

Medium

Sum of Middle elements of two sorted arrays

Summary

Given two sorted arrays, find the sum of their middle elements. If one array has an even length and the other has an odd length, consider the average of the middle elements in the longer array.

This problem involves arrays, divide and conquer, and binary search concepts.

Detailed Explanation

The approach to this problem is to use a combination of divide and conquer along with binary search. First, find the middle index of both arrays. Then, perform a binary search on one array to find the closest element to the middle index in that array. Repeat the process for the other array.

Here's a step-by-step breakdown:

  1. Calculate the middle indices of both arrays.
  2. Perform a binary search on the first array to find the closest element to the middle index.
  3. Perform a similar binary search on the second array to find the closest element to the middle index.
  4. Add the two found elements together.

Here's an ASCII art diagram illustrating the process:

Array 1: [1, 2, 3, 4]
          ^

Middle index: 2
Binary search result: 3 (since 3 is closer to 2 than 1 or 4)

Array 2: [5, 6, 7, 8, 9]
          ^

Middle index: 3
Binary search result: 7 (since 7 is closer to 3 than 5, 6, 8, or 9)

Time complexity: O(log(m) + log(n)) where m and n are the lengths of the two arrays. Space complexity: O(1)

Optimized Solutions

Java

View on GeeksforGeeks
public int sumMiddleElements(int[] arr1, int[] arr2) {
    int mid1 = arr1.length / 2;
    int mid2 = arr2.length / 2;

    int left1 = binarySearch(arr1, mid1);
    int right1 = binarySearch(arr1, mid1 + 1);

    int left2 = binarySearch(arr2, mid2);
    int right2 = binarySearch(arr2, mid2 + 1);

    return Math.max(left1, right1) + Math.max(left2, right2);
}

private int binarySearch(int[] arr, int target) {
    int low = 0;
    int high = arr.length - 1;

    while (low <= high) {
        int mid = low + (high - low) / 2;

        if (arr[mid] == target) {
            return mid;
        } else if (arr[mid] < target) {
            low = mid + 1;
        } else {
            high = mid - 1;
        }
    }

    return Math.min(low, high);
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.