Problem solution · C++

Median of Two Sorted Arrays

Median of Two Sorted Arrays: a C++ solution using sliding window or two pointers. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Sliding window or two pointers
Source
walkccc LeetCode Solutions
Length
32 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Sliding window or two pointers

For Median of Two Sorted Arrays, the implementation maintains a moving interval and updates only the information that enters or leaves the window.

  1. Choose the invariant that makes a window valid or useful.
  2. Advance the right boundary and add the new element.
  3. Move the left boundary only as needed while maintaining the invariant and updating the answer.

Code notes

  • 32 lines of C++ from the credited upstream file 4.cpp.
  • The implementation visibly relies on sequence storage.
  • 1 loop block detected.

Complexity

Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeMedian of Two Sorted Arrays · C++C++
Use this to learn the idea, then write your own version.
class Solution { public:  double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {    const int n1 = nums1.size();    const int n2 = nums2.size();    if (n1 > n2)      return findMedianSortedArrays(nums2, nums1);     int l = 0;    int r = n1;     while (l <= r) {      const int partition1 = (l + r) / 2;      const int partition2 = (n1 + n2 + 1) / 2 - partition1;      const int maxLeft1 = partition1 == 0 ? INT_MIN : nums1[partition1 - 1];      const int maxLeft2 = partition2 == 0 ? INT_MIN : nums2[partition2 - 1];      const int minRight1 = partition1 == n1 ? INT_MAX : nums1[partition1];      const int minRight2 = partition2 == n2 ? INT_MAX : nums2[partition2];      if (maxLeft1 <= minRight2 && maxLeft2 <= minRight1)        return (n1 + n2) % 2 == 0                   ? (max(maxLeft1, maxLeft2) + min(minRight1, minRight2)) * 0.5                   : max(maxLeft1, maxLeft2);      else if (maxLeft1 > minRight2)        r = partition1 - 1;      else        l = partition1 + 1;    }     throw;  }}; 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