Median of two sorted arrays. Extremely legible solution. LeetCode#4
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…
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.
let nums1 = [1,3]
let nums2 = [2,4]
nums1 = [...nums1,...nums2]// nums1 = [1,3,2,4]
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,
this will order the array from least to greatest (a,b)=> a-b
this will order the array from greatest to least(a,b)=> b-ayou can check out my Merge Sort Article for the verbouse explanation of sorting
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 @www.linkedIn.com/in/adanieljohnson