# Reduce array to a single element by repeatedly replacing adjacent unequal pairs with their maximum

Given an array arr[] consisting of N integers, the task is to reduce the given array to a single element by repeatedly replacing any pair of consecutive unequal elements, say arr[i] and arr[i+1] with max(arr[i], arr[i + 1]) + 1. If possible, print the index of the element from where the operation can be started. Otherwise, print -1.

Examples:

Input: arr[] = {5, 3, 4, 4, 5}
Output:
Explanation:
Step 1: Replace arr[1] and arr[2] with max(arr[1], arr[2])+1 = max(5, 3) + 1 = 6. Therefore, arr[] = {6, 4, 4, 5}.
Step 2: Replace arr[1] and arr[2] with max(arr[1], arr[2]) + 1 = max(6, 4) + 1 = 7. Therefore, arr[] = {7, 4, 5}.
Step 3: Replace arr[1] and arr[2] with max(arr[1], arr[2])+1 = max(7, 4) + 1 = 8. Therefore, arr[] = {8, 5}.
Step 4: Replace arr[1] and arr[2] with max(arr[1], arr[2]) + 1 = max(8, 5)+1 = 9. Therefore, arr[] = {9}.

Input: arr[] ={1, 1}
Output: -1

Naive Approach: The idea is to reduce an array of integers by increasing some of its elements until all the elements become equal. The approach taken by the algorithm is to find pairs of adjacent elements that are not equal and increase the larger of the two until they become equal. This is repeated until all the elements become equal or the array cannot be reduced further. Below are the steps:

1. Initialize a variable n to the size of the array and a variable index to -1.
2. Iterate a loop that runs until n is greater than 1.
1. Inside the loop, initialize a variable i to 0 and enter a loop that runs until i is less than n – 1, Inside this loop, check if arr[i] is not equal to arr[i+1]. If they are not equal, set arr[i] to the maximum of arr[i] and arr[i+1] plus 1, set the index to i, and then break out of the inner loop.
2. If i is equal to n – 1, break out of the outer loop, as all elements of the array are equal.
3. Otherwise, initialize a variable j to i + 1 and enter a loop that runs until j is less than n – 1, and inside this loop, check if arr[j] is not equal to arr[j+1]. If they are not equal, set arr[j] to the maximum of arr[j] and arr[j+1] plus 1, set the index to j, and then break out of the inner loop.
4. If j is equal to n – 1, break out of the outer loop, as all elements of the array from i to n – 1 are equal. Otherwise, set i to j + 1 and set n to j + 1.
3. If the index is not equal to -1, increment the index by 1 and print this resultant index.

Below is the implementation of the above approach:

## C++

 `// C++ program for the above approach` `#include ` `#include ` `using` `namespace` `std;`   `// Function to find the index of the` `// array to reduce the array as per the` `// given conditions` `int` `reduceArray(vector<``int``>& arr)` `{` `    ``int` `n = arr.size();` `    ``int` `index = -1;` `    ``while` `(n > 1) {` `        ``int` `i = 0;` `        ``while` `(i < n - 1) {` `            ``if` `(arr[i] != arr[i + 1]) {` `                ``arr[i] = max(arr[i], arr[i + 1]) + 1;` `                ``index = i;` `                ``break``;` `            ``}` `            ``i++;` `        ``}`   `        ``// If all elements are equal` `        ``if` `(i == n - 1)` `            ``break``;` `        ``int` `j = i + 1;` `        ``while` `(j < n - 1) {` `            ``if` `(arr[j] != arr[j + 1]) {` `                ``arr[j] = max(arr[j], arr[j + 1]) + 1;` `                ``index = j;` `                ``break``;` `            ``}` `            ``j++;` `        ``}`   `        ``// If all elements are equal` `        ``if` `(j == n - 1)` `            ``break``;` `        ``i = j + 1;` `        ``n = j + 1;` `    ``}` `    ``if` `(index != -1)` `        ``index++;`   `    ``// Return the resultant index` `    ``return` `index;` `}`   `// Driver Code` `int` `main()` `{` `    ``vector<``int``> arr =  { 5, 3, 4, 4, 5 };` `    ``int` `index = reduceArray(arr);` `    ``if` `(index == -1) {` `        ``cout << ``"-1"``;` `    ``}` `    ``else` `{` `        ``cout << index;` `    ``}` `    ``return` `0;` `}`

