Consecutive numbers at distance less than or equal to 2, only two consecutives at distance 1.

In this exercise you have to implement a function which receives a
vector of integers satisfying the following property. Any pair of
consecutive values in the vector are at a distance less than or equal to
2 from each other. Moreover, there is only one pair of consecutive
values which are exactly at distance 1. For instance, the following
sequence of values satisfies this property:

    3 1 1 2 4 2 2 0

The function has to return the position (indexing from 0) of the first
element of the consecutive pair which has distance 1. With the previous
example as the input, the function would return 2.

This is the header:

    // Pre: Let n be v.size(). Then, for each i in {0..n-2}, |v[i]-v[i+1]|<=2 holds.
    //      In addition, there is exactly one i in {0..n-2} satisfying |v[i]-v[i+1]|=1.
    // Post: The function returns this particular i in {0..n-2} satisfying |v[i]-v[i+1]|=1.
    int positionDistance1(const vector<int> &v);

Observation

You only need to submit the required procedure; your main program will
be ignored.

Observation

Evaluation out of 10 points:

- Slow solution: 5 points.

- Fast solution: 10 points.

A fast solution is one which is correct, of logarithmic cost and passing
the test cases, both public and private. A slow solution is one which is
not fast, but it is correct and passes the public test cases.

Problem information

Author: PRO1

Generation: 2026-01-25T23:01:28.747Z

© Jutge.org, 2006–2026.
https://jutge.org
