Skip to content

Edvins Antonovs

Find the Median code challenge

My approach to solving HackerRank’s Find the Median code challenge.


Problem

The median of a list of numbers is essentially its middle element after sorting. The same number of elements occur after it as before. Given a list of numbers with an odd number of elements, find the median?

Example

arr = [5, 3, 1, 2, 4]

The sorted array arr = [1, 2, 3, 4, 5]. The middle element and the median is 3.

Input format

The first line contains the integer n, the size of arr.

The second line contains n space-separated integers arr[i].

Returns

int: the median of the array.

Sample input

17
20 1 2 4 6 5 3

Sample output

13

Solution

We start by sorting our given array in ascending order and saving the results as a sorted array (strArr) variable.

After that, we find the array's middle point by dividing the array's length by 2 and using Math.floor() to round up the number.

Then we check to see if the array's length is even or odd and return the results based on the evaluation.

1function findMedian(arr) {
2 const srtArr = arr.sort((a, b) => a - b);
3 const mid = Math.floor(srtArr.length / 2);
4
5 if (srtArr.length % 2 === 0) {
6 return (srtArr[mid - 1] + srtArr[mid]) / 2;
7 }
8
9 return srtArr[mid];
10}

Appendix

Subscribe to the newsletter

Get emails from me about web development, tech and entrepreneurship.

© 2022 by Edvins Antonovs. All rights reserved.