Finding the Median of Two Sorted Arrays with JavaScript

Hero image for Finding the Median of Two Sorted Arrays with JavaScript. Image by charlesdeluvio.
Hero image for 'Finding the Median of Two Sorted Arrays with JavaScript.' Image by charlesdeluvio.

The problem "Find the median of two sorted arrays" is a classic computing problem, often encountered in interviews and coding challenge platforms. It requires merging two sorted arrays of numbers and determining their median value. This is a problem that tests a developer's ability to deal with array manipulations alongside potential edge cases.


Problem Description

Given two sorted arrays, nums1 and nums2, find the median of the combined array.

Example

// Input:nums1 = [1, 3];nums2 = [2];// Output: 2.0// Input:nums1 = [1, 2];nums2 = [3, 4];// Output: 2.5// (Because there are an equal number of numbers, so we add the middle two: (2 + 3) / 2 = 2.5)

Solution Approach

  1. Merge the two arrays:

    Begin by merging the two sorted arrays to form a single sorted array.
  2. Find the median:

    • If the length of the merged array is odd, return the middle element.
    • If the length is even, return the average of the two middle elements.

Solving with JavaScript (TypeScript)

const findMedianSortedArrays = (nums1: number[], nums2: number[]): number => {  const merged = [...nums1, ...nums2].sort((a, b) => a - b);  const mid = Math.floor(merged.length / 2);  if (merged.length % 2 === 0) {    return (merged[mid - 1] + merged[mid]) / 2;  }  return merged[mid];};

Why is This Problem Important?

Whilst sometimes 'leet' developers can be accused of making up problems simply for the sake of their complexity, there are some real values in the Two Sorted Arrays problem, and seeing how a developer approaches a solution:

  • Fundamentals

    : It solidifies and demonstrates an understanding of arrays, sorting, and mathematical calculations.
  • Performance

    : Finding an efficient solution (beyond the one presented above) requires diving deep into the properties of sorted arrays, which can lead to O(log(min(m,n))) solutions using binary search.
  • Problemsolving skills:

    The problem presents an opportunity to think about edge cases, different data scenarios, and efficient algorithms.

The Wrap‑Up

Wrapping up, whilst the "Find the median of two sorted arrays" problem may seem straightforward at first glance, it offers a rich opportunity for deepening algorithmic understanding and honing problemsolving skills.


Categories:

  1. Algorithms
  2. Guides
  3. JavaScript
  4. LeetCode
  5. TypeScript