Data Structures & AlgorithmsHardAmazon · Microsoft coding round

Problem: Generating all permutations of an n-element array via backtracking takes how much time, and why?

  1. A. O(n!) exactly, with no extra factor
  2. B. O(n^2), since only pairs are swapped
  3. C. O(2^n), same as subsets
  4. D. O(n * n!), since there are n! permutations and each takes O(n) to build/copy

Correct answer: D. O(n * n!), since there are n! permutations and each takes O(n) to build/copy

There are n! distinct orderings, and constructing/copying each one (e.g. appending n elements into a result list) costs O(n) extra, giving O(n * n!) total work.

More Coding Interview Problems questions

Exams that ask this topic