Minimum number of swaps required to sort an array
You have been given an array 'ARR' of 'N' distinct elements.
Your task is to find the minimum no. of swaps required to sort the array.
For example:
For the given input array [4, 3, 2, 1], the minimum no. of swaps required to sort the array is 2, i.e. swap index 0 with 3 and 1 with 2 to form the sorted array [1, 2, 3, 4].
Input Format:
The first line of input contains an integer ‘T’ representing the number of test cases. Then the test cases follow.
The first line of each test case contains an integer ‘N’ representing the size of the input array.
The second line of each test case contains the 'N' elements of the array separated by a single space.
Output Format:
For each test case, print a single line containing a single integer which represents the minimum no. of swaps required to sort the array.
The output for each test case is in a separate line.
Note:
You do not need to print anything; it has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 100
1 <= N <= 1000
0 <= ARR[i] <= 10 ^ 9
Where 'ARR[i]' is the value of the input array elements.
Time Limit: 1 sec
CodingNinjas
author
2y
Approach :
1) The basic idea is to make a new array (called temp), which is a sorted form of the input array.
2) Make a map that stores the elements and their corresponding index, of the input array. So...read more
CodingNinjas
author
2y
Naive Approach
While iterating over the array, check the current element, and if not in the correct place, replace that element with the index of the element which should have come in this place.
Below...read more
CodingNinjas
author
2y
Optimized Approach
The basic idea is to make a new array (called temp), which is a sorted form of the input array. We know that we need to transform the input array to the new array (temp) in the minim...read more
Add answer anonymously...
Top Bosch Global Software Technologies Associate Software Engineer interview questions & answers
Popular interview questions of Associate Software Engineer
Top HR questions asked in Bosch Global Software Technologies Associate Software Engineer
>
Bosch Global Software Technologies Associate Software Engineer Interview Questions
Stay ahead in your career. Get AmbitionBox app
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+
Reviews
4 L+
Interviews
4 Cr+
Salaries
1 Cr+
Users/Month
Contribute to help millions
Get AmbitionBox app