Solution: Find K Largest Elements in an Array

Let’s solve the Find K Largest Elements in an Array problem.

Statement

Given an array of integers, nums, and a positive integer, k, find the k largest elements in the array.

Constraints:

  • 11 \leq k \leq nums.length 103\leq 10^3

  • 104-10^4 \leq nums[i] 104\leq 10^4

Solution 1: Utilizing sort

In this solution, we sort the given array of numbers in descending order, meaning the largest numbers come first. Then, we select the first k elements from the sorted array, which are the k largest elements in the original array, and return them.

Let’s look at how the implementation of the algorithm works:

  • The nums undergoes sorting in descending order utilizing the sort method with the greater<int>() parameter.

  • Using a for loop first k elements are retrieved from the sorted array.

  • These first k elements, now representing the largest values, are returned as the output.

Level up your interview prep. Join Educative to access 80+ hands-on prep courses.