n-largest elements in a sequence need to retain duplicates
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
If you need the n largest elements from a sequence and duplicates must count as separate entries, the problem is simpler than it first sounds. Most standard sorting and heap-based approaches already retain duplicates naturally unless you accidentally convert the data into a set somewhere in the process.
Full Sort Is the Simplest Approach
For small and medium inputs, the clearest solution is to sort in descending order and take the first n items.
Duplicates are preserved automatically because sorting does not remove anything. It only reorders the original values.
Use heapq.nlargest for Large Inputs
If the input is large and n is much smaller than the total sequence length, heapq.nlargest is often a better fit.
This function also keeps duplicates. It returns the n largest elements, not the n largest distinct values.
That distinction is the entire point of the question: if the sequence contains the same large number several times, each occurrence should remain eligible.
Understand the Complexity Tradeoff
Choose the method based on input size:
- '
sorted(values, reverse=True)[:n]is simple and good when sorting the entire list is acceptable' - '
heapq.nlargest(n, values)is usually better whennis small relative to the full sequence'
The sorted version is often easier to read. The heap version is more efficient in the common top-k scenario.
Getting Indices as Well as Values
Sometimes the real requirement is not only the top values, but also where they came from. In that case, pair each item with its index before selecting the largest entries.
Now duplicates are still preserved, but you also know which occurrence each selected value came from.
The Main Mistake: Deduplicating by Accident
Many incorrect solutions introduce set(values) or otherwise group equal values before selection. That changes the problem completely.
For example, this is wrong if duplicates must be retained:
That produces the largest distinct values, not the largest n elements with multiplicity.
This is one of those cases where the algorithm is not hard, but the problem statement must be read precisely.
Streaming Scenarios
If values arrive over time and you cannot hold everything in memory, maintain a min-heap of size n. Each incoming value is compared against the smallest retained value.
That streaming pattern still preserves duplicates as long as you store each item individually. You do not need special duplicate logic. You only need to avoid collapsing equal values into one record.
Common Pitfalls
- Converting the sequence to a set and accidentally removing duplicates.
- Solving for the largest distinct values when the requirement is the largest
nelements. - Sorting the whole sequence when
heapq.nlargestwould be more efficient for smalln. - Forgetting that ties should be kept as separate occurrences.
- Losing index information when the actual task needs both the values and their positions.
Summary
- Duplicates are preserved automatically by normal sorting and by
heapq.nlargest. - The simplest solution is descending sort plus slice.
- '
heapq.nlargestis better whennis small compared with the full sequence.' - Avoid
setor any deduplication step if multiplicity matters. - If positions matter too, select from
enumerate(values)instead of from raw values alone.
Related reading
- n log n is On?
- n steps with 1, 2 or 3 steps taken. How many ways to get to the top?
- nᵗʰ ugly number
- Naive Bayes Imbalanced Test Dataset
- n-th or Arbitrary Combination of a Large Set
- Names of Graph Traversal Algorithms
- Naive Bayes without Naive assumption
- name of algorithm related to load balancing / re-distribution

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.