Problem statement
In this problem we are given with an array consisting of permutation within the range[1, N] and the goal is to check if we can reduce the array to single non-zero element by performing some set of operations that is we can Select indices ‘i’ and ‘j’ such that i < j and arr[i] < arr[j] and then convert one of the two elements to 0 after all the operations if we are able to reduce the array to a single non-zero element then print “yes” followed by the chosen index elements and the number of operation and if there is no way to reduce the array to single non-zero element print “no”.
Example 1
Input
Let the input array be like arr = [ 12,14,16,11,13,15 ]
Output:
Yes
0 1 1
0 2 2
3 4 3
0 4 4
0 5 5
Explanation:
In the first operation choose the elements 12 and 14 at indices 0 and 1. Convert the element 14 at index 1 to 0, arr[] = {12, 0, 16, 11, 13, 15}
In the second operation choose the elements 12 and 16 at indices 0 and 2. Convert the element 16 at index 2 to 0, arr[] = {12, 0, 0, 11, 13, 15}
In the third operation choose the elements 11 and 13 at indices 3 and 4. Convert the element 11 at index 3 to 0, arr[] = {12, 0, 0, 0, 13, 15}
In the fourth operation choose the elements 12 and 13 at indices 0 and 4. Convert the element 13 at index 4 to 0, arr[] = {12, 0, 0, 0, 0, 5}
In the fifth operation choose the elements 12 and 15 at indices 0 and 5. Convert the element 15 at index 5 to 0, arr[] = {12, 0, 0, 0, 0, 0}
So, after 5 successful operations we are able to reduce the array to a single non-zero element
Example 2
Input
Let the input array be like arr = [ 9, 7, 4, 2]
Output
No
Explanation
There is no way to reduce the array to a single non-zero element so we will simply print “no” for this test case
Also see, Euclid GCD Algorithm
Approach
To reduce the array to a single non-zero element the main goal is to convert all the elements of the array to 0 except the first element and the last element. So first we will make all the elements of the array as 0 from [1, size - 2] by performing the set of rules given in the problem statement and will try to eliminate the first element or last element in the last iteration.
While choosing which element to make 0 try to follow these steps i.e If 0th index is not a part of the chosen indices on which you are working, then replace the smaller of the two elements to 0 and if 0th index is a part of the chosen index then try to convert the other indices elements as zero