• + 0 comments

    solution in scala

    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
        }
      }
    }