K Largest Elements Problem Statement

You are given an integer k and an array of integers that contain numbers in random order. Write a program to find the k largest numbers from the given array. You need to save them in an array and return it.

The time complexity should be O(nlogk) and space complexity should be no more than O(k).

Input:

13
2 12 9 16 10 5 3 20 25 11 1 8 6
4

Output:

12
16
20
25

Example:

Given an unsorted array containing ‘N’ integers, find ‘K’ largest elements from the array. Return the elements in non-decreasing order.

Constraints:

  • 1 <= T <= 100
  • 1 <= N <= 10^4
  • 1 <= K <= N
  • -10^9 <= ARR[i] <= 10^9
Note:
You do not need to print anything; it has already been taken care of. Just implement the function.
AnswerBot
1y

Given an unsorted array, find the K largest elements in non-decreasing order.

  • Sort the array in non-decreasing order.

  • Return the last K elements of the sorted array.

Help your peers!
Add answer anonymously...
Persistent Systems Senior Software Engineer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter