KatInterview

All Orderings and Subsets of Distinct Integers

Arrays & HashingAuto-graded · 21 test cases
MediumAuto-gradedArrays & Hashingbacktrackingrecursioncombinatorics

Last 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 in nums, listed in lexicographic order.
  • "combinations": all possible ways to choose exactly k elements from nums (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 nums are 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.