n-largest elements
sequences
duplicate elements
data structures
algorithms

n-largest elements in a sequence need to retain duplicates

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

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.

python
1values = [5, 1, 3, 3, 5, 2, 4]
2n = 4
3
4result = sorted(values, reverse=True)[:n]
5print(result)
text
[5, 5, 4, 3]

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.

python
1import heapq
2
3values = [5, 1, 3, 3, 5, 2, 4]
4n = 4
5
6result = heapq.nlargest(n, values)
7print(result)
text
[5, 5, 4, 3]

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 when n is 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.

python
1import heapq
2
3values = [5, 1, 3, 3, 5, 2, 4]
4n = 4
5
6result = heapq.nlargest(n, enumerate(values), key=lambda pair: pair[1])
7print(result)
text
[(0, 5), (4, 5), (6, 4), (2, 3)]

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:

python
result = sorted(set(values), reverse=True)[:n]

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 n elements.
  • Sorting the whole sequence when heapq.nlargest would be more efficient for small n.
  • 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.nlargest is better when n is small compared with the full sequence.'
  • Avoid set or any deduplication step if multiplicity matters.
  • If positions matter too, select from enumerate(values) instead of from raw values alone.

Course illustration
Course illustration

All Rights Reserved.