Related Articles

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

• Last Updated : 24 Apr, 2021

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 and arr with max(arr, arr)+1 = max(5, 3) + 1 = 6. Therefore, arr[] = {6, 4, 4, 5}.
Step 2: Replace arr and arr with max(arr, arr) + 1 = max(6, 4) + 1 = 7. Therefore, arr[] = {7, 4, 5}.
Step 3: Replace arr and arr with max(arr, arr)+1 = max(7, 4) + 1 = 8. Therefore, arr[] = {8, 5}.
Step 4: Replace arr and arr with max(arr, arr) + 1 = max(8, 5)+1 = 9. Therefore, arr[] = {9}.

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

Naive Approach: The simplest approach is to traverse the given array and for each element arr[i], start performing the given operation continuously according to the given constraints. If for any element, the array becomes a single element, print the index i otherwise, print -1

Time Complexity: O(N2)
Auxiliary Space: O(N)

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 and save is not equals arr, 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 is maximum element``    ``if` `(save == arr``        ``&& save != arr) {``        ``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);` `    ``// 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 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 prthe 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 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 is maximum``  ``// element``  ``if` `(save == arr &&``      ``save != arr)``  ``{``    ``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(N)
Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

My Personal Notes arrow_drop_up