• Amazon Interview Questions
  • Google Interview Questions
  • Microsoft Interview Questions

Problem Source

Given two integers n and k, return all possible combinations of k numbers out of 1…n.


Input: n = 4, k = 2.

Output: [


This problem is efficiently solved by backtracking algorithm. Backtracking is a general algorithm for finding all (or some) solutions to some computational problems, notably constraint satisfaction problems, that incrementally builds candidates to the solutions, and abandons a candidate (“backtracks”) as soon as it determines that the candidate cannot possibly be completed to a valid solution.

By using the above technique, we implement our algorithm.

From the starting integer i.e. 1 we generate an array of combinations of integers untill we reach the length of an array, k = 2. we generate every possible solutions, if it’s giving us the required combination, we will add it to the answer array.

After going through every possible combinations and adding it to the array, we will simply return the answer array.



class Solution {
    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> result = new ArrayList();
        int[] nums = new int[n];
        for (int i = 0; i < n; i++) {
            nums[i] = i + 1;
        backtracking(k, 0, nums, new ArrayList(), result);
        return result;

    void backtracking(int k, int start, int[] nums, List<Integer> curr, List<List<Integer>> result) {
        if (curr.size() == k) {
            result.add(new ArrayList(curr));
        } else if (curr.size() < k) {
            for (int i = start; i < nums.length; i++) {
                backtracking(k, i + 1, nums, curr, result);
                curr.remove(curr.size() - 1);

Complexity Analysis:

  • Time Complexity: O(kCkn).

  • Space Complexity: O(kCkn).

Scroll to Top
[gravityforms id="5" description="false" titla="false" ajax="true"]