## Java

 `import` `java.util.ArrayList;` `import` `java.util.List;`   `public` `class` `Main {` `    ``// Function to find the index of the array to reduce the array as per the given conditions` `    ``public` `static` `int` `reduceArray(List arr) {` `        ``int` `n = arr.size();` `        ``int` `index = -``1``;` `        ``while` `(n > ``1``) {` `            ``int` `i = ``0``;` `            ``while` `(i < n - ``1``) {` `                ``if` `(!arr.get(i).equals(arr.get(i + ``1``))) {` `                    ``arr.set(i, Math.max(arr.get(i), arr.get(i + ``1``)) + ``1``);` `                    ``index = i;` `                    ``break``;` `                ``}` `                ``i++;` `            ``}`   `            ``// If all elements are equal` `            ``if` `(i == n - ``1``)` `                ``break``;` `            `  `            ``int` `j = i + ``1``;` `            ``while` `(j < n - ``1``) {` `                ``if` `(!arr.get(j).equals(arr.get(j + ``1``))) {` `                    ``arr.set(j, Math.max(arr.get(j), arr.get(j + ``1``)) + ``1``);` `                    ``index = j;` `                    ``break``;` `                ``}` `                ``j++;` `            ``}`   `            ``// If all elements are equal` `            ``if` `(j == n - ``1``)` `                ``break``;`   `            ``i = j + ``1``;` `            ``n = j + ``1``;` `        ``}` `        ``if` `(index != -``1``)` `            ``index++;`   `        ``// Return the resultant index` `        ``return` `index;` `    ``}`   `    ``// Driver Code` `    ``public` `static` `void` `main(String[] args) {` `        ``List arr = ``new` `ArrayList<>();` `        ``arr.add(``5``);` `        ``arr.add(``3``);` `        ``arr.add(``4``);` `        ``arr.add(``4``);` `        ``arr.add(``5``);` `        ``int` `index = reduceArray(arr);` `        ``if` `(index == -``1``) {` `            ``System.out.println(``"-1"``);` `        ``} ``else` `{` `            ``System.out.println(index);` `        ``}` `    ``}` `}`

## Python3

 `def` `reduce_array(arr):` `    ``n ``=` `len``(arr)` `    ``index ``=` `-``1` `    ``# loop until the size of the array becomes 1 or less` `    ``while` `n > ``1``:` `        ``i ``=` `0` `        ``# find the first pair of consecutive elements that are not equal` `        ``while` `i < n ``-` `1``:` `            ``if` `arr[i] !``=` `arr[i ``+` `1``]:` `                ``# set the larger of the two elements to the ` `                ``# sum of the two elements + 1` `                ``arr[i] ``=` `max``(arr[i], arr[i ``+` `1``]) ``+` `1` `                ``index ``=` `i` `                ``break` `            ``i ``+``=` `1`   `        ``# If all elements are equal` `        ``if` `i ``=``=` `n ``-` `1``:` `            ``break`   `        ``j ``=` `i ``+` `1` `        ``# find the next pair of consecutive elements that are not equal` `        ``while` `j < n ``-` `1``:` `            ``if` `arr[j] !``=` `arr[j ``+` `1``]:` `                ``# set the larger of the two elements to the sum of ` `                ``# the two elements + 1` `                ``arr[j] ``=` `max``(arr[j], arr[j ``+` `1``]) ``+` `1` `                ``index ``=` `j` `                ``break` `            ``j ``+``=` `1`   `        ``# If all elements are equal` `        ``if` `j ``=``=` `n ``-` `1``:` `            ``break`   `        ``i ``=` `j ``+` `1` `        ``n ``=` `j ``+` `1`   `    ``if` `index !``=` `-``1``:` `        ``index ``+``=` `1`   `    ``# Return the resultant index` `    ``return` `index`   `# Driver Code` `arr ``=` `[``5``, ``3``, ``4``, ``4``, ``5``]` `index ``=` `reduce_array(arr)` `if` `index ``=``=` `-``1``:` `    ``print``(``"-1"``)` `else``:` `    ``print``(index)`

