Functional Programming
  • Preface
  • Getting Started
  • Sorting
    • Bubble Sort
    • Merge Sort
    • Insertion Sort
  • Stacks
    • Stack
  • Queues
    • Queue
    • Binary Heap (Priority Queue)
  • Trees
    • Binary Tree (Unbalanced)
    • Prefix Trie
  • Graphs
    • Undirected
    • Directed
    • Edge Weighted
  • Dynamic Programming
    • Knapsack
    • Longest Common Substring
    • Staircase
  • Leetcode/InterviewBit
    • 2 Sum [Easy]
    • Longest Valid Parentheses [Medium-Hard]
    • Kth Smallest Element [Medium]
    • Max Profit [2 variations: 1st Easy 2nd Hard]
    • Pretty Print 2D Matrix [Easy]
    • Max Contiguous Subarray (Kadane's) [Medium (just cause its tricky)]
    • Permutations [Medium]
    • Next Permutation [Medium]
Powered by GitBook
On this page

Was this helpful?

  1. Leetcode/InterviewBit

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
  }

}
PreviousPermutations [Medium]

Last updated 6 years ago

Was this helpful?