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++
#include <iostream>
#include <vector>
using namespace std;
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 (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 (j == n - 1)
break ;
i = j + 1;
n = j + 1;
}
if (index != -1)
index++;
return index;
}
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 {
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 (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 (j == n - 1 )
break ;
i = j + 1 ;
n = j + 1 ;
}
if (index != - 1 )
index++;
return index;
}
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
while n > 1 :
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 + = 1
if i = = n - 1 :
break
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 + = 1
if j = = n - 1 :
break
i = j + 1
n = j + 1
if index ! = - 1 :
index + = 1
return index
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
{
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 (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 (j == n - 1)
break ;
i = j + 1;
n = j + 1;
}
if (index != -1)
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 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 (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 (j === n - 1)
break ;
i = j + 1;
n = j + 1;
}
if (index !== -1)
index++;
return index;
}
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++
#include <bits/stdc++.h>
using namespace std;
void printIndex( int arr[], int N)
{
int B[N];
int save = -1;
for ( int i = 0; i < N; i++) {
B[i] = arr[i];
}
sort(B, B + N);
for ( int i = N - 1; i >= 1; i--) {
if (B[i] != B[i - 1]) {
save = B[i];
break ;
}
}
if (save == -1) {
cout << -1 << endl;
return ;
}
if (save == arr[0]
&& save != arr[1]) {
cout << 1;
}
else if (save == arr[N - 1]
&& save != arr[N - 2]) {
cout << N;
}
for ( int i = 1; i < N - 1; i++) {
if (save == arr[i]
&& (save != arr[i - 1]
|| save != arr[i + 1])) {
cout << i + 1;
break ;
}
}
}
int main()
{
int arr[] = { 5, 3, 4, 4, 5 };
int N = sizeof (arr) / sizeof (arr[0]);
printIndex(arr, N);
return 0;
}
|
Java
import java.util.*;
class GFG{
static void printIndex( int arr[],
int N)
{
int []B = new int [N];
int save = - 1 ;
for ( int i = 0 ; i < N; i++)
{
B[i] = arr[i];
}
Arrays.sort(B);
for ( int i = N - 1 ; i >= 1 ; i--)
{
if (B[i] != B[i - 1 ])
{
save = B[i];
break ;
}
}
if (save == - 1 )
{
System.out.print(- 1 + "\n" );
return ;
}
if (save == arr[ 0 ] &&
save != arr[ 1 ])
{
System.out.print( 1 );
}
else if (save == arr[N - 1 ] &&
save != arr[N - 2 ])
{
System.out.print(N);
}
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 ;
}
}
}
public static void main(String[] args)
{
int arr[] = { 5 , 3 , 4 , 4 , 5 };
int N = arr.length;
printIndex(arr, N);
}
}
|
Python3
def printIndex(arr, N):
B = [ 0 ] * (N)
save = - 1
for i in range (N):
B[i] = arr[i]
B = sorted (B)
for i in range (N - 1 , 1 , - 1 ):
if (B[i] ! = B[i - 1 ]):
save = B[i]
break
if (save = = - 1 ):
print ( - 1 + "")
return
if (save = = arr[ 0 ] and
save ! = arr[ 1 ]):
print ( 1 )
elif (save = = arr[N - 1 ] and
save ! = arr[N - 2 ]):
print (N)
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
if __name__ = = '__main__' :
arr = [ 5 , 3 , 4 , 4 , 5 ]
N = len (arr)
printIndex(arr, N)
|
C#
using System;
class GFG{
static void printIndex( int []arr,
int N)
{
int []B = new int [N];
int save = -1;
for ( int i = 0; i < N; i++)
{
B[i] = arr[i];
}
Array.Sort(B);
for ( int i = N - 1; i >= 1; i--)
{
if (B[i] != B[i - 1])
{
save = B[i];
break ;
}
}
if (save == -1)
{
Console.Write(-1 + "\n" );
return ;
}
if (save == arr[0] &&
save != arr[1])
{
Console.Write(1);
}
else if (save == arr[N - 1] &&
save != arr[N - 2])
{
Console.Write(N);
}
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 ;
}
}
}
public static void Main(String[] args)
{
int []arr = { 5, 3, 4, 4, 5 };
int N = arr.Length;
printIndex(arr, N);
}
}
|
Javascript
<script>
function printIndex(arr, N)
{
let B = [];
let save = -1;
for (let i = 0; i < N; i++)
{
B[i] = arr[i];
}
B.sort();
for (let i = N - 1; i >= 1; i--)
{
if (B[i] != B[i - 1])
{
save = B[i];
break ;
}
}
if (save == -1)
{
document.write(-1 + "<br/>" );
return ;
}
if (save == arr[0] &&
save != arr[1])
{
document.write(1);
}
else if (save == arr[N - 1] &&
save != arr[N - 2])
{
document.write(N);
}
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 ;
}
}
}
let arr = [5, 3, 4, 4, 5];
let N = arr.length;
printIndex(arr, N);
</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.
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!
Last Updated :
14 Oct, 2023
Like Article
Save Article