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

C++ProgrammingServer Side Programming

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[0]; mismatch++; } } if (mismatch == 1) return ans; if (mismatch == 0) return 0; mismatch = 0; nextElement = arr[0] + 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.

raja
Updated on 10-Aug-2022 10:01:57

Advertisements