![]() |
VOOZH | about |
Given a Linked list of integers, the task is to find N largest elements in the Linked List.
Examples:
Input: [4, 5, 1, 2, 9], N = 2
Output: [9, 5]Input: [81, 52, 45, 10, 3, 2, 96], N = 3
Output: [ 96, 81, 52]
Approach: To solve the problem follow the below idea:
The idea is to Sort the Linked list using any sorting method and then traverse the list up to N
Follow the steps to solve the problem:
Below is the implementation for the above approach:
9 5
Time complexity: O(N2)
Auxiliary space: O(1)
Store the elements of the linked list in a priority queue (max heap). Pop out the elements from the heap till N becomes 0 and add it to an array. Return the array as our answer.
Output: 96 81 52
Time Complexity: O(N*logN). To insert elements into the max-heap, it takes logN time. We insert N elements from the linked list to the heap, hence the overall time complexity is O(N*logN).
Space Complexity: O(N). We create a max-heap data structure due to which it requires O(N) space.