Second Highest Number with Streams
Problem
Read an array. Print the second highest different value, or none if it does not exist. Use distinct, sorting and skip in a stream pipeline (in Java).
Constraints
- 1 <= n <= 10^5
Examples
Input
8 3 1 4 1 5 9 2 6
Output
6
Solutions
A pipeline that removes duplicates, sorts and skips the first element. Optional models the case of no answer without using null.
Optional and streams are Java 8 features.
/*
* Problem : Process an array.
* Input : n, then n integers.
* Output : The second highest or none.
* Approach: distinct, sorted, skip.
* Time : O(n log n)
* Space : O(n)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static String solve(int[] a) {
// Step 1: distinct removes equal values.
// Step 2: sorted in reverse order puts the biggest value first.
// Step 3: skip(1) drops the highest value. findFirst takes the next one, if there is one.
java.util.Optional<Integer> second = java.util.Arrays.stream(a)
.boxed()
.distinct()
.sorted(java.util.Comparator.reverseOrder())
.skip(1)
.findFirst();
// Step 4: Optional says "maybe there is no value". We print none for an empty Optional.
return second.isPresent() ? String.valueOf(second.get()) : "none";
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = scanner.nextInt();
}
System.out.println(solve(a));
}
}
Hints (1)
- What does Optional.isPresent tell you?