Top N Highest Numbers

Java coding interview problem for Java 8 Streams: Top N Highest Numbers.

Finding the Top N highest numbers is one of the most common algorithm and Java Collections interview problems.

Examples:

  • Find top 3 largest numbers from an array.
  • Find top 10 highest salaries.
  • Find top K transactions.
  • Find top rated products.

This problem introduces important concepts:

  • Sorting
  • Stream API
  • Comparator
  • PriorityQueue
  • Heap data structure
  • Time complexity optimization

What is Top N Problem?

The Top N problem means:

Find the N largest elements from a collection.


Example:

Input:

[10,40,20,90,50,70]

Requirement:

Top 3 highest numbers

Sorted order:

90

70

50

40

20

10

Output:

[90,70,50]

Understanding Ranking Problems

Ranking problems find elements based on their position.

Examples:

Highest value

Second highest value

Top 5 values

Bottom 10 values

Difference:

Maximum Problem

Find:

One highest element

Example:

100

Top N Problem

Find:

Multiple highest elements

Example:

100

90

80

Top 1 vs Top N

Example:

Numbers:

20,50,80,100

Top 1:

100

Top 3:

100

80

50

Top N requires maintaining multiple results.


Why Top N Problems Are Important?

Top N problems test:

1. Algorithm Selection

Choosing between:

Sorting

Heap

Streams

2. Performance Optimization

Comparing:

O(n log n)

vs

O(n log k)

3. Data Structure Knowledge

Understanding:

  • PriorityQueue
  • Heap
  • Comparator

Real-World Applications

Banking Systems

Find:

Top customers by account balance

E-Commerce

Find:

Top selling products

Analytics Systems

Find:

Top searched keywords

Monitoring Systems

Find:

Top error generating services

Employee Management

Find:

Top paid employees

Problem Statement

Given an integer array, find the top N highest numbers.


Example 1

Input:

[5,10,3,20,15]

N:

3

Output:

[20,15,10]

Example 2

Input:

[100,50,25,75]

N:

2

Output:

[100,75]

Finding Top N Concept

There are multiple approaches.


Approach 1

Sort complete collection.

Sort descending

        ↓

Take first N

Approach 2

Use Stream API.

sorted()

        ↓

limit()

Approach 3

Use Heap.

Maintain only N elements

Approach 1 — Sorting Entire Collection

The simplest solution.

Algorithm:

  1. Sort numbers descending.
  2. Pick first N elements.

Visualization

Input:

10 40 20 90 50

Sort:

90 50 40 20 10

Take first 3:

90 50 40

Java Program — Sorting Approach

import java.util.*;

public class TopNUsingSorting {


    public static List<Integer> findTopN(
            List<Integer> numbers,
            int n) {


        return numbers.stream()

                .sorted(
                    Comparator.reverseOrder()
                )

                .limit(n)

                .toList();

    }


    public static void main(String[] args) {


        List<Integer> numbers =
                Arrays.asList(
                    10,
                    40,
                    20,
                    90,
                    50
                );


        System.out.println(
            findTopN(numbers,3)
        );

    }

}

Output

[90,50,40]

Step-by-Step Explanation

Input:

[10,40,20,90,50]

Stream:

10

40

20

90

50

Sort descending:

90

50

40

20

10

Limit:

First 3 elements

Result:

90,50,40

Stream Pipeline

List

 ↓

stream()

 ↓

sorted(reverseOrder)

 ↓

limit(N)

 ↓

collect

Handling Duplicate Numbers

Example:

Input:

[10,20,20,30,30,40]

Top 3:

Normal sorting:

40,30,30

But sometimes requirement is:

Top 3 distinct numbers

Expected:

40,30,20

Using distinct()

numbers.stream()

.distinct()

.sorted(
    Comparator.reverseOrder()
)

.limit(3)

.toList();

Dry Run

Input:

[10,20,20,30,30,40]

Distinct:

10

20

30

40

Sort:

40

30

20

10

Limit:

40

30

20

Complexity Analysis — Sorting Approach

Sorting:

O(n log n)

Limit:

O(k)

where:

k = top elements required

Total:

O(n log n)

Space:

O(n)

because sorting requires storing elements.


Advantages

  • Simple implementation.
  • Easy to understand.
  • Good for small datasets.
  • Stream solution is readable.

Drawbacks

  • Sorts unnecessary elements.
  • Expensive for large datasets.
  • Does not optimize when N is small.

