VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-n-largest-elements-from-a-linked-list/

⇱ find N largest elements from a Linked list - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

find N largest elements from a Linked list

Last Updated : 23 Jul, 2025

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]

Method 1 : Brute Force

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:

  • Sort the given list using bubble sort.
  • Traverse the list up to N values
  • Print the values.

Below is the implementation for the above approach:


Output
9 5 

Time complexity: O(N2)
Auxiliary space: O(1)


Method 2: Max Heap

Intuition

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.

Algorithm

  1. Create a max heap (priority queue) to store the elements of the linked list.
  2. Iterate through the linked list from head to end.
  3. For each element, insert the data into the heap.
  4. Initialize an empty vector to store our answer.
  5. Pop out N elements from the max-heap and add it to the vector or array.
  6. Return the array and print the answer.

Code


Output
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.



Comment
Article Tags: