0

how to find the max sequence order number before missing element.

input - 123678 output -3

public static void Main()
    {
        List<int> nums = new List<int>(){1,2,3,6,7,8};
        int count = nums.Count;
        for(int i=0;i<count;i++){
            if((nums[i+1]-nums[i])>1){
                Console.WriteLine("Missed Element after digit :" [i]);
            }
        }
    }

fiddle https://dotnetfiddle.net/Hkd0rx

error

Index was out of range. Must be non-negative and less than the size of the collection.

  • is there always only **1** number missing? or is it possible that you will have something like this as input: `new List(){1,2,3,6,7,8, 10, 11, 12, 13, 14};` ? – Mong Zhu Jun 03 '22 at 11:39

2 Answers2

1

You need to skip the last number because there's nothing to compare it to after it. So in your for loop change the condition to loop while i<count-1 is true.

You also have an error in your WriteLine. Right now it will pick the character from the string Missed Element after digit : at a specific index. To properly concatenate strings you could use + or string interpolation.

List<int> nums = new List<int>() { 1, 2, 3, 6, 7, 8 };
int count = nums.Count;
for (int i = 0; i < count - 1; i++)
{
    var current = nums[i];
    var next = nums[i + 1];
    if ((next - current) > 1)
    {
        Console.WriteLine("Missing Element(s) between : " + current + " and " + next);
    }
}
NotFound
  • 5,005
  • 2
  • 13
  • 33
0

Several issues are here:

  1. nums[i+1] can be out ouf range when i = 0 .. nums.Count - 1.
  2. When item is found you should break looping
  3. If all items (no missing item) in required order, you should return the last one.

Code

List<int> nums = new List<int>(){
  1, 2, 3, 6, 7, 8
};

// Add sorting if there's no guarantee that num has been sorted
// nums.Sort();

// In case we have no missing item we return the last one
int result = nums[nums.Count - 1];

// Note "nums.Count - 1" instead of "nums.Count"
for (int i = 0; i < nums.Count - 1; ++i)
  if (nums[i + 1] - nums[i] > 1) {
    result = nums[i];

    break; // Note break
  }

Console.WriteLine($"Missed Element is after number : {result}");
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215