Skip to problem
←

Combinations of R Elements

Medium 0 attempts

Given an array arr and an integer r, return every way to choose r distinct indices in increasing order, displaying the selected values for each choice.

Keep the input's relative order within each combination. The array need not be sorted, and you must not reorder it. Equal values at different indices are separate choices, so identical value arrays may appear more than once in the result.

For arr = [2, 1, 2] and r = 2, return [[2, 1], [2, 2], [1, 2]]. For [1, 1, 1] and r = 2, return [[1, 1], [1, 1], [1, 1]]: the three index pairs are distinct.

Return [[]] when r = 0, and [] when r exceeds the array length. Otherwise include every valid combination once per index choice. The outer result may be in any order; return it rather than printing it.

Function contract

Implement combinations(arr, r).

Output: Return one length-r value array per choice of r distinct indices, preserving increasing index order. Outer array order does not matter; duplicate value arrays from different index choices must remain.

Example 1

Input
arr = [1,2,3]
r = 2
Output
[[1,2],[1,3],[2,3]]

Example 2

Input
arr = [1,2]
r = 0
Output
[[]]

Example 3

Input
arr = [1]
r = 2
Output
[]
Constraints
  • 1 <= arr.length <= 20
  • 0 <= r <= 20
  • Array entries are safe JavaScript integers; duplicate values are allowed.

Backtracking over Increasing Indices

Build a combination by choosing its next index from the unused suffix. Recurse from the following index so no entry is reused and original order is preserved. After returning, remove the last choice before trying another index.

If needed positions remain, the next index cannot exceed arr.length - needed; later indices would leave too few entries to complete the combination. When no positions remain, save a copy of the current values.

Different increasing index sequences produce different branches, even when their values match. Do not deduplicate the output. With r = 0, the initial empty path is saved immediately; with r > arr.length, return no combinations.

javascript
function combinations(arr, r) {
  if (r > arr.length) return [];
  const results = [];
  const current = [];
  function combine(start) {
    const needed = r - current.length;
    if (needed === 0) {
      results.push([...current]);
      return;
    }
    for (let i = start; i <= arr.length - needed; i++) {
      current.push(arr[i]);
      combine(i + 1);
      current.pop();
    }
  }
  combine(0);
  return results;
}

Time: O(1 + C(n, r) × (r + 1)), including copying returned combinations. Here n is arr.length, and C(n, r) is zero when r > n.

Space: O(r + 1) auxiliary space for recursion and the current combination, plus O(C(n, r) × (r + 1)) for the output arrays.

Loading discussion…

Saved in this browser only. Private to you.

JavaScript