Median of two sorted arrays. Extremely legible solution. LeetCode#4

Guadalupe Island -White Shark Diving Trip Sept 2018. Not relevant at all.

So, this ones gonna be short, Median of two sorted arrays is LeetCode problem number 4 and has a difficulty rating of hard (and its probably one of the easiest questions I've solved on the platform.)

Ok… Problem — Write a function that takes in two sorted arrays and returns the median number. It's really that simple.

Stop, right now, go solve it if you think you can.. come back if you're having issues; this problem is a huge confidence booster (maybe not if you arent following yet)

To the solution break down…

Light-Themed IDE to show that I’m a psychopath

Ok, so we have a function with two parameters (nums1, nums2).

When we get into our code block the first thing we are doing is reassigning our nums1 variable to a new array with both inputs spread to create one flat array with all values.

To save space because why not (I was playing around with a few things when writing the Algo if you can't tell.) after we create our new array, we are going to use the “Array-baked-in” sort() method. This method expects a function that will take in two parameters and does a Browser-Dependent-Sort (Merge Sort for Mozilla, Quick, or Insertion for Chrome)and returns an array in ascending or descending order... For example,

The next step in the algorithm is array length-dependent because of how division when finding the center of an array and how we determine the median.

If the array is even, meaning there is no center index, we will need to figure out the difference between the “left-middle” and “right-middle” elements. Once we have the difference we add that to the left-middle index of the array to return the median.

Else, we just return the center of our sorted array…

Wallah, that is that.

Surely, LeetCode’s easiest “Hard” problem.

If you have a better solution or solved the problem differently, please comment below or message me on LinkedIn



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store