Example: Large Data Problem

Suppose:

1,000,000 numbers

Need:

Top 5

Sorting approach:

Sort:

1,000,000 elements

But we only need:

5 elements

Better approach:

PriorityQueue

Approach 2 — Stream sorted() Deep Dive

Java Stream sorting internally uses object sorting.

Example:

.sorted(
    Comparator.reverseOrder()
)

For numbers:

Ascending:

1,2,3,4

Descending:

4,3,2,1

Then:

.limit(n)

selects required elements.


Finding Top N With Integer Stream

Example:

List<Integer> result =

numbers.stream()

.sorted(
    Comparator.reverseOrder()
)

.limit(5)

.toList();

Handling Empty Collections

Input:

[]

Result:

[]

because:

limit()

returns available elements.


Handling N Greater Than Size

Input:

[10,20,30]

N:

10

Result:

[30,20,10]

No exception occurs.


Approach 3 — PriorityQueue (Min Heap) Approach

The sorting approach works well, but it sorts every element.

For large datasets, we can optimize using:

PriorityQueue

Why Heap?

Problem:

Find Top 5 numbers from 10 million numbers

Sorting:

Sort all 10 million

↓

Take first 5

Unnecessary work.


Heap approach:

Maintain only:

Top 5 elements

Min Heap Concept

For Top N highest numbers, use:

Min Heap

Why?

The smallest element among our top N candidates stays at the root.

Example:

Need:

Top 3

Numbers:

90,80,70

Heap:

70
 |
80
 |
90

When a larger number arrives:

60

Ignore.


When:

100

arrives:

Remove smallest:

70

Add:

100

Heap becomes:

80

90

100

Heap Algorithm

  1. Create Min Heap.
  2. Add numbers one by one.
  3. If heap size exceeds N:
    • Remove smallest element.
  4. Remaining elements are Top N.

Java Program — Top N Using PriorityQueue

import java.util.*;

public class TopNUsingHeap {


    public static List<Integer> findTopN(
            List<Integer> numbers,
            int n) {


        PriorityQueue<Integer> heap =
                new PriorityQueue<>();


        for(Integer number : numbers) {


            heap.offer(number);


            if(heap.size() > n) {

                heap.poll();

            }

        }


        return new ArrayList<>(heap);

    }


    public static void main(String[] args) {


        List<Integer> numbers =
                Arrays.asList(
                    10,
                    40,
                    20,
                    90,
                    50
                );


        System.out.println(
            findTopN(numbers,3)
        );

    }

}

Output

[40,50,90]

Order may vary because PriorityQueue does not maintain sorted order.


Step-by-Step Dry Run

Input:

[10,40,20,90,50]

N:

3

Start:

Heap = []

Add:

10

Heap:

[10]

Add:

40

Heap:

[10,40]

Add:

20

Heap:

[10,40,20]

Add:

90

Size exceeds 3.

Remove minimum:

10

Heap:

[20,40,90]

Add:

50

Remove minimum:

20

Final:

[40,50,90]

Complexity Analysis — Heap Approach

For every element:

Insert:

O(log N)

For n elements:

O(n log N)

Space:

O(N)

Sorting vs Heap Comparison

Approach Time Complexity Space Best Use
Sorting O(n log n) O(n) Small data
Stream sorted() O(n log n) O(n) Readable code
Min Heap O(n log k) O(k) Large data
Single pass O(n) O(1) Only max values

Top N Employees by Salary

A very common enterprise interview problem.

Problem:

Find top 3 highest paid employees.


Employee:

John     90000

Alice   150000

Bob     70000

David   120000

Result:

Alice

David

John

Stream Approach

List<Employee> topEmployees =

employees.stream()

.sorted(

Comparator
.comparing(
    Employee::getSalary
)
.reversed()

)

.limit(3)

.toList();


Heap Approach For Employees

PriorityQueue<Employee> heap =

new PriorityQueue<>(

Comparator.comparing(
    Employee::getSalary
)

);


for(Employee employee : employees) {


    heap.offer(employee);


    if(heap.size() > 3) {

        heap.poll();

    }

}

Top N Frequent Elements

Another popular interview problem:

Find the numbers appearing most frequently.


Example:

Input:

[1,1,1,2,2,3]

Frequency:

1 → 3

2 → 2

3 → 1

Top 2:

