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: 1Â
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:
- Initialize a variable n to the size of the array and a variable index to -1.
- Iterate a loop that runs until n is greater than 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.
- If i is equal to n – 1, break out of the outer loop, as all elements of the array are equal.
- 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.
- 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.
- 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 <iostream>#include <vector>using namespace std;Â
// Function to find the index of the// array to reduce the array as per the// given conditionsint 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 Codeint 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<Integer> 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<Integer> 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 Codearr = [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 conditionsfunction 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 Codeconst arr = [5, 3, 4, 4, 5];const index = reduceArray(arr);if (index === -1) {Â Â Â Â console.log("-1");} else {Â Â Â Â console.log(index);} |
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 <bits/stdc++.h>using namespace std;Â
// Function to print the index from// where the operation can be startedvoid 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 Codeint 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 approachimport java.util.*;class GFG{Â
// Function to print the index // from where the operation can // be startedstatic 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 Codepublic 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 starteddef 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 Codeif __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 approachusing System;Â
class GFG{Â
// Function to print the index // from where the operation can // be startedstatic 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 Codepublic 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
<script>Â
// JavaScript program for the above approachÂ
// Function to print the index// from where the operation can// be startedfunction printIndex(arr, N){         // Initialize B[]    let B = [];         // Initialize save    let save = -1;         // Make B[] equals to arr[]    for(let i = 0; i < N; i++)    {        B[i] = arr[i];    }         // Sort the array B[]    B.sort();         // Traverse from N-1 to 1    for(let 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)    {        document.write(-1 + "<br/>");        return;    }         // If arr[1] is maximum    // element    if (save == arr[0] &&        save != arr[1])    {        document.write(1);    }         // If arr[N-1] is maximum    // element    else if (save == arr[N - 1] &&            save != arr[N - 2])    {        document.write(N);    }         // Find the maximum element    for (let i = 1; i < N - 1; i++)    {        if (save == arr[i] &&           (save != arr[i - 1] ||            save != arr[i + 1]))        {            document.write(i + 1);            break;        }    }}Â
// Driver CodeÂ
// Given array arr[]let arr = [5, 3, 4, 4, 5];Â
// Length of arraylet N = arr.length;Â
// Function CallprintIndex(arr, N);Â
// This code is contribute by target_2Â
</script> |
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.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



