Image for post

If you are actively interviewing with companies, this is probably one of the most common problems out there. You can probably find this problem on leetcode, hackerrank and other websites with interview preparation.

To understand how to solve this problem, reading my article about quicksort would be helpful:

Explanation of Quick Sort

Alright, I know you probably don’t even understand why quick sort plays into this picture but I will explain in a minute.

So what do we mean by finding the kth largest/smallest element in the array?

It means that with a given array(sorted or unsorted) I want to find 1st or 2nd largest/smallest element in the array, if k is 1 or 2.

For example, let’s say there is an array with the following values: [5,4,7,1,2,3,6]. If k is 2 then I will get the value of 2 because it is the 2nd smallest element. It would have been 6 if I was getting the 2nd largest element.

Generally, there are a few ways to solve this:

  • Sort the array and return the element by indicing the array via k(arr[k])
  • using min/maximum heap to find the kth element
  • using quick select/partial quick sort to solve the problem.

Let’s start off by using a default array to solve the problem:

const getKthSmallest = (arr, k) => {
	  arr.sort(arr);
	  return arr[k - 1];
	}

	const arr = [8,2,3,4,1,7];
	console.log(getKthSmallest(arr,5)); //will return 7

#algorithms #javascript #web-development #es6 #coding #array

How to find kth largest/smallest element in an array
3.95 GEEK