[1,2]

Step 1 — Create Frequency Map

Map<Integer,Integer> frequency =

numbers.stream()

.collect(

Collectors.toMap(

n -> n,

n -> 1,

Integer::sum

)

);

Result:

{
1=3,

2=2,

3=1
}

Step 2 — Sort By Frequency

frequency.entrySet()

.stream()

.sorted(

Map.Entry
.<Integer,Integer>
comparingByValue()
.reversed()

)

.limit(2)

.toList();

Comparator Customization

Top N problems often require custom ordering.

Example:

Sort by:

  1. Salary descending
  2. Name ascending

Comparator<Employee> comparator =

Comparator
.comparing(
    Employee::getSalary
)
.reversed()

.thenComparing(
    Employee::getName
);


Comparable vs Comparator

Feature Comparable Comparator
Defined Inside class Outside class
Method compareTo() compare()
Multiple sorting rules No Yes
Lambda support Limited Yes

Handling Duplicate Values

Example:

Input:

[100,90,90,80]

Question:

Should Top 3 return:

Include duplicates

100,90,90

Distinct values

100,90,80

Distinct solution:

numbers.stream()

.distinct()

.sorted(
    Comparator.reverseOrder()
)

.limit(3)

.toList();

Handling Null Values

Real applications may contain:

null

Example:

[100,90,null,80]

Filter null values:

numbers.stream()

.filter(
    Objects::nonNull
)

.sorted(
    Comparator.reverseOrder()
)

.limit(3)

.toList();

Parallel Stream Considerations

For very large datasets:

parallelStream()

can improve performance.

Example:

numbers.parallelStream()

.sorted(
    Comparator.reverseOrder()
)

.limit(10)

.toList();

But consider:

  • Data size
  • CPU cores
  • Ordering requirements

For normal collections:

stream()

is usually preferred.


Common Interview Mistakes

Mistake 1

Sorting when only Top K is required.

Example:

Need:

Top 5

from:

1 million numbers

Better:

Heap

Mistake 2

Using wrong heap.

For Top N highest:

Use:

Min Heap

For Top N lowest:

Use:

Max Heap

Mistake 3

Ignoring duplicates.

Clarify:

Top N values

or

Top N distinct values

Mistake 4

Assuming PriorityQueue is sorted.

PriorityQueue only guarantees:

Smallest element at root

Edge Cases

Case Handling
Empty list Return empty list
N = 0 Return empty list
N > size Return all elements
Duplicate values Use distinct if required
Null values Filter nulls

Interview Follow-up Questions

Q1. Find top N largest numbers.

Q2. Find top K frequent elements.

Q3. Difference between sorting and heap.

Q4. Why use Min Heap for Top K?

Q5. Find top N employees by salary.

Q6. How PriorityQueue works internally?

Q7. Solve without sorting.


Related Java Collection Problems

  • Find Highest Salary Employee
  • Second Highest Salary Using Streams
  • Custom Comparator Examples
  • Sort Employees by Salary
  • Find Duplicate Elements Using Streams
  • Character Frequency Using Streams

Key Takeaways

Top N pattern:

Collection

      ↓

Ranking Strategy

      ↓

Maintain N Elements

      ↓

Return Result

Recommended approach:

Small Data

Use:

sorted()

+

limit()

Large Data

Use:

PriorityQueue

Frequency Problems

Use:

HashMap

+

Heap

Complexity:

Sorting:

O(n log n)

Heap:

O(n log k)

Space:

O(k)

Frequently Asked Interview Questions

Q1. Why use Min Heap for Top N?

Because the smallest element among selected values can be removed quickly.


Q2. What is the best approach?

Depends on data size:

  • Sorting for simplicity
  • Heap for scalability

Q3. What is the difference between Top N and Maximum?

Maximum finds one element.

Top N finds multiple ranked elements.


Interview Tip

When asked:

"Find Top N highest numbers in Java."

Explain:

  1. For simple solution use Stream sorted + limit.
  2. For large data use PriorityQueue.
  3. Use Min Heap for Top N highest.
  4. Discuss duplicate handling.
  5. Explain complexity trade-offs.

For senior Java interviews, discuss:

  • Heap data structures.
  • Comparator design.
  • Stream operations.
  • Large-scale data processing.
  • Performance optimization.

This demonstrates strong understanding of Java Collections, Streams, heaps, and algorithm optimization.