Amazon Interview Question
Software Engineer / DevelopersCountry: United States
vector returnSubsets(vector items, int k) {
int[] result;
if (k < 1 || items.length < k) {
return null;
}
if (k == 1) {
return items;
}
if (items.length == k) {
vector result = createSetFromItems(items)
}
for (int i=0;i<items.length;i++) {
vector exceptItems = getItemsExcept(items, i);
vector result;
result += returnSubsets(exceptItems, k);
result += mergeItem(items[k], returnSubsets(exceptItems, k-1));
return result;
}
}
private static ArrayList<ArrayList<Integer>> findSubArrays(Integer subArraySize, ArrayList<Integer> array) {
ArrayList<ArrayList<Integer>> subArray = new ArrayList<ArrayList<Integer>>();
int i=0;
while ((i+subArraySize)<= array.size()){
for (int j=i; j<=(array.size() - subArraySize); j++){
ArrayList<Integer> aSubArray = new ArrayList<Integer>();
aSubArray.add(array.get(i));
for (int k=1; k<subArraySize; k++){
aSubArray.add(array.get(j+k));
}
subArray.add(aSubArray);
}
i++;
}
return subArray;
}
#include <iostream>
using namespace std;
// function to increment the counters
int inc(int i, int a[], int n,int k)
{
if (i<=0)
{
return (++a[0]);
}
a[i]++;
if(a[i] >= (n - (k-i)))
{
a[i] = inc(i-1, a, n, k) + 1;
}
return a[i];
}
// function to check the end of loop
bool end_of_loop(int a[], int k, int n)
{
bool res = true;
for(int i = 0; i < k; i++)
{
res = res && (a[i] >= (n -(k+i-1)));
}
return res;
}
int main()
{
// input array
int arr[] = {1,2,3,4,5,6,7,8};
// total number of elements in array
int N = 8;
// combination size
int K = 4;
// indexes of size K
int a[K];
for(int i = 0; i<K;i++)
{
a[i] = i;
}
bool loop = end_of_loop(arr,K,N-1);
int count = 0;
//loop till all combinations are printed
while(!loop)
{
for(int i = 0; i < K; i++)
{
cout << arr[a[i]] <<" - ";
}
cout <<endl;
count++;
// increment the counters
inc(K-1, a, N,K-1);
// check for end of loop
loop = end_of_loop(a,K,N-1);
}
// total no of combinations
cout << "Count -- "<<count<<endl;
return 0;
}
The easiest way to see this example is to note that it is just a special case of a combination. Here is a solution that will print out the results of the subsets as specified. The easiest way to do combinations is via recursion, hence my solution uses recursion. It is written in C++, and tested using g++ compiler on Linux.
- barry.steyn April 09, 2013