## C#

 `using` `System;` `using` `System.Collections.Generic;`   `class` `Program` `{` `    ``// Function to find the index of the array to reduce the array as per the given conditions` `    ``static` `int` `ReduceArray(List<``int``> arr)` `    ``{` `        ``int` `n = arr.Count;` `        ``int` `index = -1;` `        ``while` `(n > 1)` `        ``{` `            ``int` `i = 0;` `            ``while` `(i < n - 1)` `            ``{` `                ``if` `(arr[i] != arr[i + 1])` `                ``{` `                    ``arr[i] = Math.Max(arr[i], arr[i + 1]) + 1;` `                    ``index = i;` `                    ``break``;` `                ``}` `                ``i++;` `            ``}`   `            ``// If all elements are equal` `            ``if` `(i == n - 1)` `                ``break``;`   `            ``int` `j = i + 1;` `            ``while` `(j < n - 1)` `            ``{` `                ``if` `(arr[j] != arr[j + 1])` `                ``{` `                    ``arr[j] = Math.Max(arr[j], arr[j + 1]) + 1;` `                    ``index = j;` `                    ``break``;` `                ``}` `                ``j++;` `            ``}`   `            ``// If all elements are equal` `            ``if` `(j == n - 1)` `                ``break``;`   `            ``i = j + 1;` `            ``n = j + 1;` `        ``}` `        ``if` `(index != -1)` `            ``index++;`   `        ``// Return the resultant index` `        ``return` `index;` `    ``}`   `    ``static` `void` `Main(``string``[] args)` `    ``{` `        ``List<``int``> arr = ``new` `List<``int``> { 5, 3, 4, 4, 5 };` `        ``int` `index = ReduceArray(arr);` `        ``if` `(index == -1)` `        ``{` `            ``Console.WriteLine(``"-1"``);` `        ``}` `        ``else` `        ``{` `            ``Console.WriteLine(index);` `        ``}` `    ``}` `}`

## Javascript

 `// Function to find the index of the array to reduce the array as per the given conditions` `function` `reduceArray(arr) {` `    ``let n = arr.length;` `    ``let index = -1;` `    ``while` `(n > 1) {` `        ``let i = 0;` `        ``while` `(i < n - 1) {` `            ``if` `(arr[i] !== arr[i + 1]) {` `                ``arr[i] = Math.max(arr[i], arr[i + 1]) + 1;` `                ``index = i;` `                ``break``;` `            ``}` `            ``i++;` `        ``}`   `        ``// If all elements are equal` `        ``if` `(i === n - 1)` `            ``break``;`   `        ``let j = i + 1;` `        ``while` `(j < n - 1) {` `            ``if` `(arr[j] !== arr[j + 1]) {` `                ``arr[j] = Math.max(arr[j], arr[j + 1]) + 1;` `                ``index = j;` `                ``break``;` `            ``}` `            ``j++;` `        ``}`   `        ``// If all elements are equal` `        ``if` `(j === n - 1)` `            ``break``;`   `        ``i = j + 1;` `        ``n = j + 1;` `    ``}` `    ``if` `(index !== -1)` `        ``index++;`   `    ``// Return the resultant index` `    ``return` `index;` `}`   `// Driver Code` `const arr = [5, 3, 4, 4, 5];` `const index = reduceArray(arr);` `if` `(index === -1) {` `    ``console.log(``"-1"``);` `} ``else` `{` `    ``console.log(index);` `}`

Output

```1

```

Time Complexity: O(N2), as we have to use nested loops for traversing N*N times.
Auxiliary Space: O(N), as we have to use extra space.

Efficient Approach: The idea is to use a Sorting Algorithm. Notice that the answer will always be -1 if all the elements are the same. Otherwise, the index having the maximum element can be chosen to starting performing the operations. Follow the below steps to solve the problem:

• Create another array B[] same as the given array and create a variable save initialize with -1 to store the answer.
• Sort the array B[].
• Traverse the array over the range [N – 1 to 0] using the variable i and if two consecutive unequal elements are found i.e., B[i] is not equals to B[i – 1], update save as save = i.
• After traversing the array:
• If save is -1, print -1 and return.
• Else if save is equal to arr[0] and save is not equals arr[1], then update save as 1.
• Else if save is equal to arr[N – 1] and save is not equal to arr[N – 2], then update save as N.
• Otherwise, iterate a loop over the range [1, N – 1] and check if save is equal to arr[i] such that arr[i] is not equals to arr[i – 1] and arr[i+1], then update save as save = i+1.
• After the above steps, print the index that is stored in the variable save.

Below is the implementation of the above approach:

