Minimum Swaps 2 HackerRank solution: Looking for Minimum Swaps 2 solution for Hackerrank problem? Get solution with source code and detailed explainer video
You are given an unordered array consisting of consecutive integers \epsilon [1, 2, 3, …, n] without any duplicates. You are allowed to swap any two elements. Find the minimum number of swaps required to sort the array in ascending order.
Example
arr = [7,1,3,2,4,5,6]
Perform the following steps:
i arr swap (indices)
0 [7, 1, 3, 2, 4, 5, 6] swap (0,3)
1 [2, 1, 3, 7, 4, 5, 6] swap (0,1)
2 [1, 2, 3, 7, 4, 5, 6] swap (3,4)
3 [1, 2, 3, 4, 7, 5, 6] swap (4,5)
4 [1, 2, 3, 4, 5, 7, 6] swap (5,6)
5 [1, 2, 3, 4, 5, 6, 7]
It took 5 swaps to sort the array.Go to problem statement
Explanation Video:
Youtube Channel partner: CodingCart
Mentor: Satyendra Jaiswal
Langauge: Python
Source Code: for triplets
function
# Complete the minimumSwaps function below.
def minimumSwaps(arr):
count=0
i=0
while i< len(arr):
index=arr[i]-1 # n= arr[i] index=n-1=arr[i]-1
# print('bef=',arr,i)
if arr[i]!=arr[index]: #n!=[n-1]
arr[i],arr[index]=arr[index],arr[i]
count+=1
else:
i+=1
# print('aft=',arr)
return count
Full Source Code: Minimum Swaps 2 HackerRank Solution
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the minimumSwaps function below.
def minimumSwaps(arr):
count=0
i=0
while i< len(arr):
index=arr[i]-1 # n= arr[i] index=n-1=arr[i]-1
# print('bef=',arr,i)
if arr[i]!=arr[index]: #n!=[n-1]
arr[i],arr[index]=arr[index],arr[i]
count+=1
else:
i+=1
# print('aft=',arr)
return count
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
arr = list(map(int, input().rstrip().split()))
res = minimumSwaps(arr)
fptr.write(str(res) + '\n')
fptr.close()
Like this article? Follow us on Facebook and LinkedIn. You can also subscribe to our Youtube Channel.
This post is in partner with CodingCart.