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

Permutations [Medium]

https://leetcode.com/problems/permutations/

Input: [1,2,3]
Output:
[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]
def permute(A: Array[Int]): Set[List[Int]] = {

  def go(arr: Array[Int]): Set[List[Int]] =
    arr match {
      case Array(fst, snd) =>
        Set(List(fst, snd), List(snd, fst))
      case _ =>
        0.until(arr.length).foldLeft(Set.empty[List[Int]]) { (set, i) =>
          val next = arr.slice(0, i) ++ arr.slice(i + 1, arr.length)
          set ++ go(next).map(arr(i) :: _)
        }
    }

  if (A.length == 1) Set(List(A(0)))
  else go(A)
}
PreviousMax Contiguous Subarray (Kadane's) [Medium (just cause its tricky)]NextNext Permutation [Medium]

Last updated 6 years ago

Was this helpful?