Hackerank: Interview Prep Kit: Minimum Swap 2.

Samuel Ezedi
2 min readJan 17, 2021

--

Hello friends, here again with another problem I found on Hackerank, so stay connected, let’s solve this one.

Problem

You are given an unordered array consisting of consecutive integers  [1, 2, 3, ..., n] without any duplicates. You are allowed to swap any two elements. You need to find the minimum number of swaps required to sort the array in ascending order.For example, given the array arr = [7,1,3,2,4,5,6] we perform the following steps:
Hackerank
It took 5 swaps to sort the array.

Function Description

Complete the function minimumSwaps in the editor below. It must return an integer representing the minimum number of swaps to sort the array.minimumSwaps has the following parameter(s):* arr: an unordered array of integers

Input Format

The first line contains an integer n, the size of arr
The second line contains n space-separated integer arr[i].

Output Format

Return the minimum number of swaps to sort the given array.

Sample Input 0

4
4 3 1 2

Sample Output 0

3

Explanation 0

Given array arr : [4,3,1,2]
After swapping (0,2) we get arr : [1,3,4,2]
After swapping (1,2) we get arr : [1,4,3,2]
After swapping (1,3) we get arr : [1,2,3,4]
So, we need a minimum of 3 swaps to sort the array in ascending order.

Sample Input 1

5
2 3 4 1 5

Sample Output

3

Explanation 1

Given array arr : [2,3,4,1,5]
After swapping (2,3) we get arr : [2,4,1,4,5]
After swapping (0,1) we get arr : [3,2,1,4,5]
After swapping (0,2) we get arr : [1,2,3,4,5]
So, we need a minimum of 3 swaps to sort the array in ascending order.

Sample Input 2

7
1 3 5 2 4 6 7

Sample Output 2

3

Explanation 2

Given array arr : [1,3,5,2,4,6,7]
After swapping (1,3) we get arr : [1,2,5,3,4,6,7]
After swapping (2,3) we get arr : [1,2,3,5,4,6,7]
After swapping (3,4) we get arr : [1,2,3,4,5,6,7]
So, we need a minimum of 3 swaps to sort the array in ascending order.

Solution in JS

Solution in Dart

Thanks for your time. Please take time to review the problem before looking at the solution. Remember this is for educational purposes and nothing more. Also, you can follow me here on Linkedin and, on Twitter.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Samuel Ezedi
Samuel Ezedi

No responses yet

Write a response