Posts

Showing posts from May, 2022

New Year Chaos - Hackerrank C++ Sol

 Question Link :  https://www.hackerrank.com/challenges/new-year-chaos/problem?isFullScreen=true&h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=arrays void minimumBribes (vector< int > A) { int n = A.size() ; int swaps = 0 ; for ( int i = n - 1 ; i >= 0 ; i--) { if (A[i] != (i + 1 )) { if (((i - 1 ) >= 0 ) && A[i - 1 ] == (i + 1 )) { swaps++ ; swap(A[i] , A[i- 1 ]) ; } else if (((i - 2 ) >= 0 ) && A[i - 2 ] == (i + 1 )) { swaps += 2 ; A[i - 2 ] = A[i - 1 ] ; A[i - 1 ] = A[i] ; A[i] = i + 1 ; } else { printf( "Too chaotic \n " ) ; return; } } } printf( "%d \n " , swaps) ; return; }