- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

Suppose we have a list of distinct numbers; we have to find the minimum number of swaps required to sort the list in increasing order.

So, if the input is like nums = [3, 1, 7, 5], then the output will be 2, as we can swap 3 and 1, then 5 and 7.

To solve this, we will follow these steps:

- sort_seq := sort the list nums
- table := a new map
- for each index i and value n in nums, do
- table[n] := i

- swaps := 0
- for i in range 0 to size of nums, do
- n := nums[i]
- s_n := sort_seq[i]
- s_i := table[s_n]
- if s_n is not same as n, then
- swaps := swaps + 1
- nums[s_i] := n
- nums[i] := s_n
- table[n] := s_i
- table[s_n] := i

- return swaps

Let us see the following implementation to get better understanding:

class Solution: def solve(self, nums): sort_seq = sorted(nums) table = {} for i, n in enumerate(nums): table[n] = i swaps = 0 for i in range(len(nums)): n = nums[i] s_n = sort_seq[i] s_i = table[s_n] if s_n != n: swaps += 1 nums[s_i] = n nums[i] = s_n table[n] = s_i table[s_n] = i return swaps ob = Solution() nums = [3, 1, 7, 5] print(ob.solve(nums))

[3, 1, 7, 5]

2

- Related Questions & Answers
- Minimum number of swaps required to sort an array in C++
- Program to find minimum swaps required to make given anagram in python
- Program to count number of swaps required to group all 1s together in Python
- Program to count number of minimum swaps required to make it palindrome in Python
- Program to count number of swaps required to change one list to another in Python?
- Program to find number of given operations required to reach Target in Python
- Program to find minimum number of operations required to make one number to another in Python
- Program to find minimum number of hops required to reach end position in Python
- Program to find minimum number of buses required to reach final target in python
- Program to find minimum number of flips required to have alternating values in Python
- Program to find number of steps required to change one word to another in Python
- Program to find minimum number of steps required to catch the opponent in C++
- Program to find minimum number of operations required to make lists strictly Increasing in python
- Program to find minimum number of movie theatres required to show all movies in python
- Program to find length of longest consecutive sequence in Python

Advertisements