Facebook Interview Question: Print out all combinations of... | Glassdoor

Interview Question

Software Engineer Interview

Print out all combinations of k numbers out of 1...N e.g

 . when k = 2, n = 4 Print out 12, 13, 14, 23, 24, 34
Tags:
analytical
Answer

Interview Answer

2 Answers

0

int[][] chart = new int[factorial(n) / factorial(k) / factorial(n - k)][k];
        for (int i = 0; i < k; i++)
            chart[0][i] = i + 1;
        for (int r = 1; r < chart.length; r++) {
            for (int i = 0; i < k; i++)
                chart[r][i] = chart[r - 1][i];

            for (int i = 0; i < k ; i++) {
                if (chart[r][k - i - 1] < n - i) {
                    chart[r][k - i - 1]++;
                    for (int c = k - i; c < k; c++)
                        chart[r][c] = chart[r][c - 1] + 1;
                    break;
                }
            }
        }

        for (int r = 0; r < chart.length; r++) {
            for (int c = 0; c < chart[r].length; c++)
                System.out.print(chart[r][c] + " ");
            System.out.println();
        }

Anonymous on Sep 24, 2010
0

public static void NumbersPuzzle(String prefix, int last_num, int digits)
   {
       for(int j=1;j<=last_num;j++)
       {
           if((prefix+j).length()<digits)
               NumbersPuzzle((prefix+j),last_num,digits);
           else
               System.out.println(prefix+j);
       }
   }

NumbersPuzzle("",4,2);

pradeep on Jul 31, 2011

Add Answers or Comments

To comment on this, Sign In or Sign Up.