Minimum Number of Swaps to Sort an Array

Find the minimum number of swaps required to sort a given array of distinct elements in ascending order.

Input:

T (number of test cases)
For each test case:
N (size of the array)
ARR (N distinct integers)

Output:

For each test case, output a single integer indicating the minimum number of swaps required to sort the array.

Example:

Given the input array [4, 3, 2, 1], the minimum number of swaps required to sort the array is 2. This can be achieved by swapping index 0 with 3 and 1 with 2, resulting in the sorted array [1, 2, 3, 4].

Constraints:

  • 1 ≤ T ≤ 100
  • 1 ≤ N ≤ 1000
  • 0 ≤ ARR[i] ≤ 109

Note that ARR[i] represents the values of the array elements with a time limit of 1 second per test case.

AnswerBot
4mo

The minimum number of swaps required to sort a given array of distinct elements in ascending order.

  • Use a graph-based approach to find cycles in the array for swapping

  • Count the number of swaps needed t...read more

Help your peers!
Select
Add answer anonymously...

Top Software Developer Intern Interview Questions Asked at Hike

Q. Infix to Postfix Conversion Convert a given infix expression, represented as a s...read more
Q. Maximum Difference in Matrix Given an n x n matrix mat[n][n] of integers, find t...read more
Q. Maximum Size Rectangle Sub-matrix with All 1's Problem Statement You are provide...read more
Software Developer Intern Interview Questions
Stay ahead in your career. Get AmbitionBox app
play-icon
play-icon
qr-code
Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+

Reviews

10L+

Interviews

4 Cr+

Salaries

1.5 Cr+

Users

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2025 Info Edge (India) Ltd.

Follow Us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
Profile Image
Hello, Guest
AmbitionBox Employee Choice Awards 2025
Winners announced!
awards-icon
Contribute to help millions!
Write a review
Write a review
Share interview
Share interview
Contribute salary
Contribute salary
Add office photos
Add office photos
Add office benefits
Add office benefits