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.
def biggerIsGreater(w: String): String = {
var i = w.length - 1
val charMap = mutable.Map[Char, Int]()
var replacePos: Option[Int] = None
while(i >= 0 && replacePos.isEmpty){
charMap(w(i)) = i
val nextLargest = charMap
.filter { case (k, _) => k > w(i) }
.minByOption { case (k, _) => k }
replacePos = nextLargest match{
case None => {
i = i - 1
None
}
case Some(s) => Some(charMap(s._1))
}
}
replacePos match{
case None => "no answer"
case Some(s) => {
val switched = w.updated(s, w(i)).updated(i, w(s))
// sort after the initial switch to efficiently arrive at the smallest possible substring
val (prefix, suffix) = switched.splitAt(i + 1)
val sortedSuffix = suffix.sorted
prefix + sortedSuffix
}
}
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Bigger is Greater
You are viewing a single comment's thread. Return to all comments →
solution in scala