arrays
sorting
algorithms
data structures
programming

Finding the first n largest elements in an array

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

Finding the n largest elements in an array is a common selection problem. The best solution depends less on the syntax of your language and more on the relationship between n and the full array size.

Start with the Real Requirement

Before choosing an algorithm, clarify what “first n largest” means in your program:

  • Do you need the result sorted from largest to smallest?
  • Can you modify the original array?
  • Is n tiny compared with the array size?
  • Do duplicates count as separate elements?

Those details change which approach is best. If you only need a few largest values from a huge array, a full sort is often more work than necessary.

Full Sort Is the Simplest Option

The easiest method is to sort the whole array in descending order and then slice the first n elements.

python
1def largest_by_sort(values, n):
2    if n <= 0:
3        return []
4    return sorted(values, reverse=True)[:n]
5
6
7print(largest_by_sort([5, 1, 8, 3, 8, 2], 3))

This is easy to read and often perfectly fine for small or medium input sizes. The tradeoff is cost: sorting the full array takes O(m log m) time when the array length is m, even if you only want a handful of top values.

Heap-Based Selection Is Better When n Is Small

If the array is large and n is much smaller than the array length, a min-heap of size n is usually a better fit. In Python, heapq.nlargest already does this efficiently.

python
1import heapq
2
3
4def largest_by_heap(values, n):
5    if n <= 0:
6        return []
7    return heapq.nlargest(n, values)
8
9
10print(largest_by_heap([5, 1, 8, 3, 8, 2], 3))

The time complexity is O(m log n), which can be much better than sorting everything when n is small. That is why heap-based selection is a common answer in interviews and production code alike.

You can also write the heap logic manually to see what is happening:

python
1import heapq
2
3
4def largest_manual(values, n):
5    if n <= 0:
6        return []
7    if n >= len(values):
8        return sorted(values, reverse=True)
9
10    heap = values[:n]
11    heapq.heapify(heap)
12
13    for value in values[n:]:
14        if value > heap[0]:
15            heapq.heapreplace(heap, value)
16
17    return sorted(heap, reverse=True)

The heap stores only the current top n candidates. The smallest of those candidates stays at the heap root, so every new array element is easy to compare against the current cutoff.

Quickselect Is Useful for Selection Problems

Another family of solutions uses partitioning, similar to Quicksort. Quickselect finds the cutoff value in average O(m) time, then you take the elements above that cutoff and sort only the final answer if needed.

This approach is very strong when raw performance matters, but it is more complex to implement correctly than a heap. In many everyday programs, the extra complexity is not worth it unless arrays are very large or the operation is on a hot path.

A practical rule is:

  • Use full sort when clarity matters most.
  • Use a heap when n is small.
  • Consider Quickselect when selection speed is critical and you can tolerate more implementation complexity.

Handling Edge Cases Correctly

Good solutions also define behavior for awkward inputs:

  • If n is zero or negative, return an empty result.
  • If n is greater than the array length, return all elements in sorted order or document the chosen behavior.
  • If duplicates exist, decide whether repeated values should appear repeatedly in the output.

For example, the three largest elements in [9, 9, 7, 2] are usually [9, 9, 7], not [9, 7, 2]. That is a selection question, not a “distinct top values” question.

Complexity Comparison

Here is the main tradeoff table in words:

  • Sorting everything costs O(m log m) time and is easy to write.
  • A heap of size n costs O(m log n) time and O(n) extra space.
  • Quickselect is average O(m) time, but the implementation is less straightforward and worst-case behavior can be worse without careful pivot handling.

In languages that provide a tested helper such as heapq.nlargest, the heap option often gives the best balance of performance and maintainability.

Common Pitfalls

The most common mistake is sorting the entire array without thinking about whether n is small. That is acceptable sometimes, but not always the best choice.

Another pitfall is forgetting whether the output must be sorted. Some heap-based solutions return the correct n values but not in final descending order. If the caller expects sorted output, sort the heap result before returning it.

It is also easy to mishandle duplicates by accidentally converting the array to a set. That changes the problem from “largest elements” to “largest distinct elements,” which is not the same task.

Finally, be clear about whether the original array may be modified. In-place partitioning methods can be fast, but they are not appropriate if the caller expects the input order to remain intact.

Summary

  • Full sorting is the simplest solution, but it does more work than necessary when n is small.
  • A min-heap of size n gives an efficient O(m log n) solution for large arrays.
  • Quickselect is powerful, but it is usually worth using only when selection performance matters a lot.
  • Define edge-case behavior for n <= 0, n > len(array), and duplicate values.
  • Pick the algorithm based on actual requirements, not just on theoretical best-case complexity.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.