Data Structures & AlgorithmsHardAmazon · Microsoft coding round
Problem: Generating all permutations of an n-element array via backtracking takes how much time, and why?
- A. O(n!) exactly, with no extra factor
- B. O(n^2), since only pairs are swapped
- C. O(2^n), same as subsets
- 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
- Problem: In the N-Queens backtracking search, what pruning technique keeps the search from degenerating into a full O(N^N) brute force?
- Problem: Which best explains why a monotonic stack is the standard technique for the 'next greater element' problem, giving O(n) overall…
- Problem: A sliding window maximum over an array of size n with window size k is computed with a monotonic deque. What is its time…
- Problem: Two Sum on an unsorted array can be solved in O(n) using a hash map, or in O(n log n) using sort-and-two-pointers. Why might the…
- Problem: Three Sum (find all triplets summing to zero) is commonly solved by sorting the array and then applying two pointers for each…
- Problem: Which statement about Dijkstra's algorithm and negative edge weights is correct?