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.
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
ntiny 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.
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.
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:
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
nis 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
nis zero or negative, return an empty result. - If
nis 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
ncostsO(m log n)time andO(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
nis small. - A min-heap of size
ngives an efficientO(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
- Finding the first non-repeated character of a string in On using a boolean array?
- Finding the furthest point in a grid when compared to other points
- Finding the hundred largest numbers in a file of a billion
- Finding the index of a given permutation
- Finding the first UIP in an inference graph
- Finding the index of elements based on a condition using python list comprehension
- Finding the intersecting node from two intersecting linked lists
- Finding the kth quantiles of an n-elements set. From cormen

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