wasAsked.

Please write a C# method that returns the second highest distinct number in an integer array. Example: input [10, 5, 20, 8, 20] should return 10 because 20 is highest and 10 is the next distinct value.

PwC · Full Stack Developer · technical

Published

Year not specified · C#

Community answers

Posted by wasAsked editorial collection

public static int? SecondHighestDistinct(int[] numbers) { ArgumentNullException.ThrowIfNull(numbers); int? highest = null; int? second = null; foreach (var n in numbers) { if (n == highest || n == second) continue; // ignore duplicates if (highest is null || n > highest) { second = highest; highest = n; } else if (second is null || n > second) { second = n; } } return second; } Console.WriteLine(SecondHighestDistinct([10, 5, 20, 8, 20])); // 10 Console.WriteLine(SecondHighestDistinct([7, 7, 7])); // null — no second distinct value Console.WriteLine(SecondHighestDistinct([-3, -1, -2])); // -2 How it works - One pass, O(n) time and O(1) extra memory. - highest and second track the two largest distinct values seen so far. - When a new maximum appears, the old maximum becomes the second highest. - Duplicates of the current highest (like the second 20) are skipped, which is why the answer is 10, not 20. Why return int? (nullable) - Arrays with fewer than two distinct values have no answer. Returning null (or using a TryGet pattern or throwing a clear exception) is better than returning a misleading value like 0 or int.MinValue, which could be a real element. LINQ alternative — shorter, fine for small inputs: public static int? SecondHighestDistinctLinq(int[] numbers) => numbers.Distinct().OrderByDescending(n => n).Skip(1).Cast<int?>().FirstOrDefault(); This is O(n log n) because of sorting and allocates more, but it is very readable. Mentioning both versions and their trade-offs is what interviewers usually want. Test cases to mention: the example input, all equal values, an empty array, a single element, negative numbers, int.MinValue present, and very large arrays.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics