To check if swapping two indices places them in their correct position
if ( pos3 != pos1 ) { indices . push_back ( { pos1 , pos2 , pos3 } ) ; swap ( arr [ pos1 ] , arr [ pos2 ] ) ; swap ( arr [ pos1 ] , arr [ pos3 ] ) ; pos . erase ( find ( pos . begin ( ) , pos . end ( ) , pos2 ) ) ; pos . erase ( find ( pos . begin ( ) , pos . end ( ) , pos3 ) ) ; if ( arr [ pos1 ] == pos1 ) { pos . erase ( find ( pos . begin ( ) , pos . end ( ) , pos1 ) ) ; } } else { if ( pos3 == * pos . begin ( ) ) { if ( * pos . begin ( ) != pos . back ( ) ) { auto it = ++ pos . begin ( ) ; pos3 = * ( it ) ; if ( * it != pos . back ( ) && pos3 == pos2 ) { pos3 = * ( ++ it ) ; } else if ( * it == pos . back ( ) && pos3 == pos2 ) { flag = true ; break ; } } else { flag = true ; break ; } } indices . push_back ( { pos1 , pos2 , pos3 } ) ; swap ( arr [ pos1 ] , arr [ pos2 ] ) ; swap ( arr [ pos1 ] , arr [ pos3 ] ) ; pos . erase ( find ( pos . begin ( ) , pos . end ( ) , pos2 ) ) ; } } if ( arr [ i ] != i ) { i -- ; } } if ( flag == true || indices . size ( ) > moves ) { cout << " Not ▁ Possible " << endl ; } else { cout << indices . size ( ) << endl ;