We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.

- Minimum Swaps 2
- Discussions

# Minimum Swaps 2

# Minimum Swaps 2

+ 0 comments **C#**static int minimumSwaps(int[] arr) { var swapsCount = 0; for(int i = 0; i < arr.Length; i++){ if(arr[i] != i+1){ swap(arr, i, arr[i] -1); i--; swapsCount++; } } return swapsCount; } static void swap(int[] arr, int indexA, int indexB){ var temp = arr[indexA]; arr[indexA] = arr[indexB]; arr[indexB] = temp; }

+ 0 comments Below worked for me.. this took much time...

def minimumSwaps(arr): swaps = 0 #mid = 0 while (listSorted(arr) == False): for i in range(0, len(arr)): if arr[i] != i+1: j = arr[i]-1 if i < j and arr[i] > arr[j]: arr[i], arr[j] = arr[j], arr[i] swaps += 1 elif i > j and arr[i] < arr[j]: arr[i], arr[j] = arr[j], arr[i] swaps += 1 return swaps def listSorted(arr): for i in range(0, len(arr)): if arr[i] != i+1: return False

+ 1 comment **Javascript**function minimumSwaps(arr) { let count=0; for(let i = 0; i < arr.length; i++){ //Skip the below steps for right element if(i+1 == arr[i]) continue; //Find the index of right element let nextIdx = i; while(arr[nextIdx] != i+1) nextIdx++; //Pleace the right element by swaping [arr[nextIdx], arr[i]] = [arr[i], arr[nextIdx]] count++; } return count; }

+ 0 comments Hey folks, Here is my solution in Ruby, anyone has tips to improve?

def minimumSwaps(arr) changes = 0 index = 0 while index < arr.size item = arr[index] position = index + 1 if item != position arr[index], arr[item - 1] = arr[item - 1], arr[index] changes += 1 else index += 1 end end changes end

+ 0 comments So the algorithm worked but because I had a print statement in there to help me debug it caused a runtime error with no further explanation. Removing that print statement caused it to work:

def minimumSwaps(arr): swaps = 0 i = 0 while i < len(arr): if arr[i] != i + 1: a = arr[i] b = arr[arr[i]-1] print(i, arr, a, b) arr[i], arr[a - 1] = b, a swaps += 1 continue i += 1 return swaps

Breaks but commenting out the print statement works.

HackerRank really needs to clarify certain things. I had to try a lot of things to figure out this was the issue.

Load more conversations

Sort 2356 Discussions, By:

Please Login in order to post a comment