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.
Anonymous
4mo
arr.sort((a,b) => a-b).slice(arr.length - value, arr.length)
Help your peers!
Add answer anonymously...
Top Senior Software Engineer Interview Questions Asked at Persistent Systems
Q. Given a sorted array of integers nums and an integer target, write an algorithm ...read more
Q. What is SDLC? What are its uses?
Q. Given an array nums, write a function to move all 0's to the end of it while mai...read more
Interview Questions Asked to Senior Software Engineer at Other Companies
Top Skill-Based Questions for Persistent Systems Senior Software Engineer
Web Development Interview Questions and Answers
250 Questions
Data Structures Interview Questions and Answers
250 Questions
Java Interview Questions and Answers
250 Questions
Algorithms Interview Questions and Answers
250 Questions
Software Development Interview Questions and Answers
250 Questions
SQL Interview Questions and Answers
250 Questions
Stay ahead in your career. Get AmbitionBox app


Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+
Reviews
10L+
Interviews
4 Cr+
Salaries
1.5 Cr+
Users
Contribute to help millions
AmbitionBox Awards
Get AmbitionBox app

