Video in progress
How do you find the largest and second largest values in an array in a single pass?
I keep two variables, first and second. If a new number is greater than first, the old one drops into second; if it's greater only than second, second is updated. No sorting is needed, and time is O(n).
📖 Answer
Sorting and taking the last two is also an answer, but it's O(n log n). One loop is enough:
static int secondMax(int[] a) {
long first = Long.MIN_VALUE, second = Long.MIN_VALUE;
for (int v : a) {
if (v > first) {
second = first;
first = v;
} else if (v > second && v != first) {
second = v;
}
}
if (second == Long.MIN_VALUE) throw new IllegalArgumentException("ikkinchi qiymat yo'q");
return (int) second;
}
long and Long.MIN_VALUE are used on purpose: even if the array contains Integer.MIN_VALUE, we don't confuse it with the "not found" case.
Clarify with the interviewer: for [5, 5, 3], is the answer 5 or 3? The code above returns the "second distinct value", so 3. If duplicates should count, remove the v != first condition.
Sign up to mark studied questions and save your progress.