All Orderings and Subsets of Distinct Integers
Arrays & HashingAuto-graded · 21 test casesLast updated
Tests recursive backtracking by building every permutation and every k-length subset of a list of distinct integers in a single function.
Problem
Given a list of distinct integers nums and a non-negative integer k, return a dictionary with two keys:
"permutations": all possible orderings of every element innums, listed in lexicographic order."combinations": all possible ways to choose exactlykelements fromnums(order does not matter), each subset listed in increasing order, with subsets ordered lexicographically.
Both outputs must be based on the sorted version of nums, regardless of the order the elements appear in the input.
Output format
{
"permutations": [[...], [...]],
"combinations": [[...], [...]]
}
If k is outside the range [0, len(nums)], return an empty list for "combinations".
If k == 0, the combinations list contains exactly one entry: the empty subset [].
Constraints
1 <= len(nums) <= 8- All elements of
numsare distinct integers. 0 <= k <= len(nums)
Examples
Example 1
Input: list_orderings_and_subsets([1, 2], 2)
Output: {'permutations': [[1, 2], [2, 1]], 'combinations': [[1, 2]]}
Example 2
Input: list_orderings_and_subsets([1, 2, 3], 2)
Output: {'permutations': [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]], 'combinations': [[1, 2], [1, 3], [2, 3]]}
Example 3
Input: list_orderings_and_subsets([3, 1, 2], 1)
Output: {'permutations': [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]], 'combinations': [[1], [2], [3]]}
Hints
Hint 1
Sort the input first — both outputs are defined in terms of the sorted order, and sorting makes it straightforward to generate results in lexicographic order naturally.
Hint 2
For permutations, use a boolean `used` array to track which elements have already been placed in the current path. When the path length equals `len(nums)`, you have a complete permutation — append a copy, not the list itself.
Hint 3
For combinations, pass a `start` index into the recursive call instead of a `used` array. Only iterate from `start` onward, and advance `start` to `i + 1` when you recurse. This ensures each subset is generated exactly once in increasing index order. You can also prune early: stop the loop when fewer elements remain than slots left to fill.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Both outputs are built with the same core technique: recursive backtracking. You grow a partial result (path) one element at a time. When it reaches the target length, you save a copy and return. Then you undo the last choice and try the next candidate — hence "backtrack."
The two sub-problems differ in one rule: which candidates are legal at each step.
Step 1 — Sort the input
Sorting nums first ensures both outputs come out in lexicographic order without any post-processing. The sample cases confirm this: [3, 1, 2] produces the same output as [1, 2, 3].
Step 2 — Permutations
Every element must appear exactly once in each ordering. A used boolean array (one entry per index) tracks which elements are already in the current path. At each recursion level, iterate over all indices and skip any that are marked used. When len(path) == n, all elements are placed — save a copy of the path.
Why no duplicates? Each leaf of the recursion tree corresponds to a unique sequence of choices (index 0 first, then index 1, …). Since the input has distinct elements and we never reuse an index, no two paths produce the same list.
Step 3 — Combinations
Order does not matter here, so [1, 2] and [2, 1] are the same subset — we only want one of them. The trick is to only ever pick elements at indices strictly after the last one picked. A start parameter carries this lower bound into each recursive call. When len(path) == k, save a copy.
A small pruning step avoids dead-end branches: if the number of elements remaining (n - start) is less than the number of slots still to fill (k - len(path)), stop immediately. This doesn't change correctness but eliminates wasted work.
Edge cases
k == 0:build_combinationsfires the base case immediately on the first call (empty path has length 0 == k), appending[]. The result is[[]]— one empty subset. Returning[]here is a common mistake.k == len(nums): produces one combination containing every element in sorted order.koutside[0, n]: the guardif 0 <= k <= nis false, sobuild_combinationsis never called and the result is[].
Why copying matters
path.append(path[:]) not path.append(path). The same list object is mutated throughout the entire recursion. Storing a reference would leave every entry in the result pointing to the same eventually-empty list.
Complexity
Permutations
- n! complete paths, each copied in O(n).
- Time: O(n · n!)
- Auxiliary space: O(n) for the recursion stack, path, and used array. Output itself is O(n · n!).
Combinations
- C(n, k) results, each copied in O(k).
- Time: O(k · C(n, k)) with the pruning.
- Auxiliary space: O(k) for the recursion stack and path. Output is O(k · C(n, k)).
With n ≤ 8 the worst cases are 8! = 40 320 permutations and C(8, 4) = 70 combinations — both trivial.
Reference solution
from typing import Dict, List
def list_orderings_and_subsets(nums: List[int], k: int) -> Dict[str, List[List[int]]]:
values = sorted(nums)
n = len(values)
# --- Permutations ---
permutations: List[List[int]] = []
used = [False] * n
perm_path: List[int] = []
def build_permutations() -> None:
if len(perm_path) == n:
permutations.append(perm_path[:])
return
for i in range(n):
if not used[i]:
used[i] = True
perm_path.append(values[i])
build_permutations()
perm_path.pop()
used[i] = False
build_permutations()
# --- Combinations ---
combinations: List[List[int]] = []
comb_path: List[int] = []
def build_combinations(start: int) -> None:
if len(comb_path) == k:
combinations.append(comb_path[:])
return
remaining_needed = k - len(comb_path)
# Prune: not enough elements left to complete a combination
if n - start < remaining_needed:
return
for i in range(start, n):
comb_path.append(values[i])
build_combinations(i + 1)
comb_path.pop()
if 0 <= k <= n:
build_combinations(0)
return {
"permutations": permutations,
"combinations": combinations,
}