Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the second last greatest element in list of integers C#

Tags:

c#

.net

I have a

list<int> input = //from db of one million records

of 1 million records .

Although I know that using input.OrderByDescending().Skip(1).Take(1) will solve the problem but if I have 1 million records , it is not a best practice to use OrderBY.

In this scenario which solution is the best one when we have more records?

like image 790
user1400915 Avatar asked Dec 15 '25 02:12

user1400915


1 Answers

Scan the list while tracking the max, as well as max2 and you'll get O(N) versus O(N * log(N)) time complexity:

  // Maximum value
  int max  = Math.Max(input[input.Count - 1], input[input.Count - 2]);
  // Second greatest   
  int max2 = Math.Min(input[input.Count - 1], input[input.Count - 2]);

  // i >= 0: Comparing with 0 is slightly faster then with Count
  for (int i = input.Count - 3; i >= 0; --i) {
    int v = input[i];

    if (v >= max) {
      max2 = max;
      max = v; 
    }
    else if (v > max2) 
      max2 = v;
  }

Edit: In case duplicates should be ignored (see comments below) and thus the answer for [1, 2, 3, 4, 4, 4, 4] should be 3, not 4:

  // Maximum value
  int max = int.MinValue;
  // Second greatest   
  int max2 = int.MinValue;

  // i >= 0: Comparing with 0 is slightly faster then with Count
  for (int i = input.Count - 1; i >= 0; --i) {
    int v = input[i];

    if (v > max) {
      max2 = max;
      max = v;
    }
    else if (v > max2 && v != max)
      max2 = v;
  }
like image 68
Dmitry Bychenko Avatar answered Dec 16 '25 16:12

Dmitry Bychenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!