Reduce array to a single element by repeatedly replacing adjacent unequal pairs with their maximum
Last Updated :
14 Oct, 2023
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 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<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 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);
}
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 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
<script>
// JavaScript program for the above approach
// Function to print the index
// from where the operation can
// be started
function 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 array
let N = arr.length;
// Function Call
printIndex(arr, N);
// This code is contribute by target_2
</script>
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.
Similar Reads
Maximum product of the remaining pair after repeatedly replacing pairs of adjacent array elements with their sum
Given an array arr[] of size N, the task is to find the maximum product of remaining pairs possible after repeatedly replacing a pair of adjacent array elements with their sum. Note: Reduce the array to a size of 2. Examples: Input: arr[] = {2, 3, 5, 6, 7}Output: 130Explanation:Replacing arr[1] and
8 min read
Minimize array length by repeatedly replacing pairs of unequal adjacent array elements by their sum
Given an integer array arr[], the task is to minimize the length of the given array by repeatedly replacing two unequal adjacent array elements by their sum. Once the array is reduced to its minimum possible length, i.e. no adjacent unequal pairs are remaining in the array, print the count of operat
6 min read
Array value by repeatedly replacing max 2 elements with their absolute difference
Given an array arr size N, the task is to print the final array value remaining in the array when the maximum and second maximum element of the array is replaced by their absolute difference in the array, repeatedly. Note: If the maximum two elements are same, then both are removed from the array, w
6 min read
Maximize the count of adjacent element pairs with even sum by rearranging the Array
Given an array, arr[] of N integers, the task is to find the maximum possible count of adjacent pairs with an even sum, rearranging the array arr[]. Examples: Input: arr[] = {5, 5, 1}Output: 2Explanation:The given array is already arranged to give the maximum count of adjacent pairs with an even sum
6 min read
Smallest array that can be obtained by replacing adjacent pairs with their products
Given an array arr[] of size N, the task is to print the least possible size the given array can be reduced to by performing the following operations: Remove any two adjacent elements, say arr[i] and arr[i+1] and insert a single element arr[i] * arr[i+1] at that position in the array.If all array el
4 min read
Minimize remaining array element by removing pairs and replacing them with their average
Given an array arr[] of size N, the task is to find the smallest possible remaining array element by repeatedly removing a pair, say (arr[i], arr[j]) from the array and inserting the Ceil value of their average. Examples: Input: arr[] = { 1, 2, 3 } Output: 2Explanation: Removing the pair (arr[1], ar
7 min read
Minimize remaining array element by repeatedly replacing pairs by half of one more than their sum
Given an array arr[] containing a permutation of first N natural numbers. In one operation, remove a pair (X, Y) from the array and insert (X + Y + 1) / 2 into the array. The task is to find the smallest array element that can be left remaining in the array by performing the given operation exactly
11 min read
Make all array elements equal by replacing adjacent pairs by their sum
Given an array arr[] consisting of N integers, the task is to replace a minimum number of pairs of adjacent elements by their sum to make all array elements equal. Print the minimum number of such operations required. Examples: Input: arr[] = {1, 2, 3}Output: 1Explanation: Replace arr[0] and arr[1]
8 min read
Reduce array to a single element by repeatedly removing an element from any increasing pair
Given an array arr[] consisting of permutation in the range [1, N], the task is to check if the given array can be reduced to a single non-zero element by performing the following operations: Select indices i and j such that i < j and arr[i] < arr[j] and convert one of the two elements to 0. I
9 min read
Maximize modulus by replacing adjacent pairs with their modulus for any permutation of given Array
Given an array A[] consisting of distinct elements, the task is to obtain the largest possible modulus value that remains after repeatedly replacing adjacent elements by their modulus, starting from the first element, for any possible permutations of the given array. (...(( A[1] mod A[2]) mod A[3])
11 min read