Second highest number in array?
Short answer: Logic Track highest and second highest in one loop. int[] arr = { 10, 5, 20, 8 }; int first = int.MinValue, second = int.MinValue; foreach (int num in arr) { if (num > first) { second = first; first = num; } else if (num > second && num != first) { second = num; } }
Example code
Logic Track highest and second highest in one loop. int[] arr = { 10, 5, 20, 8 };
int first = int.MinValue, second = int.MinValue;
foreach (int num in arr)
{
if (num > first)
{
second = first;
first = num;
} else if (num > second && num != first) {
second = num;
}
}
Real-world example (ShopNest)
In coding rounds, state complexity aloud, write a clear ShopNest-flavored example (orders, carts), then handle edge cases (empty list, null, overflow).
Say this in the interview
- Define — one clear sentence (the short answer above).
- Example — relate it to a project like ShopNest or your real work.
- Trade-off — when you would not use it.
Share this Q&A
Share preview image: https://www.toolliyo.com/images/toolliyo-logo.png