![]() |
VOOZH | about |
Given two integers S and T and an array arr that contains elements from 1 to N in unsorted fashion. The task is to find the minimum number of moves to move Sth element to the Tth place in the array with the following operation:
A single move consists of the following
// Initially b[] = {1, 2, 3, ..., N}
// arr[] is input array
for (i = 1..n)
temp[arr[i]] = b[i]
b = temp
If not possible then print -1 instead.
Examples:
Input: S = 2, T = 1, arr[] = {2, 3, 4, 1}
Output: 3
N is 4 (size of arr[])
Move 1: b[] = {4, 1, 2, 3}
Move 2: b[] = {3, 4, 1, 2}
Move 3: b[] = {2, 3, 4, 1}
Input: S = 3, T = 4, arr[] = {1, 2, 3, 4}
Output: -1
N is 4 (Size of arr[])
Regardless of how many moves are made, the permutation would remain the same.
Approach: The important observation here is that we are only concerned with the position of a single element, and not the entire array. So at each move we move the element at position S to the position arr[S], until we reach Tth position.
Since there are at most N distinct places that we can reach, if we don't reach T within N moves, it would mean we can never reach it.
Below is the implementation of the above approach:
3