Find the second-largest distinct value
Find the second-largest distinct integer in an array without sorting it. Reject arrays that do not contain two distinct values.
Course progress
Problem 20 of 100
Example → approach → runnable solution
Worked example
See the problem in action
Trace a concrete input through to the verified result.
Example input
numbers = [8, 3, 8, 6, 2]
Expected output
6
What is happening?
The largest distinct value is 8. Ignoring its duplicate leaves 6 as the next-largest distinct value.
Solution strategy
Build the right mental model
Track the largest and second-largest distinct values during one scan. Boolean flags avoid unsafe sentinel values for arrays containing int.MinValue.
Core concepts
arrays · state tracking
Complexity
Time O(n), space O(1).
Runnable solution
Learn from working code
Compare languages, copy the code, or open it in the compiler.
Complete C# solution for second-largest-distinct
using System;
class Program
{
static int SecondLargest(int[] numbers)
{
int largest = 0, second = 0;
bool hasLargest = false, hasSecond = false;
foreach (int number in numbers)
{
if (!hasLargest || number > largest)
{
if (hasLargest) { second = largest; hasSecond = true; }
largest = number;
hasLargest = true;
}
else if (number != largest && (!hasSecond || number > second))
{
second = number;
hasSecond = true;
}
}
if (!hasSecond) throw new ArgumentException("Two distinct values are required.");
return second;
}
static void Main()
{
Console.WriteLine(SecondLargest(new[] { 8, 3, 8, 6, 2 }));
}
}Knowledge check
Questions students often ask
What is the main idea behind find the second-largest distinct value?
Track the largest and second-largest distinct values during one scan. Boolean flags avoid unsafe sentinel values for arrays containing int.MinValue.
What is the time and space complexity of this solution?
Time O(n), space O(1).
Do all language tabs solve the same problem?
Yes. Every program uses the same example and produces the verified output shown on this page. The syntax and a few language-specific data structures differ.