LeetCode- 215. Kth Largest Element in an Array | C++ STL

Explanation and Code.

Purushottam Banerjee
ALgo 101
3 min readJan 9, 2022

--

Problem Statement:

Given an integer array nums and an integer k, return the kth largest element in the array.
Note that it is the kth largest element in the sorted order, not the kth Distinct element.

Check out the Problem → Question
Full Code → Git

Example:

Approach:

First, let’s discuss how, in general, we can get the Kth MAX number in any Array.

Brute Force:

The most brute approach will be finding all max numbers and removing them from the array until we find the K th Max.

Ex- for 3rd largest
[10,20,50,30,90,40] — MAX 1-90 (remove)
[10,20,50,30,40] — MAX 2-50 (remove)
[10,20,30,40] — MAX 3-40 (remove)

Hence we find our 3rd Max that is 40.

Time Complexity :

For Searching Max each time it will be dependent on Array size.
For an Array of N Size.
Time taken will be for:
1st Iteration as N
2nd Iteration as N-1
and so on….

N+N-1+N-2……+1 = (N²+ N)/2

This gives us a Time Complexity of order (N²) which is not a very optimal solution.

Optimized Solution:

A good way to approach the problem will be using the Partitioning concept.

Partition Concept is used in Quick Sort, Where we Divide an Array-based on a pivot that we choose arbitrarily.

You can take a closer look at Quick Sort in this article.

In Brief, In Partition Technique we pick a pivot element, then move the pivot element to its correct position and partition the surrounding array. The idea is, not to do complete quicksort, but stop at the point where the pivot itself is k’th smallest element.

CODE :

Competetive Code

There are many other ways to complete this in a few lines with advanced DS such as Maps and Sets.

With C++ you can use the sort function as well.

An implementation that can help to solve in a few lines:

with Sort():

Other than this you can use MinHeap, Priority Queue as well

If you have any suggestions please feel free to connect with us or comment with your thoughts.

Happy Coding.

--

--

ALgo 101
ALgo 101

Published in ALgo 101

Solutions and explanation for questions featured in various platforms such as HackerEarth, Leet Code and Feed back from Coding Interviews

Purushottam Banerjee
Purushottam Banerjee

Written by Purushottam Banerjee

Software Engineer| Film enthusiast| Story Teller || Wants to make the world better.