Q:

Why does my code doesn't print the correct minimum difference?

I'm currently trying to solve the horse-racing game on Codingame. The problem statement is as follows:

Input
Line 1: Number N of horses
The N following lines: the strength Pi of each horse. Pi is an integer.
Output
The difference D between the two closest strengths. D is an integer greater than or equal to 0.

I'm using a std::set, and my algorithm is quite easy but for some reason it fails 2/8 of the submission validators. I don't have access to the actual test data, but according to the test names, the code below fails for

all horses same strength
horses in disorder

Why does my code fail on that input?
#include <iostream>
#include <set>

using namespace std;

int main()
{
    int N;
    cin >> N; cin.ignore();

    set<int> power;

    for (int i = 0; i < N; i++)
    {
        int Pi;
        cin >> Pi; cin.ignore();
        power.insert(Pi);
    }

    int minDiff = 10000000;

    auto i = power.begin();

    while (i != power.end())
    {
        minDiff = min(minDiff, abs(*i - *(++i)));
    }
    
    cout << minDiff << endl;
}

A:

Your solution fails if any two horses have the same strength:
std::set<int> horses;
horses.insert(1);
horses.insert(2);
horses.insert(1);

// your algorithm returns 1, but it should be 0

Also, you have undefined behaviour. What happens if ++i is power.end() here?
minDiff = std::min(minDiff, abs(*i - *(++i)));

Use two iterators instead, and check for the special case where you have only one kind of horse if you want to use std::set.

