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.
Yes, the performance killer is the indexOf on the array and the update of the array when you do the swap so you have to try avoiding that this is my recursive fn solution in Scala and goes really fast
def minimumSwaps(arr: Array[Int]): Int = {
@tailrec
def rec(lt: List[Int], sorting: Vector[Int], swap: Int, smallest: Int, track: Map[Int, Int]): Int = {
lt match {
case h :: t if h < smallest =>
val replaced: Int = track(h)
rec(replaced :: t, sorting, swap, smallest, track - h)
case h :: t if h != smallest =>
val newTrack = track + (smallest -> h)
rec(t, sorting :+ smallest, swap + 1, smallest + 1, newTrack)
case h :: t if h == smallest =>
rec(t, sorting :+ smallest, swap, smallest + 1, track)
case _ => swap
}
}
rec(arr.toList, Vector(), 0, 1, Map())
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Minimum Swaps 2
You are viewing a single comment's thread. Return to all comments →
Yes, the performance killer is the indexOf on the array and the update of the array when you do the swap so you have to try avoiding that this is my recursive fn solution in Scala and goes really fast
def minimumSwaps(arr: Array[Int]): Int = {
}