FastPrepGenerate Fixed-Size Combinations

Generate Fixed-Size Combinations

Microsoft logoMicrosoft● MediumFULLTIMEONSITE INTERVIEW
Learn

Problem statement

Given integers n and k, return every combination of k distinct values chosen from 1 through n.

List values inside each combination in increasing order, and return the combinations in lexicographic order. A combination differs from a permutation: changing only the order of the same chosen values does not create a new result.

Function

combinations(n: int, k: int) → int[][]

Examples

Example 1

n = 4k = 2return = [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]

Each unordered pair appears once in lexicographic order.

Example 2

n = 5k = 5return = [[1,2,3,4,5]]

Choosing all available values produces one combination.

Constraints

  • 1 <= n <= 20.
  • 1 <= k <= n.
  • The number of returned combinations does not exceed 10000.

Source note: The source image is a source-neutral excerpt of the author-reported prompt.

More Microsoft problems

See Microsoft hiring insights
public int[][] combinations(int n, int k) {
  // Write your code here.
}
n4
k2
expected[[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
Checking account…