Next Permutation [Medium]

https://leetcode.com/problems/next-permutation/

Implement next permutation, which rearranges numbers into the 
lexicographically next greater permutation of numbers.

If such arrangement is not possible, it must rearrange it as the lowest 
possible order (ie, sorted in ascending order).

The replacement must be in-place and use only constant extra memory.

Here are some examples. Inputs are in the left-hand column and its
corresponding outputs are in the right-hand column.

1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1
def nextPermutation(nums: Array[Int]): Array[Int] = {
  
  type Index = Int
  type Num = Int

  @tailrec
  def backwards(i: Index): Option[Index] =
    if (i == 0) None
    else if (nums(i - 1) <= nums(i)) Some(i - 1)
    else backwards(i - 1)

  @tailrec
  def forwards(
    i: Index,
    num: Num,
    min: (Num, Index) = (Int.MaxValue, Int.MaxValue)): Index =
    if (i == nums.length) min._2
    else if (nums(i) > num)
      forwards(i + 1, num, if (nums(i) < min._1) nums(i) -> i else min)
    else forwards(i + 1, num, min)

  backwards(nums.length - 1).fold(nums.reverse) { startI =>
    val endI = forwards(startI + 1, nums(startI))
    val arr = nums.updated(startI, nums(endI)).updated(endI, nums(startI))
    arr.slice(0, startI + 1) ++ arr.slice(startI + 1, arr.length).reverse
  }

}

Last updated

Was this helpful?