Skip to main content

Leetcode 4: Median of Two Sorted Arrays


1. Problem Statement (Simple Explanation)


You are given two sorted arrays:

  • nums1 of size m

  • nums2 of size n

You need to return the median of the combined data if both arrays were merged into one sorted array.

Constraints:

  • Total length m + n >= 1

  • Arrays are individually sorted in non-decreasing order.

  • You must achieve overall time complexity:

O(log(m+n))

The median:

  • If total length is odd: middle element.

  • If total length is even: average of the two middle elements.


2. Examples


Example 1

Input: nums1 = [1,3], nums2 = [2]

Output: 2.00000

Explanation: Merged array: [1, 2, 3] and Median = 2


Example 2

Input: nums1 = [1,2], nums2 = [3,4]

Output: 2.50000

Explanation: Merged array: [1, 2, 3, 4] and Median =2+32=2.5


3. Approach 1 – Merge and Find Median (Basic, O(m+n))


Intuition


Simulate the merging step of merge sort:

  • Merge nums1 and nums2 into a single sorted array (or at least until we reach the median position).

  • Compute the median from the merged data.

This is simple but runs in:

O(m+n)

which does not meet the required O(log(m+n)) constraint, but is a good starting explanation for beginners.


Algorithm (Step-by-Step)


  1. Let m = len(nums1), n = len(nums2), total = m + n.

  2. Use two pointers i = 0 (for nums1), j = 0 (for nums2).

  3. Option A (fully merge):

    • Create a new array merged, and push the smaller of nums1[i] and nums2[j] each step.

    • After merging, if total is odd, return merged[total // 2]; else average merged[total // 2 - 1] and merged[total // 2].

  4. Option B (partial merge, more space efficient):

    • We only need elements up to the middle indices.

    • Maintain two variables, prev and curr, updated each step until we reach the median position.


Pseudo-code (Partial Merge)


Complexity

  • Time: O(m+n)

  • Space: O(1) extra (with partial merge)

Good for understanding, but not optimal per problem requirement.


4. Approach 2 – Binary Search on Partition (Optimal, O(log(min(m, n))))


This is the standard interview solution.


Key Idea (Partition-Based)


We conceptually partition the combined sorted array into left and right halves such that:

  • All elements on the left side are <= all elements on the right side.

  • The left and right halves differ in size by at most 1.

We don’t actually merge, we just find such a partition by using binary search on one array.

We choose nums1 to be the shorter array (swap if needed).
We perform binary search on nums1's partition index i, and derive j for nums2.

Let:

  • m = len(nums1), n = len(nums2) and assume m <= n.

  • total = m + n.

  • half = (total + 1) // 2 → number of elements that should be on the left side combined.

We choose some i from 0 to m, and then:

                                                        j=half-i

So:

  • Left side = nums1[0..i-1] and nums2[0..j-1]

  • Right side = nums1[i..m-1] and nums2[j..n-1]

We want the partition to be valid:

  1. All elements on left ≤ all elements on right:

    • nums1[i-1] <= nums2[j] (if i > 0 and j < n)

    • nums2[j-1] <= nums1[i] (if j > 0 and i < m)

  2. Once we have a valid partition:

    • If total is odd: median is max(left parts)

    • If total is even: median is average of max(left parts) and min(right parts)

We adjust i using binary search:

  • If nums1[i-1] > nums2[j] → i is too big → move left.

  • Else if nums2[j-1] > nums1[i] → i is too small → move right.

  • Else → perfect partition.

To avoid index problems at borders, we treat out-of-bounds as ±∞, e.g.:

  • If i == 0, then left1 = -∞ (no element)

  • If i == m, then right1 = +∞

  • Similarly for j.


Pseudo-code (Binary Search on Shorter Array)



Complexity

We binary-search only on the shorter array:

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

  • Space: O(1)

Meets the required O(log(m+n)).


5. Java code



6. C code



7. C++ code



8. Python code



9. JavaScript




Comments

Popular posts from this blog

Leetcode 1: Two Sum

  Leetcode Link: https://leetcode.com/problems/two-sum/ 1. Problem Statement (Simple Explanation) You are given: An array of integers nums An integer target You need to  return the indices of two numbers in the array  such that: Conditions: Each input has  exactly one solution . You  cannot use the same element twice . You can return the answer in  any order . 2. Examples Example 1 Input:                                    nums = [2, 7, 11, 15], target = 9 Output:                                 [0, 1] Explanation:                     nums[0]+nums[1]=2+7=9              So we return [0, 1]. Example 2 Input:           ...

Leetcode 3: Longest Substring Without Repeating Characters

  Leetcode Link 1. Problem Statement (Simple Explanation) You are given a string s. You need to find the length of the longest substring of s that does not  contain any repeated characters. A substring is a contiguous sequence of characters in the string. You must return an integer length, not the substring itself. 2. Examples Example 1 Input: s = "abcabcbb" Output: 3 Explanation: Some substrings without repeating characters: "abc", "bca", "cab"The longest length is 3. Example 2 Input: s = "bbbbb" Output: 1 Explanation: All substrings that are valid are just "b". The longest length is 1. Example 3 Input:   s = "pwwkew" Output:   3 Explanation: Possible substrings without repetition: "pw", "wke", "kew". "wke" or "kew" have length 3. "pwke" is not valid because it’s not contiguous in the original string (p and k are separated by ww). Constraints...

Leetcode 2: Add Two Numbers

Leetcode Link: https://leetcode.com/problems/add-two-numbers/ 1. Problem Statement (Simple Explanation) You are given  two non-empty linked lists , l1 and l2, that represent two non-negative integers. Each node contains a  single digit . The digits are stored in  reverse order  (i.e., the 1’s digit is at the head). You need to  add the two numbers  and return the  sum as a linked list , also in reverse order. You can assume: There are  no leading zeros , except when the number itself is 0. 2. Examples Example 1 Input:                l1 = [2,4,3]                l2 = [5,6,4]           Interpreting linked lists as numbers (reverse order): l1 represents 342 l2 represents 465 Output:                [7,0,8] Explanation:        ...