## C++

 `// C++ program for the above approach`   `#include ` `using` `namespace` `std;`   `// Function to print the index from` `// where the operation can be started` `void` `printIndex(``int` `arr[], ``int` `N)` `{` `    ``// Initialize B[]` `    ``int` `B[N];`   `    ``// Initialize save` `    ``int` `save = -1;`   `    ``// Make B[] equals to arr[]` `    ``for` `(``int` `i = 0; i < N; i++) {` `        ``B[i] = arr[i];` `    ``}`   `    ``// Sort the array B[]` `    ``sort(B, B + N);`   `    ``// Traverse from N-1 to 1` `    ``for` `(``int` `i = N - 1; i >= 1; i--) {`   `        ``// If B[i] & B[i-1] are unequal` `        ``if` `(B[i] != B[i - 1]) {` `            ``save = B[i];` `            ``break``;` `        ``}` `    ``}`   `    ``// If all elements are same` `    ``if` `(save == -1) {` `        ``cout << -1 << endl;` `        ``return``;` `    ``}`   `    ``// If arr[1] is maximum element` `    ``if` `(save == arr[0]` `        ``&& save != arr[1]) {` `        ``cout << 1;` `    ``}`   `    ``// If arr[N-1] is maximum element` `    ``else` `if` `(save == arr[N - 1]` `             ``&& save != arr[N - 2]) {` `        ``cout << N;` `    ``}`   `    ``// Find the maximum element` `    ``for` `(``int` `i = 1; i < N - 1; i++) {`   `        ``if` `(save == arr[i]` `            ``&& (save != arr[i - 1]` `                ``|| save != arr[i + 1])) {` `            ``cout << i + 1;` `            ``break``;` `        ``}` `    ``}` `}`   `// Driver Code` `int` `main()` `{` `    ``// Given array arr[]` `    ``int` `arr[] = { 5, 3, 4, 4, 5 };`   `    ``// Length of array` `    ``int` `N = ``sizeof``(arr) / ``sizeof``(arr[0]);`   `    ``// Function Call` `    ``printIndex(arr, N);`   `    ``return` `0;` `}`

## Java

 `// Java program for the` `// above approach` `import` `java.util.*;` `class` `GFG{`   `// Function to print the index ` `// from where the operation can ` `// be started` `static` `void` `printIndex(``int` `arr[], ` `                       ``int` `N)` `{` `  ``// Initialize B[]` `  ``int` `[]B = ``new` `int``[N];`   `  ``// Initialize save` `  ``int` `save = -``1``;`   `  ``// Make B[] equals to arr[]` `  ``for` `(``int` `i = ``0``; i < N; i++) ` `  ``{` `    ``B[i] = arr[i];` `  ``}`   `  ``// Sort the array B[]` `  ``Arrays.sort(B);`   `  ``// Traverse from N-1 to 1` `  ``for` `(``int` `i = N - ``1``; i >= ``1``; i--) ` `  ``{` `    ``// If B[i] & B[i-1] are ` `    ``// unequal` `    ``if` `(B[i] != B[i - ``1``])` `    ``{` `      ``save = B[i];` `      ``break``;` `    ``}` `  ``}`   `  ``// If all elements are same` `  ``if` `(save == -``1``) ` `  ``{` `    ``System.out.print(-``1` `+ ``"\n"``);` `    ``return``;` `  ``}`   `  ``// If arr[1] is maximum ` `  ``// element` `  ``if` `(save == arr[``0``] && ` `      ``save != arr[``1``]) ` `  ``{` `    ``System.out.print(``1``);` `  ``}`   `  ``// If arr[N-1] is maximum ` `  ``// element` `  ``else` `if` `(save == arr[N - ``1``] && ` `           ``save != arr[N - ``2``])` `  ``{` `    ``System.out.print(N);` `  ``}`   `  ``// Find the maximum element` `  ``for` `(``int` `i = ``1``; i < N - ``1``; i++) ` `  ``{` `    ``if` `(save == arr[i] && ` `       ``(save != arr[i - ``1``] || ` `        ``save != arr[i + ``1``])) ` `    ``{` `      ``System.out.print(i + ``1``);` `      ``break``;` `    ``}` `  ``}` `}`   `// Driver Code` `public` `static` `void` `main(String[] args)` `{` `  ``// Given array arr[]` `  ``int` `arr[] = {``5``, ``3``, ``4``, ``4``, ``5``};`   `  ``// Length of array` `  ``int` `N = arr.length;`   `  ``// Function Call` `  ``printIndex(arr, N);` `}` `}`   `// This code is contributed by Rajput-Ji`

