# C++ program to replace an element makes array elements consecutive

C++ProgrammingServer Side Programming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

We are given an array of elements. We need to find if it is possible to change the value of any one element to make the array elements consecutive. If not possible, return -1 ; otherwise, the element needs to be changed.

Let's suppose we have an array {4, 3, 9, 5, 6} and we have to sort this given array. Then start from the smallest and largest element checking the number of mismatches. If the number of mismatches is more than 1 on both sides of the array, the answer is -1. Otherwise, it is possible to get the element that needs to change.

## Algorithm (Steps)

Following are the Algorithm/steps to be followed to perform the desired task −

• Get the required values in the form of an array (input array).

• A series of subsequent elements begins with the array's smallest element and moves forward by adding 1 to the previous element.

• A series of subsequent elements begins with maximum element of array, then continues by subtracting 1 from previous.

• Create the two series mentioned above, and then find each series' elements in the array. If there are more than one mismatches between the two series, then impossible. If one mismatch can be detected in any sequence, we have the answer.

## Example

Implementing a C++ program below, that replaces an array element such that all the array elements become consecutive −

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int solve(vector<int> arr) {
sort(arr.begin(), arr.end());
int n = arr.size();
int mismatch = 0, ans;
int nextElement = arr[n-1] - n + 1;
for (int i=0; i<n-1; i++, nextElement++) {
if (binary_search(arr.begin(), arr.end(), nextElement) == 0) {
ans = arr;
mismatch++;
}
}
if (mismatch == 1)
return ans;
if (mismatch == 0)
return 0;
mismatch = 0;
nextElement = arr + n - 1;
for (int i=n-1;i>=1;i--, nextElement--) {
if (binary_search(arr.begin(), arr.end(), nextElement) == 0) {
ans = arr[n-1];
mismatch++;
}
}
if (mismatch == 1)
return ans;
return -1;
}
int main() {
vector<int> arr = {4, 3, 9, 5, 6};
int ans = solve(arr);
if (ans == -1)
cout << "Impossible";
else if (ans == 0)
cout << "Already consecutive";
else
cout << ans;
return 0;
}


Changing the element 9 to 2 or 7 makes the entire set of elements consecutive. The arraybecomes = {4, 3, 7, 5, 6} and the output will be −

## Output

9


## Conclusion

The algorithm's time complexity is O(nlog(n)). We can also solve the exact problem by using a different array and finding if the difference changes at more than one place in the array and several more approaches. You may give it a shot after understanding this basic approach.