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
3mo
arr.sort((a,b) => a-b).slice(arr.length - value, arr.length)
Help your peers!
Add answer anonymously...
Persistent Systems Senior Software Engineer interview questions & answers
A Senior Software Engineer was asked 9mo agoQ. Given a sorted array of integers nums and an integer target, write an algorithm ...read more
A Senior Software Engineer was asked 10mo agoQ. What is SDLC? What are its uses?
A Senior Software Engineer was asked 11mo agoQ. What is a state file?
Popular interview questions of Senior Software Engineer
A Senior Software Engineer was asked 9mo agoQ1. Given a sorted array of integers nums and an integer target, write an algorithm ...read more
A Senior Software Engineer was asked 11mo agoQ2. What is SDLC? What are its uses?
A Senior Software Engineer was asked 11mo agoQ3. What is a state file?
>
Persistent Systems Senior Software Engineer Interview 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