## Python3

 `# Python3 program for the` `# above approach`   `# Function to print the index` `# from where the operation can` `# be started` `def` `printIndex(arr, N):` `    `  `    ``# Initialize B` `    ``B ``=` `[``0``] ``*` `(N)`   `    ``# Initialize save` `    ``save ``=` `-``1` `    `  `    ``# Make B equals to arr` `    ``for` `i ``in` `range``(N):` `        ``B[i] ``=` `arr[i]`   `    ``# Sort the array B` `    ``B ``=` `sorted``(B)`   `    ``# Traverse from N-1 to 1` `    ``for` `i ``in` `range``(N ``-` `1``, ``1``, ``-``1``):` `        `  `        ``# If B[i] & B[i-1] are` `        ``# unequal` `        ``if` `(B[i] !``=` `B[i ``-` `1``]):` `            ``save ``=` `B[i]` `            ``break`   `    ``# If all elements are same` `    ``if` `(save ``=``=` `-``1``):` `        ``print``(``-``1` `+` `"")` `        ``return`   `    ``# If arr[1] is maximum` `    ``# element` `    ``if` `(save ``=``=` `arr[``0``] ``and` `        ``save !``=` `arr[``1``]):` `        ``print``(``1``)`   `    ``# If arr[N-1] is maximum` `    ``# element` `    ``elif` `(save ``=``=` `arr[N ``-` `1``] ``and` `          ``save !``=` `arr[N ``-` `2``]):` `        ``print``(N)`   `    ``# Find the maximum element` `    ``for` `i ``in` `range``(``1``, N ``-` `1``):` `        ``if` `(save ``=``=` `arr[i] ``and` `           ``(save !``=` `arr[i ``-` `1``] ``or` `            ``save !``=` `arr[i ``+` `1``])):` `            ``print``(i ``+` `1``)` `            ``break`   `# Driver Code` `if` `__name__ ``=``=` `'__main__'``:` `    `  `    ``# Given array arr` `    ``arr ``=` `[ ``5``, ``3``, ``4``, ``4``, ``5` `]`   `    ``# Length of array` `    ``N ``=` `len``(arr)`   `    ``# Function Call` `    ``printIndex(arr, N)`   `# This code is contributed by Rajput-Ji`

## C#

 `// C# program for the` `// above approach` `using` `System;`   `class` `GFG{`   `// Function to print the index ` `// from where the operation can ` `// be started` `static` `void` `printIndex(``int` `[]arr, ` `                       ``int` `N)` `{` `  `  `  ``// Initialize []B` `  ``int` `[]B = ``new` `int``[N];`   `  ``// Initialize save` `  ``int` `save = -1;`   `  ``// Make []B equals to []arr` `  ``for``(``int` `i = 0; i < N; i++) ` `  ``{` `    ``B[i] = arr[i];` `  ``}`   `  ``// Sort the array []B` `  ``Array.Sort(B);`   `  ``// Traverse from N-1 to 1` `  ``for``(``int` `i = N - 1; i >= 1; i--) ` `  ``{` `    `  `    ``// If B[i] & B[i-1] are ` `    ``// unequal` `    ``if` `(B[i] != B[i - 1])` `    ``{` `      ``save = B[i];` `      ``break``;` `    ``}` `  ``}`   `  ``// If all elements are same` `  ``if` `(save == -1) ` `  ``{` `    ``Console.Write(-1 + ``"\n"``);` `    ``return``;` `  ``}`   `  ``// If arr[1] is maximum ` `  ``// element` `  ``if` `(save == arr[0] && ` `      ``save != arr[1]) ` `  ``{` `    ``Console.Write(1);` `  ``}`   `  ``// If arr[N-1] is maximum ` `  ``// element` `  ``else` `if` `(save == arr[N - 1] && ` `           ``save != arr[N - 2])` `  ``{` `    ``Console.Write(N);` `  ``}`   `  ``// Find the maximum element` `  ``for``(``int` `i = 1; i < N - 1; i++) ` `  ``{` `    ``if` `(save == arr[i] && ` `       ``(save != arr[i - 1] || ` `        ``save != arr[i + 1])) ` `    ``{` `      ``Console.Write(i + 1);` `      ``break``;` `    ``}` `  ``}` `}`   `// Driver Code` `public` `static` `void` `Main(String[] args)` `{` `  `  `  ``// Given array []arr` `  ``int` `[]arr = { 5, 3, 4, 4, 5 };`   `  ``// Length of array` `  ``int` `N = arr.Length;`   `  ``// Function Call` `  ``printIndex(arr, N);` `}` `}`   `// This code is contributed by Amit Katiyar`

## Javascript

 ``

Output

```1

```

Time Complexity: O(NlogN), as we are using an inbuilt sort function.
Auxiliary Space: O(N), as we are using extra space for the array.

Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!

Previous
Next